impact-chatbot 3.0.0 → 3.1.1

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.esm.js CHANGED
@@ -16,7 +16,7 @@ import DOMPurify from 'dompurify';
16
16
  import { useNavigate, useLocation } from 'react-router-dom-v5-compat';
17
17
  import RefreshIcon from '@mui/icons-material/Refresh';
18
18
  import styled from 'styled-components';
19
- import { CircularProgress, Typography, Grid } from '@mui/material';
19
+ import { CircularProgress, Typography, Grid, Box, IconButton, Accordion, AccordionSummary, AccordionDetails } from '@mui/material';
20
20
  import { Button, Modal, Slider, Select, DatePicker, DateRangePicker, Checkbox, RadioButtonGroup, Input, Tabs, Loader, Prompt, Tooltip, ChatBotComponent } from 'impact-ui-v3';
21
21
  import isArray$2 from 'lodash/isArray';
22
22
  import isEmpty$2 from 'lodash/isEmpty';
@@ -38,10 +38,19 @@ import 'highcharts/esm/modules/heatmap.js';
38
38
  import 'highcharts/esm/modules/pareto.js';
39
39
  import makeStyles$1 from '@mui/styles/makeStyles';
40
40
  import ChevronRightIcon$1 from '@mui/icons-material/ChevronRight';
41
+ import DescriptionOutlinedIcon from '@mui/icons-material/DescriptionOutlined';
42
+ import OpenInNewIcon from '@mui/icons-material/OpenInNew';
41
43
  import FormatListBulletedOutlinedIcon from '@mui/icons-material/FormatListBulletedOutlined';
42
44
  import PsychologyOutlinedIcon from '@mui/icons-material/PsychologyOutlined';
43
45
  import SaveOutlinedIcon from '@mui/icons-material/SaveOutlined';
44
46
  import 'react-dates/lib/css/_datepicker.css';
47
+ import { createPortal } from 'react-dom';
48
+ import VisibilityOutlinedIcon from '@mui/icons-material/VisibilityOutlined';
49
+ import OpenInFullIcon from '@mui/icons-material/OpenInFull';
50
+ import CloseFullscreenIcon from '@mui/icons-material/CloseFullscreen';
51
+ import CloseIcon from '@mui/icons-material/Close';
52
+ import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
53
+ import ArrowForwardIcon from '@mui/icons-material/ArrowForward';
45
54
 
46
55
  /**
47
56
  * Internal HTTP client module for impact-chatbot.
@@ -752,6 +761,30 @@ const uploadFile = async (payload) => {
752
761
  return null;
753
762
  }
754
763
  };
764
+ /** Saves a skill for the signed-in user: its SKILL.md and the files it refers to, each keyed by its path in
765
+ * the skill's folder ({"SKILL.md": text, "references/x.md": text}). The agent checks it as its harness would
766
+ * serve it and answers {name, version, characters, files, missing_files, trigger, trigger_said, turn_on}; a
767
+ * skill it refuses is a 422 whose detail says why. Errors reach the caller, which shows them. */
768
+ const uploadSkill = async (files, baseUrl) => {
769
+ return axiosInstance({
770
+ url: `${baseUrl}/chatbot/agent/skills`,
771
+ method: 'POST',
772
+ data: { files },
773
+ });
774
+ };
775
+ /** Whether the agent takes skill uploads: its /info answer carries skills.upload beside the cards. Any
776
+ * failure, or an agent that does not say so, is false (no "Upload Skill" item). */
777
+ const fetchSkillUploadOn = async (baseUrl) => {
778
+ try {
779
+ const response = await fetchAgentsInfo(baseUrl);
780
+ const body = response?.data || {};
781
+ return body?.skills?.upload === true || body?.data?.skills?.upload === true;
782
+ }
783
+ catch (error) {
784
+ console.error('fetchSkillUploadOn error:', error);
785
+ return false;
786
+ }
787
+ };
755
788
  const triggerRefresh = async (baseUrl) => {
756
789
  try {
757
790
  return httpRequest({
@@ -811,6 +844,21 @@ const getTableRecords = async (payload, baseUrl, tableName) => {
811
844
  return null;
812
845
  }
813
846
  };
847
+ /** A read for a generated surface (frame protocol iui:query): the agent runs one read tool as the signed-in
848
+ * user and answers {rows, total}. */
849
+ const postUiQuery = async (payload, baseUrl) => {
850
+ try {
851
+ return httpRequest({
852
+ url: `${baseUrl}/chatbot/agent/ui-query`,
853
+ method: 'POST',
854
+ data: payload,
855
+ });
856
+ }
857
+ catch (error) {
858
+ console.error('postUiQuery error:', error);
859
+ return null;
860
+ }
861
+ };
814
862
  const getTableRecordsByUrl = async (payload, url) => {
815
863
  try {
816
864
  return httpRequest({
@@ -1433,6 +1481,7 @@ const parseResponse = (data, type, agentId = "", currentMode = "", disableTimeAn
1433
1481
  isDisabled: data?.data?.isDisabled,
1434
1482
  orientation: data?.data?.orientation,
1435
1483
  options: data?.data?.options,
1484
+ defaultSelected: data?.data?.defaultSelected,
1436
1485
  paramName: data?.data?.param_name
1437
1486
  }
1438
1487
  };
@@ -1512,6 +1561,17 @@ const parseResponse = (data, type, agentId = "", currentMode = "", disableTimeAn
1512
1561
  bodyType: "html",
1513
1562
  bodyText: { content: data?.data?.content || "" },
1514
1563
  };
1564
+ case "allocation_plan_card":
1565
+ return {
1566
+ ...data,
1567
+ timeStamp: timeString,
1568
+ userType: "bot",
1569
+ userName: userName,
1570
+ headerTitle: "",
1571
+ noShowHeaderTitle: true,
1572
+ bodyType: "allocation_plan_card",
1573
+ bodyText: data?.data || data,
1574
+ };
1515
1575
  case "image":
1516
1576
  return {
1517
1577
  ...data,
@@ -1539,6 +1599,18 @@ const parseResponse = (data, type, agentId = "", currentMode = "", disableTimeAn
1539
1599
  thinkingResponse: utilityObject?.thinkingResponse,
1540
1600
  enableLikes: true
1541
1601
  };
1602
+ case "surface_frame":
1603
+ // A generated UI surface drawn by the UI service's renderer page (Impact UI 5), which SurfaceFrameContent embeds
1604
+ return {
1605
+ ...data,
1606
+ agentId: agentId,
1607
+ timeStamp: timeString,
1608
+ userType: "bot",
1609
+ userName: userName,
1610
+ headerTitle: data?.data?.surface?.title || "",
1611
+ bodyType: "surface_frame",
1612
+ bodyText: data?.data,
1613
+ };
1542
1614
  default:
1543
1615
  return null;
1544
1616
  }
@@ -2801,6 +2873,10 @@ const useAgentFlow = (dateFormat, chatDataRef, currentMode, setShowChatPlacehold
2801
2873
  answer_mode: data?.answerMode || "auto",
2802
2874
  ...(!isEmpty(utilityObjectData?.additionalArgs) ? utilityObjectData.additionalArgs : {}),
2803
2875
  };
2876
+ if (data?.uiContext && typeof data.uiContext === "object") {
2877
+ // a follow-up asked from a generated surface: which surface, and its input values
2878
+ payload.ui_context = data.uiContext;
2879
+ }
2804
2880
  // Handle @ filter mentions - user_explicit_input contains filter values
2805
2881
  if (!isEmpty(data?.userExplicitInput)) {
2806
2882
  payload.user_explicit_input = data?.userExplicitInput;
@@ -3261,9 +3337,16 @@ const useChatFlow = (chatDataRef, setLoader, setFlowType, setScreenName, setUser
3261
3337
  else if (data.actionType === "indirect") {
3262
3338
  setUserInput(data.displayText);
3263
3339
  }
3264
- else {
3340
+ else if (data.screen_name) {
3265
3341
  fetchUserResultsFromQuery(data, true, "", activeConversationId);
3266
3342
  }
3343
+ else {
3344
+ // No screen_name (e.g. suggested follow-up chips from navigation-v2):
3345
+ // treat the chip's displayText as a regular user query so it flows
3346
+ // through the navigation streaming endpoint instead of the
3347
+ // fetchRelatedQuestions screen-based endpoint.
3348
+ fetchUserResultsFromQuery(data, false, data.displayText, activeConversationId);
3349
+ }
3267
3350
  }, [activeConversationId, baseUrl]);
3268
3351
  const fetchUserResultsFromQuery = useCallback(async (refObject, fetchQuestions = false, inputValue = userInput, conversationId = activeConversationId) => {
3269
3352
  let flowType = refObject?.flow_type ? refObject?.flow_type : currentMode;
@@ -5995,6 +6078,73 @@ const QuestionsContent = ({ bodyText, props }) => {
5995
6078
  }) }));
5996
6079
  };
5997
6080
 
6081
+ /**
6082
+ * One widget per generated surface in a stream: the agent may send a surface more than once (a placeholder
6083
+ * while it is composed, `status: "pending"`, version 0; then the surface, version 1; or its withdrawal), and
6084
+ * frame protocol 1 replaces a surface by its id (agent-ui-service-ssr docs/chat-frame-widget.md, rule 4).
6085
+ * No imports: the stream reader (AxiosEventSource) uses it too. Ported from core's smartBot
6086
+ * (insideinsight/core feat/iui-surface, e386f8f0).
6087
+ */
6088
+ /** A surface's version; one when it gives none. */
6089
+ const surfaceVersion = (surface) => (Number.isFinite(surface?.version) ? surface.version : 1);
6090
+ const surfaceIdOf = (widget) => (widget?.type === "surface_frame" ? widget?.data?.surface?.id : undefined);
6091
+ /** A stream's widgets with these added: a surface_frame widget whose surface the list already holds replaces
6092
+ * it in place (a lower version is dropped); any other widget is added at the end. */
6093
+ const mergeSurfaceWidgets = (previous, incoming) => {
6094
+ const merged = Array.isArray(previous) ? previous.slice() : previous ? [previous] : [];
6095
+ for (const widget of Array.isArray(incoming) ? incoming : [incoming]) {
6096
+ const id = surfaceIdOf(widget);
6097
+ const at = id === undefined ? -1 : merged.findIndex((w) => surfaceIdOf(w) === id);
6098
+ if (at < 0)
6099
+ merged.push(widget);
6100
+ else if (surfaceVersion(widget.data.surface) >= surfaceVersion(merged[at].data.surface))
6101
+ merged[at] = widget;
6102
+ }
6103
+ return merged;
6104
+ };
6105
+ /*
6106
+ * Across the chat's messages (one page per surface): a surface revised in a later turn is shown, newest
6107
+ * version, where that turn put it; each earlier widget of it collapses to a line. Every SurfaceFrameContent
6108
+ * says which version it shows; a widget whose surface another widget shows in a higher version collapses.
6109
+ * Placeholders and withdrawn surfaces take no part. Equal versions (the same surface drawn in two places)
6110
+ * both show.
6111
+ */
6112
+ const shownVersions = new Map(); // surface id -> Map(widget token -> version)
6113
+ const watchers = new Set();
6114
+ let lastToken = 0;
6115
+ /** A token for one widget. */
6116
+ const surfaceToken = () => {
6117
+ lastToken += 1;
6118
+ return lastToken;
6119
+ };
6120
+ const notify = () => watchers.forEach((watch) => watch());
6121
+ /** This widget shows `version` of surface `id`. */
6122
+ const showSurface = (id, token, version) => {
6123
+ if (!shownVersions.has(id))
6124
+ shownVersions.set(id, new Map());
6125
+ shownVersions.get(id).set(token, version);
6126
+ notify();
6127
+ };
6128
+ /** This widget no longer shows surface `id`. */
6129
+ const hideSurface = (id, token) => {
6130
+ const versions = shownVersions.get(id);
6131
+ if (!versions)
6132
+ return;
6133
+ versions.delete(token);
6134
+ if (versions.size === 0)
6135
+ shownVersions.delete(id);
6136
+ notify();
6137
+ };
6138
+ /** Whether another widget shows surface `id` in a version higher than `version`. */
6139
+ const newerShown = (id, version) => [...(shownVersions.get(id)?.values() ?? [])].some((v) => v > version);
6140
+ /** Calls `watch` whenever a widget starts or stops showing a surface; returns the unsubscribe. */
6141
+ const watchSurfaces = (watch) => {
6142
+ watchers.add(watch);
6143
+ return () => {
6144
+ watchers.delete(watch);
6145
+ };
6146
+ };
6147
+
5998
6148
  // Utility: check whether a string is a likely complete JSON value
5999
6149
  const isLikelyCompleteJson = (message) => {
6000
6150
  try {
@@ -6202,10 +6352,8 @@ const sseevent = (message, messageToStoreRef) => {
6202
6352
  let previousWidgetData = isArray$1(messageToStoreRef.current.appendedData)
6203
6353
  ? messageToStoreRef.current.appendedData
6204
6354
  : [messageToStoreRef.current.appendedData];
6205
- messageToStoreRef.current.appendedData = [
6206
- ...previousWidgetData,
6207
- ...finalWidgetData,
6208
- ];
6355
+ // a surface sent again (placeholder, then the surface) replaces its widget in place
6356
+ messageToStoreRef.current.appendedData = mergeSurfaceWidgets(previousWidgetData, finalWidgetData);
6209
6357
  messageToStoreRef.current.sessionId = parsedData.session_id;
6210
6358
  messageToStoreRef.current.uniqueChatId = parsedData?.chat_id
6211
6359
  ? parsedData.chat_id
@@ -6245,10 +6393,8 @@ const sseevent = (message, messageToStoreRef) => {
6245
6393
  let previousWidgetData = isArray$1(messageToStoreRef.current.appendedData)
6246
6394
  ? messageToStoreRef.current.appendedData
6247
6395
  : [messageToStoreRef.current.appendedData];
6248
- messageToStoreRef.current.appendedData = [
6249
- ...previousWidgetData,
6250
- ...finalWidgetData,
6251
- ];
6396
+ // a surface sent again (placeholder, then the surface) replaces its widget in place
6397
+ messageToStoreRef.current.appendedData = mergeSurfaceWidgets(previousWidgetData, finalWidgetData);
6252
6398
  messageToStoreRef.current.additionalArgs = parsedData?.additional_args
6253
6399
  ? parsedData.additional_args
6254
6400
  : {};
@@ -9155,13 +9301,36 @@ const CheckboxGroupContent = ({ bodyText, isFormDisabled = false, messageIndex }
9155
9301
  const RadioContent = ({ bodyText, isFormDisabled = false, messageIndex }) => {
9156
9302
  const formKey = `${messageIndex}_${bodyText?.paramName}`;
9157
9303
  const classes = useStyles$b();
9158
- const { label, isDisabled, orientation, options } = bodyText;
9304
+ const { label, isDisabled, orientation, options, defaultSelected } = bodyText;
9159
9305
  const chatbotContext = useSelector((state) => state.smartBotReducer.chatbotContext);
9160
9306
  const chatbotContextRef = useRef(chatbotContext);
9161
9307
  chatbotContextRef.current = chatbotContext;
9162
9308
  const persistedFormValues = useSelector((state) => state.smartBotReducer.persistedFormValues);
9163
9309
  const dispatch = useDispatch();
9164
- const [selectedOption, setSelectedOption] = useState(persistedFormValues[formKey] ?? null);
9310
+ const [selectedOption, setSelectedOption] = useState(persistedFormValues[formKey] ?? defaultSelected ?? null);
9311
+ // When a defaultSelected value is provided and nothing was previously persisted,
9312
+ // seed Redux state so submit-validation and context are aware of the pre-selection.
9313
+ // Uses getState inside a thunk to read the latest chatbotContext at dispatch time,
9314
+ // avoiding stale-ref overwrites when multiple radio widgets mount in the same flush.
9315
+ useEffect(() => {
9316
+ if (defaultSelected && !persistedFormValues[formKey]) {
9317
+ dispatch((dispatchAction, getState) => {
9318
+ const currentContext = getState().smartBotReducer.chatbotContext;
9319
+ dispatchAction({
9320
+ type: "SET_CHATBOT_CONTEXT",
9321
+ payload: {
9322
+ ...currentContext,
9323
+ [bodyText?.paramName]: {
9324
+ ...currentContext?.[bodyText?.paramName],
9325
+ [bodyText?.paramName]: defaultSelected,
9326
+ updated: true,
9327
+ },
9328
+ },
9329
+ });
9330
+ });
9331
+ dispatch(setPersistedFormValues({ [formKey]: defaultSelected }));
9332
+ }
9333
+ }, []);
9165
9334
  if (isEmpty$1(bodyText))
9166
9335
  return null;
9167
9336
  const handleChange = (selectedOption) => {
@@ -9239,6 +9408,183 @@ const ImageContent = ({ bodyText }) => {
9239
9408
  } })), caption && (jsx("div", { children: jsx(TextRenderer, { text: caption }) }))] }));
9240
9409
  };
9241
9410
 
9411
+ const SUBMIT = { buttons: [{ label: "Submit", variant: "primary" }] };
9412
+ /** A follow-up's limits: longer ones are ignored. */
9413
+ const PROMPT_TEXT_MAX = 1000;
9414
+ const PROMPT_CONTEXT_MAX = 16000;
9415
+ /** The window event the chat listens to for a follow-up asked from a surface. */
9416
+ const PROMPT_EVENT = "iris:prompt";
9417
+ /** The source a surface names for this temp table, if it names it: the only tables its page may ask pages
9418
+ * of, and the endpoint address the agent gave (the page's own copy of the source is not trusted for it). */
9419
+ const sourceOf = (surface, table) => Object.values(surface?.data || {}).map((entry) => entry?.source).find((source) => typeof source?.table === "string" && source.table === table);
9420
+ /** Whether the surface binds this tool: the only tools its page may ask to read again. */
9421
+ const bindsTool = (surface, tool) => typeof tool === "string" && tool !== "rows" && Object.values(surface?.data || {}).some((entry) => entry?.tool === tool);
9422
+ const baseUrl = () => sessionStorage.getItem("stepForm_baseUrl") || "";
9423
+ /** One page of a source, from the agent's paging endpoint (its pages hold at most 10 rows): at the address
9424
+ * the agent gave, as TableContent does with temp_table_url, else under the stream's base URL. `search`: a
9425
+ * filter Control over the kept rows (catalog 0.3), each `{field, value}` an exact match the endpoint applies. */
9426
+ const pageOf = async ({ source, page, pageSize, sort, search }) => {
9427
+ const payload = {
9428
+ limit: { page, page_size: pageSize },
9429
+ search: (Array.isArray(search) ? search : [])
9430
+ .filter((s) => s && typeof s.field === "string" && s.value !== undefined && s.value !== null)
9431
+ .slice(0, 5)
9432
+ .map((s) => ({ column: s.field, pattern: String(s.value), search_type: "equals" })),
9433
+ sort: (Array.isArray(sort) ? sort : []).map((s) => ({ column: s.field, order: s.order === "desc" ? "desc" : "asc" })),
9434
+ };
9435
+ const response = source.url
9436
+ ? await getTableRecordsByUrl(payload, source.url)
9437
+ : await getTableRecords(payload, baseUrl(), source.table);
9438
+ const rows = response?.data?.data;
9439
+ const total = response?.data?.total_count;
9440
+ if (!Array.isArray(rows) || !Number.isFinite(total))
9441
+ throw new Error("no rows");
9442
+ return { rows, total };
9443
+ };
9444
+ /** A read tool the surface binds, run again by the agent with these arguments. */
9445
+ const readOf = async ({ surface, tool, args }) => {
9446
+ const response = await postUiQuery({ surface, tool, args: args && typeof args === "object" ? args : {} }, baseUrl());
9447
+ const rows = response?.data?.rows;
9448
+ const total = response?.data?.total;
9449
+ if (!Array.isArray(rows) || !Number.isFinite(total))
9450
+ throw new Error(response?.data?.error || "no rows");
9451
+ return { rows, total };
9452
+ };
9453
+ /** The page's origin, for http(s) addresses only; anything else is refused. */
9454
+ const frameOrigin = (src) => {
9455
+ try {
9456
+ const url = new URL(src, window.location.href);
9457
+ return url.protocol === "https:" || url.protocol === "http:" ? url.origin : null;
9458
+ }
9459
+ catch {
9460
+ return null;
9461
+ }
9462
+ };
9463
+ /** A follow-up within the limits, or null. */
9464
+ const promptOf = (data, surfaceId) => {
9465
+ const text = typeof data?.text === "string" ? data.text.trim() : "";
9466
+ const context = data?.context && typeof data.context === "object" ? { ...data.context, surface: surfaceId } : { surface: surfaceId };
9467
+ let size = Infinity;
9468
+ try {
9469
+ size = JSON.stringify(context).length;
9470
+ }
9471
+ catch {
9472
+ // a context that cannot be sent is not sent
9473
+ }
9474
+ if (!text || text.length > PROMPT_TEXT_MAX || size > PROMPT_CONTEXT_MAX)
9475
+ return null;
9476
+ return { text, uiContext: context };
9477
+ };
9478
+ const SurfaceFrameContent = ({ frame, isFormDisabled = false, messageIndex = 0 }) => {
9479
+ const dispatch = useDispatch();
9480
+ const chatbotContext = useSelector((state) => state.smartBotReducer.chatbotContext);
9481
+ const contextRef = useRef(chatbotContext);
9482
+ contextRef.current = chatbotContext;
9483
+ const iframeRef = useRef(null);
9484
+ const ready = useRef(false);
9485
+ const [height, setHeight] = useState(120);
9486
+ const [form, setForm] = useState({ values: {}, inputs: [], missing: [] });
9487
+ const formRef = useRef(form);
9488
+ formRef.current = form;
9489
+ const src = frame?.src;
9490
+ const incoming = frame?.surface;
9491
+ // the surface shown: a newer version of the same surface replaces it, a lower one is ignored
9492
+ const [surface, setSurface] = useState(incoming);
9493
+ useEffect(() => {
9494
+ if (incoming && (!surface || incoming.id !== surface.id || surfaceVersion(incoming) >= surfaceVersion(surface)))
9495
+ setSurface(incoming);
9496
+ }, [incoming]); // eslint-disable-line react-hooks/exhaustive-deps
9497
+ const origin = useMemo(() => frameOrigin(src), [src]);
9498
+ const ask = surface?.mode === "ask";
9499
+ // which version of its surface each widget shows, across the chat's messages
9500
+ const token = useRef(null);
9501
+ if (token.current === null)
9502
+ token.current = surfaceToken();
9503
+ const [, setShownChange] = useState(0);
9504
+ useEffect(() => watchSurfaces(() => setShownChange((n) => n + 1)), []);
9505
+ useEffect(() => {
9506
+ if (!surface?.id || surface.status === "pending" || surface.status === "withdrawn")
9507
+ return undefined;
9508
+ showSurface(surface.id, token.current, surfaceVersion(surface));
9509
+ return () => hideSurface(surface.id, token.current);
9510
+ }, [surface?.id, surface?.version, surface?.status]); // eslint-disable-line react-hooks/exhaustive-deps
9511
+ const send = (target, values) => target?.postMessage({ type: "iui:surface", surface, values, disabled: Boolean(isFormDisabled), query: true, ...(ask ? { submit: false } : {}) }, origin);
9512
+ useEffect(() => {
9513
+ if (!origin || !surface)
9514
+ return undefined;
9515
+ const onMessage = (event) => {
9516
+ const target = iframeRef.current?.contentWindow;
9517
+ if (!target || event.source !== target || event.origin !== origin)
9518
+ return;
9519
+ const data = event.data || {};
9520
+ // every message but iui:ready and iui:height names its surface: this widget answers for its own only
9521
+ const own = data.surface === undefined || data.surface === surface.id;
9522
+ if (data.type === "iui:ready") {
9523
+ ready.current = true;
9524
+ send(target, undefined);
9525
+ }
9526
+ else if (data.type === "iui:height" && Number.isFinite(data.height))
9527
+ setHeight(Math.max(40, Math.ceil(data.height)));
9528
+ else if (data.type === "iui:query" && own) {
9529
+ const reply = (body) => target.postMessage({ type: "iui:data", surface: surface.id, id: data.id, ...body }, origin);
9530
+ const args = data.args || {};
9531
+ if (data.tool === "rows") {
9532
+ const source = sourceOf(surface, args.source?.table);
9533
+ if (!source)
9534
+ reply({ error: "not a table of this answer" });
9535
+ else
9536
+ pageOf({ ...args, source }).then(reply, () => reply({ error: "the rows could not be loaded" }));
9537
+ }
9538
+ else if (bindsTool(surface, data.tool)) {
9539
+ readOf({ surface: surface.id, tool: data.tool, args }).then(reply, () => reply({ error: "the data could not be loaded" }));
9540
+ }
9541
+ else
9542
+ reply({ error: "not a tool of this answer" });
9543
+ }
9544
+ else if (data.type === "iui:prompt" && data.surface === surface.id) {
9545
+ const prompt = promptOf(data, surface.id);
9546
+ if (prompt)
9547
+ window.dispatchEvent(new CustomEvent(PROMPT_EVENT, { detail: prompt }));
9548
+ }
9549
+ else if (data.type === "iui:change" && ask && own) {
9550
+ const values = data.values || {};
9551
+ setForm({ values, inputs: Array.isArray(data.inputs) ? data.inputs : Object.keys(values), missing: Array.isArray(data.missing) ? data.missing : [] });
9552
+ // as this chat's own inputs record their values, for the step form's Submit (ButtonContent)
9553
+ const context = { ...contextRef.current };
9554
+ for (const [name, value] of Object.entries(values)) {
9555
+ const empty = value === "" || value === null || value === undefined || (Array.isArray(value) && value.length === 0);
9556
+ context[name] = { ...context[name], [name]: value, updated: !empty };
9557
+ }
9558
+ dispatch(setChatbotContext(context));
9559
+ // only what was filled in: ButtonContent sends a persisted value even when it is empty
9560
+ const filled = Object.entries(values).filter(([name]) => context[name].updated);
9561
+ dispatch(setPersistedFormValues(Object.fromEntries(filled.map(([name, value]) => [`${messageIndex}_${name}`, value]))));
9562
+ }
9563
+ // anything else: a message type this chat does not know, ignored
9564
+ };
9565
+ window.addEventListener("message", onMessage);
9566
+ return () => window.removeEventListener("message", onMessage);
9567
+ }, [origin, surface, isFormDisabled, ask, messageIndex]); // eslint-disable-line react-hooks/exhaustive-deps
9568
+ // a newer version of the surface goes into the page that shows it
9569
+ useEffect(() => {
9570
+ if (ready.current)
9571
+ send(iframeRef.current?.contentWindow, undefined);
9572
+ }, [surface]); // eslint-disable-line react-hooks/exhaustive-deps
9573
+ // a submitted form is posted again, disabled, with what was filled in
9574
+ useEffect(() => {
9575
+ if (isFormDisabled && ask)
9576
+ send(iframeRef.current?.contentWindow, formRef.current.values);
9577
+ }, [isFormDisabled]); // eslint-disable-line react-hooks/exhaustive-deps
9578
+ // a surface that will not come after all (its composition failed): nothing to draw
9579
+ if (!origin || !surface || surface.status === "withdrawn")
9580
+ return null;
9581
+ // a later message shows this surface revised: one line here, the surface there
9582
+ if (newerShown(surface.id, surfaceVersion(surface))) {
9583
+ return (jsx(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}` : ""}.` }));
9584
+ }
9585
+ return (jsxs(Box, { "data-iui-host": "surface-frame", my: 1, children: [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 ? (jsx(ButtonContent, { bodyText: SUBMIT, isFormDisabled: isFormDisabled, isStepFormSubmit: true, isFormValid: form.inputs.length > 0 && form.missing.length === 0, formParamNames: form.inputs, messageIndex: messageIndex })) : null] }));
9586
+ };
9587
+
9242
9588
  // Key used to persist timeout state in sessionStorage (survives component remounts from tab switches)
9243
9589
  const STEP_FORM_TIMEOUT_KEY = "__stepFormTimedOut";
9244
9590
  /**
@@ -9668,11 +10014,17 @@ const StepFormContent = ({ formData, messageIndex = 0, isFormDisabled = false, s
9668
10014
  case "radio":
9669
10015
  return jsx(RadioContent, { bodyText: parsedData.bodyText, isFormDisabled: formFieldsDisabled, messageIndex: messageIndex }, key);
9670
10016
  case "button":
10017
+ // A form in the renderer page has its Submit drawn by SurfaceFrameContent, which knows the page's inputs
10018
+ if (formData.some((item) => item?.type === "surface_frame"))
10019
+ return null;
9671
10020
  return jsx(ButtonContent, { bodyText: parsedData.bodyText, isFormDisabled: isFormDisabled || isFormSubmitted || isTimedOut, isStepFormSubmit: true, isFormValid: requiredFieldsFilled && checkboxGroupsValid, formParamNames: formParamNames, messageIndex: messageIndex }, key);
9672
10021
  case "input":
9673
10022
  return jsx(InputContent, { bodyText: parsedData.bodyText, isFormDisabled: formFieldsDisabled, messageIndex: messageIndex }, key);
9674
10023
  case "image":
9675
10024
  return jsx(ImageContent, { bodyText: parsedData.bodyText }, key);
10025
+ case "surface_frame":
10026
+ // The whole form in the renderer page; the widget draws this form's Submit (its inputs are in the page)
10027
+ return jsx(SurfaceFrameContent, { frame: parsedData.bodyText, isFormDisabled: isFormDisabled || isFormSubmitted || isTimedOut, messageIndex: messageIndex }, parsedData.bodyText?.surface?.id || key);
9676
10028
  default:
9677
10029
  return null;
9678
10030
  }
@@ -10068,7 +10420,7 @@ const ProgressBarItem$1 = ({ question, questionSteps, isLast, classes, formData,
10068
10420
  const [isExpanded, setIsExpanded] = useState(true);
10069
10421
  const dotClass = status === "completed"
10070
10422
  ? "completed"
10071
- : status === "in-progress"
10423
+ : status === "in-progress" || status === "not-started"
10072
10424
  ? "in-progress"
10073
10425
  : status === "error"
10074
10426
  ? "error"
@@ -10189,6 +10541,479 @@ const Steps$1 = ({ steps, setSteps, done, setTabValue, setDone, finalStepDone, s
10189
10541
  }, children: jsx(ProgressBarItem$1, { question: "Thinking", questionSteps: [{ header: "", sub_header: "", step_status: "not-completed" }], isLast: true, classes: classes, formData: null, isFormDisabled: isFormDisabled }) }))] }));
10190
10542
  };
10191
10543
 
10544
+ const useAllocationPanelStyles = makeStyles((theme) => ({
10545
+ // AllocationPlanCard styles (inside chatbot)
10546
+ planCard: {
10547
+ border: "1.5px solid #e2e8f0",
10548
+ borderRadius: "14px",
10549
+ padding: "14px 16px",
10550
+ display: "flex",
10551
+ alignItems: "center",
10552
+ gap: "14px",
10553
+ cursor: "pointer",
10554
+ position: "relative",
10555
+ overflow: "hidden",
10556
+ transition: "border-color 0.25s ease, box-shadow 0.25s ease, background 0.25s ease",
10557
+ background: "#fafbff",
10558
+ "&:hover": {
10559
+ borderColor: "#b4beff",
10560
+ boxShadow: "0 2px 12px rgba(66, 89, 238, 0.10)",
10561
+ background: "linear-gradient(135deg, #f5f7ff 0%, #eef1ff 60%, #e8ecff 100%)",
10562
+ },
10563
+ },
10564
+ planCardIcon: {
10565
+ width: "48px",
10566
+ height: "48px",
10567
+ borderRadius: "12px",
10568
+ background: "linear-gradient(135deg, #e8edff 0%, #dbe1ff 100%)",
10569
+ display: "flex",
10570
+ alignItems: "center",
10571
+ justifyContent: "center",
10572
+ flexShrink: 0,
10573
+ "& svg": {
10574
+ color: "#4259EE",
10575
+ fontSize: "22px",
10576
+ },
10577
+ },
10578
+ planCardContent: {
10579
+ flex: 1,
10580
+ minWidth: 0,
10581
+ },
10582
+ planCardTitle: {
10583
+ fontSize: "14px",
10584
+ fontWeight: 700,
10585
+ color: "#1e293b",
10586
+ lineHeight: 1.4,
10587
+ marginBottom: "4px",
10588
+ },
10589
+ planCardLinks: {
10590
+ display: "flex",
10591
+ alignItems: "center",
10592
+ gap: "4px",
10593
+ flexWrap: "wrap",
10594
+ fontSize: "13px",
10595
+ color: "#64748b",
10596
+ },
10597
+ planCardLink: {
10598
+ color: "#64748b",
10599
+ cursor: "pointer",
10600
+ textDecoration: "none",
10601
+ transition: "color 0.2s ease",
10602
+ "&:hover": {
10603
+ color: "#4259EE",
10604
+ },
10605
+ },
10606
+ planCardLinkSeparator: {
10607
+ color: "#94a3b8",
10608
+ margin: "0 3px",
10609
+ },
10610
+ planCardOpenIcon: {
10611
+ flexShrink: 0,
10612
+ color: "#94a3b8",
10613
+ fontSize: "20px !important",
10614
+ padding: "6px",
10615
+ borderRadius: "8px",
10616
+ border: "1px solid #e2e8f0",
10617
+ background: "#ffffff",
10618
+ transition: "border-color 0.25s ease, color 0.25s ease",
10619
+ "$planCard:hover &": {
10620
+ borderColor: "#b4beff",
10621
+ color: "#4259EE",
10622
+ },
10623
+ },
10624
+
10625
+ // PanelHeader styles
10626
+ panelHeader: {
10627
+ display: "flex",
10628
+ alignItems: "center",
10629
+ justifyContent: "space-between",
10630
+ padding: "16px",
10631
+ borderBottom: "1px solid #f0f0f0",
10632
+ flexShrink: 0,
10633
+ },
10634
+ panelHeaderLeft: {
10635
+ display: "flex",
10636
+ alignItems: "center",
10637
+ gap: "8px",
10638
+ flex: 1,
10639
+ minWidth: 0,
10640
+ },
10641
+ panelHeaderIcon: {
10642
+ color: "#666",
10643
+ fontSize: "20px",
10644
+ cursor: "pointer",
10645
+ },
10646
+ panelTitle: {
10647
+ fontSize: "14px",
10648
+ fontWeight: 600,
10649
+ color: "#1a1a1a",
10650
+ lineHeight: 1.4,
10651
+ overflow: "hidden",
10652
+ textOverflow: "ellipsis",
10653
+ whiteSpace: "nowrap",
10654
+ },
10655
+ panelHeaderActions: {
10656
+ display: "flex",
10657
+ alignItems: "center",
10658
+ gap: "6px",
10659
+ flexShrink: 0,
10660
+ },
10661
+ panelHeaderActionBtn: {
10662
+ width: "28px !important",
10663
+ height: "28px !important",
10664
+ borderRadius: "8px !important",
10665
+ background: "#f1f5f9 !important",
10666
+ color: "#475569 !important",
10667
+ padding: "0 !important",
10668
+ "&:hover": {
10669
+ background: "#e2e8f0 !important",
10670
+ color: "#1e293b !important",
10671
+ },
10672
+ },
10673
+
10674
+ // ReportSummaryCard styles
10675
+ reportSummaryCard: {
10676
+ border: "1px solid #f0c36d",
10677
+ borderRadius: "8px",
10678
+ padding: "14px",
10679
+ margin: "16px 0",
10680
+ background: "#fffdf5",
10681
+ },
10682
+ reportBadge: {
10683
+ display: "inline-block",
10684
+ fontSize: "11px",
10685
+ fontWeight: 500,
10686
+ padding: "3px 8px",
10687
+ borderRadius: "4px",
10688
+ marginBottom: "8px",
10689
+ border: "1px solid #f0c36d",
10690
+ color: "#8b6914",
10691
+ background: "transparent",
10692
+ },
10693
+ reportDescription: {
10694
+ fontSize: "12px",
10695
+ lineHeight: 1.6,
10696
+ color: "#333",
10697
+ marginBottom: "10px",
10698
+ },
10699
+ baselinePlanRow: {
10700
+ fontSize: "12px",
10701
+ color: "#666",
10702
+ display: "flex",
10703
+ alignItems: "center",
10704
+ gap: "4px",
10705
+ },
10706
+ baselinePlanLink: {
10707
+ color: "#2563eb",
10708
+ textDecoration: "underline",
10709
+ cursor: "pointer",
10710
+ wordBreak: "break-all",
10711
+ },
10712
+
10713
+ // PanelSection (Accordion) styles
10714
+ sectionAccordion: {
10715
+ boxShadow: "none !important",
10716
+ border: "none !important",
10717
+ borderRadius: "12px !important",
10718
+ marginBottom: "10px !important",
10719
+ background: "#f8fafc !important",
10720
+ "&:before": {
10721
+ display: "none !important",
10722
+ content: "none !important",
10723
+ background: "none !important",
10724
+ width: "0 !important",
10725
+ height: "0 !important",
10726
+ },
10727
+ "&.Mui-expanded": {
10728
+ margin: "0 0 10px 0 !important",
10729
+ background: "#ffffff !important",
10730
+ boxShadow: "0 1px 8px rgba(0, 0, 0, 0.06) !important",
10731
+ border: "1px solid #e2e8f0 !important",
10732
+ },
10733
+ },
10734
+ sectionSummary: {
10735
+ minHeight: "48px !important",
10736
+ padding: "0 16px !important",
10737
+ border: "none !important",
10738
+ flexDirection: "row-reverse !important",
10739
+ gap: "10px",
10740
+ "&:before": {
10741
+ display: "none !important",
10742
+ content: "none !important",
10743
+ background: "none !important",
10744
+ width: "0 !important",
10745
+ height: "0 !important",
10746
+ },
10747
+ "& .MuiAccordionSummary-content": {
10748
+ margin: "12px 0 !important",
10749
+ },
10750
+ "& .MuiAccordionSummary-expandIconWrapper": {
10751
+ color: "#64748b",
10752
+ transform: "rotate(-90deg)",
10753
+ padding: "0 !important",
10754
+ marginRight: "0 !important",
10755
+ "&.Mui-expanded": {
10756
+ transform: "rotate(0deg)",
10757
+ },
10758
+ },
10759
+ },
10760
+ sectionTitle: {
10761
+ fontSize: "14px",
10762
+ fontWeight: 600,
10763
+ color: "#1e293b",
10764
+ },
10765
+ sectionDetails: {
10766
+ padding: "0 16px 16px !important",
10767
+ border: "none !important",
10768
+ "&:before": {
10769
+ display: "none !important",
10770
+ content: "none !important",
10771
+ background: "none !important",
10772
+ width: "0 !important",
10773
+ height: "0 !important",
10774
+ },
10775
+ },
10776
+
10777
+ // StructuredComparison styles
10778
+ comparisonSubtitle: {
10779
+ fontSize: "12px",
10780
+ color: "#666",
10781
+ marginBottom: "12px",
10782
+ lineHeight: 1.5,
10783
+ },
10784
+ scenarioLabel: {
10785
+ fontSize: "12px",
10786
+ fontWeight: 500,
10787
+ color: "#1a1a1a",
10788
+ padding: "8px 12px",
10789
+ background: "#f8f9fa",
10790
+ borderRadius: "6px",
10791
+ marginBottom: "12px",
10792
+ },
10793
+ comparisonCard: {
10794
+ background: "#f8f9fa",
10795
+ borderRadius: "8px",
10796
+ padding: "12px",
10797
+ marginBottom: "10px",
10798
+ },
10799
+ comparisonParamRow: {
10800
+ display: "flex",
10801
+ alignItems: "center",
10802
+ gap: "8px",
10803
+ marginBottom: "10px",
10804
+ },
10805
+ comparisonParamName: {
10806
+ fontSize: "13px",
10807
+ fontWeight: 600,
10808
+ color: "#1a1a1a",
10809
+ },
10810
+ comparisonTag: {
10811
+ display: "inline-block",
10812
+ fontSize: "10px",
10813
+ fontWeight: 500,
10814
+ padding: "2px 6px",
10815
+ borderRadius: "4px",
10816
+ color: "#2563eb",
10817
+ border: "1px solid #bfdbfe",
10818
+ background: "#eff6ff",
10819
+ },
10820
+ comparisonValues: {
10821
+ display: "flex",
10822
+ alignItems: "center",
10823
+ gap: "8px",
10824
+ },
10825
+ comparisonValueBox: {
10826
+ flex: 1,
10827
+ background: theme.palette.common.white,
10828
+ borderRadius: "6px",
10829
+ padding: "8px 10px",
10830
+ border: "1px solid #e8e8e8",
10831
+ },
10832
+ comparisonValueLabel: {
10833
+ fontSize: "10px",
10834
+ color: "#999",
10835
+ marginBottom: "2px",
10836
+ },
10837
+ comparisonValueText: {
10838
+ fontSize: "12px",
10839
+ fontWeight: 600,
10840
+ color: "#1a1a1a",
10841
+ },
10842
+ comparisonArrow: {
10843
+ color: "#999",
10844
+ fontSize: "16px",
10845
+ flexShrink: 0,
10846
+ },
10847
+
10848
+ // Panel-specific HTML content wrapper (font size/line-height for panel context)
10849
+ panelHtmlContainer: {
10850
+ fontSize: "12px",
10851
+ lineHeight: 1.6,
10852
+ },
10853
+
10854
+ // Slide-in keyframes for panel entry
10855
+ "@keyframes panelSlideIn": {
10856
+ "0%": {
10857
+ transform: "translateX(100%)",
10858
+ opacity: 0,
10859
+ },
10860
+ "100%": {
10861
+ transform: "translateX(0)",
10862
+ opacity: 1,
10863
+ },
10864
+ },
10865
+ // AllocationDetailPanel container (portaled)
10866
+ panelContainer: {
10867
+ position: "fixed",
10868
+ top: 56,
10869
+ right: 0,
10870
+ width: "calc(50vw - 32px)",
10871
+ maxWidth: "520px",
10872
+ height: "calc(100vh - 56px)",
10873
+ zIndex: 99999,
10874
+ display: "flex",
10875
+ flexDirection: "column",
10876
+ background: "#ffffff",
10877
+ boxShadow: "-4px 0 16px rgba(0, 0, 0, 0.15)",
10878
+ borderLeft: "1px solid #e8e8e8",
10879
+ borderRadius: "12px 0 0 12px",
10880
+ overflow: "hidden",
10881
+ animation: "$panelSlideIn 0.3s ease forwards",
10882
+ transition: "width 0.3s ease, max-width 0.3s ease, border-radius 0.3s ease",
10883
+ },
10884
+ // Expanded / maximized panel — covers the chatbot area too
10885
+ panelExpanded: {
10886
+ width: "calc(100vw - 4rem)",
10887
+ maxWidth: "calc(100vw - 4rem)",
10888
+ borderRadius: "0",
10889
+ },
10890
+ panelScrollBody: {
10891
+ flex: 1,
10892
+ overflowY: "auto",
10893
+ padding: "0 16px 24px",
10894
+ },
10895
+
10896
+ // Footer
10897
+ panelFooter: {
10898
+ display: "flex",
10899
+ justifyContent: "flex-end",
10900
+ alignItems: "center",
10901
+ gap: "10px",
10902
+ padding: "12px 16px",
10903
+ borderTop: "1px solid #e2e8f0",
10904
+ background: "#ffffff",
10905
+ flexShrink: 0,
10906
+ position: "relative",
10907
+ },
10908
+ footerBtnOutlined: {
10909
+ display: "inline-flex",
10910
+ alignItems: "center",
10911
+ justifyContent: "center",
10912
+ height: "32px",
10913
+ padding: "0 12px",
10914
+ fontSize: "14px",
10915
+ fontWeight: 600,
10916
+ fontFamily: "Manrope, sans-serif",
10917
+ lineHeight: 1,
10918
+ borderRadius: "8px",
10919
+ border: "1px solid #d1d5db",
10920
+ background: "#ffffff",
10921
+ color: "#1e293b",
10922
+ cursor: "pointer",
10923
+ textTransform: "none",
10924
+ },
10925
+ footerBtnPrimary: {
10926
+ display: "inline-flex",
10927
+ alignItems: "center",
10928
+ justifyContent: "center",
10929
+ height: "32px",
10930
+ padding: "0 12px",
10931
+ fontSize: "14px",
10932
+ fontWeight: 600,
10933
+ fontFamily: "Manrope, sans-serif",
10934
+ lineHeight: 1,
10935
+ borderRadius: "8px",
10936
+ border: "1px solid #4259EE",
10937
+ background: "#4259EE",
10938
+ color: "#ffffff",
10939
+ cursor: "pointer",
10940
+ textTransform: "none",
10941
+ },
10942
+
10943
+ // Footer options popover
10944
+ optionsCard: {
10945
+ position: "absolute",
10946
+ bottom: "100%",
10947
+ right: 0,
10948
+ marginBottom: "8px",
10949
+ background: "#ffffff",
10950
+ borderRadius: "12px",
10951
+ boxShadow: "0 4px 20px rgba(0, 0, 0, 0.12)",
10952
+ border: "1px solid #e2e8f0",
10953
+ padding: "8px",
10954
+ minWidth: "280px",
10955
+ zIndex: 1,
10956
+ },
10957
+ optionRow: {
10958
+ display: "flex",
10959
+ alignItems: "center",
10960
+ gap: "10px",
10961
+ padding: "10px 12px",
10962
+ borderRadius: "8px",
10963
+ cursor: "pointer",
10964
+ fontSize: "13px",
10965
+ fontWeight: 500,
10966
+ color: "#1e293b",
10967
+ background: "#f8fafc",
10968
+ marginBottom: "4px",
10969
+ border: "none",
10970
+ width: "100%",
10971
+ textAlign: "left",
10972
+ fontFamily: "Manrope, sans-serif",
10973
+ "&:hover": {
10974
+ background: "#eef2ff",
10975
+ },
10976
+ "&:last-child": {
10977
+ marginBottom: 0,
10978
+ },
10979
+ },
10980
+ optionIcon: {
10981
+ color: "#6366f1",
10982
+ fontSize: "16px",
10983
+ },
10984
+ }));
10985
+
10986
+ const AllocationPlanCard = ({ bodyText }) => {
10987
+ const classes = useAllocationPanelStyles();
10988
+ const title = bodyText?.title || "Allocation Plan";
10989
+ const links = bodyText?.links || [];
10990
+ const panelData = bodyText?.panel_data || null;
10991
+ const handleCardClick = (target) => {
10992
+ if (!panelData)
10993
+ return;
10994
+ const openPanel = () => {
10995
+ window.dispatchEvent(new CustomEvent("openAllocationDetailPanel", {
10996
+ detail: { panelData, activeSection: target || null },
10997
+ }));
10998
+ };
10999
+ // Check if the chatbot is in a collapsed/minimized state by looking for
11000
+ // the "Expand chatbot" button (present only when collapsed)
11001
+ const expandBtn = document.querySelector('button[aria-label="Expand chatbot"]');
11002
+ if (expandBtn) {
11003
+ // Maximize first, then open the panel after chatbot finishes expanding
11004
+ window.dispatchEvent(new CustomEvent("smartBotMaximize"));
11005
+ setTimeout(openPanel, 350);
11006
+ }
11007
+ else {
11008
+ openPanel();
11009
+ }
11010
+ };
11011
+ return (jsxs("div", { className: classes.planCard, onClick: () => handleCardClick(links[0]?.target), children: [jsx("div", { className: classes.planCardIcon, children: jsx(DescriptionOutlinedIcon, {}) }), jsxs("div", { className: classes.planCardContent, children: [jsx("div", { className: classes.planCardTitle, children: title }), jsx("div", { className: classes.planCardLinks, children: links.map((link, index) => (jsxs("span", { children: [index > 0 && (jsx("span", { className: classes.planCardLinkSeparator, children: "\u00B7" })), jsx("span", { className: classes.planCardLink, onClick: (e) => {
11012
+ e.stopPropagation();
11013
+ handleCardClick(link.target);
11014
+ }, children: link.label })] }, link.target || index))) })] }), jsx(OpenInNewIcon, { className: classes.planCardOpenIcon })] }));
11015
+ };
11016
+
10192
11017
  const renderWidgetItem = (item, index, isFormDisabled) => {
10193
11018
  try {
10194
11019
  const parsedData = parseResponse(item, item.type, "", "", true);
@@ -10225,6 +11050,10 @@ const renderWidgetItem = (item, index, isFormDisabled) => {
10225
11050
  return jsx(DateRangePickerContent, { bodyText: parsedData.bodyText, isFormDisabled: isFormDisabled }, key);
10226
11051
  case "html":
10227
11052
  return jsx(HtmlContent, { bodyText: parsedData.bodyText }, key);
11053
+ case "surface_frame":
11054
+ return jsx(SurfaceFrameContent, { frame: parsedData.bodyText }, parsedData.bodyText?.surface?.id || key);
11055
+ case "allocation_plan_card":
11056
+ return jsx(AllocationPlanCard, { bodyText: parsedData.bodyText }, key);
10228
11057
  default:
10229
11058
  return null;
10230
11059
  }
@@ -11097,7 +11926,8 @@ const StreamedContent = ({ botData, botProps }) => {
11097
11926
  const widgetItems = isArray(data.widget_data)
11098
11927
  ? data.widget_data
11099
11928
  : [data.widget_data];
11100
- setStreamingWidgetData((prev) => [...prev, ...widgetItems]);
11929
+ // a surface sent again (placeholder, then the surface) replaces its widget in place
11930
+ setStreamingWidgetData((prev) => mergeSurfaceWidgets(prev, widgetItems));
11101
11931
  }
11102
11932
  else if (data.message !== "[DONE]") {
11103
11933
  if (!thinkingDoneRef?.current && currentMode === "agent") {
@@ -12267,6 +13097,8 @@ const TabularContent = ({ steps: initialSteps, currentTabValue, children, questi
12267
13097
  return jsx(TableContent, { bodyText: parsedData.bodyText }, parsedData.bodyText?.table_name || key);
12268
13098
  case "graph":
12269
13099
  return jsx(GraphContent, { bodyText: parsedData.bodyText }, key);
13100
+ case "surface_frame":
13101
+ return jsx(SurfaceFrameContent, { frame: parsedData.bodyText }, parsedData.bodyText?.surface?.id || key);
12270
13102
  case "radio":
12271
13103
  return jsx(RadioContent, { bodyText: parsedData.bodyText, isFormDisabled: isFormDisabled }, key);
12272
13104
  case "checkbox":
@@ -12346,7 +13178,8 @@ const TabularContent = ({ steps: initialSteps, currentTabValue, children, questi
12346
13178
  }
12347
13179
  });
12348
13180
  if (newWidgets.length > 0) {
12349
- setWidgetContent((prev) => [...prev, ...newWidgets]);
13181
+ // a surface sent again (placeholder, then the surface) replaces its widget in place
13182
+ setWidgetContent((prev) => mergeSurfaceWidgets(prev, newWidgets));
12350
13183
  }
12351
13184
  return;
12352
13185
  }
@@ -12477,7 +13310,7 @@ const TabularContent = ({ steps: initialSteps, currentTabValue, children, questi
12477
13310
  let newQuestions = [...questionsRef.current];
12478
13311
  let newQuestionsStepsMap = cloneDeep(questionsStepsMapRef.current);
12479
13312
  let newStepFormDataMap = cloneDeep(stepFormDataMapRef.current);
12480
- const newWidgets = [];
13313
+ let newWidgets = [];
12481
13314
  chunks.forEach((data) => {
12482
13315
  if (data.status === "questions") {
12483
13316
  const incomingQuestions = data.widget_data?.[0]?.questions || [];
@@ -12574,10 +13407,8 @@ const TabularContent = ({ steps: initialSteps, currentTabValue, children, questi
12574
13407
  }
12575
13408
  if (data.status === "widget") {
12576
13409
  const widgetItems = isArray$2(data.widget_data) ? data.widget_data : [data.widget_data];
12577
- widgetItems.forEach((item) => {
12578
- if (item)
12579
- newWidgets.push(item);
12580
- });
13410
+ // a surface sent again (placeholder, then the surface) replaces its widget in place
13411
+ newWidgets = mergeSurfaceWidgets(newWidgets, widgetItems.filter(Boolean));
12581
13412
  }
12582
13413
  if (data.status === "content" && data.message) {
12583
13414
  newWidgets.push({ type: "text", response: data.message });
@@ -12704,6 +13535,10 @@ const CombinedContent = ({ botData, props }) => {
12704
13535
  return jsx(ImageContent, { bodyText: parsedData.bodyText }, key);
12705
13536
  case "html":
12706
13537
  return jsx(HtmlContent, { bodyText: parsedData.bodyText }, key);
13538
+ case "surface_frame":
13539
+ return jsx(SurfaceFrameContent, { frame: parsedData.bodyText }, parsedData.bodyText?.surface?.id || key);
13540
+ case "allocation_plan_card":
13541
+ return jsx(AllocationPlanCard, { bodyText: parsedData.bodyText }, key);
12707
13542
  default:
12708
13543
  return null;
12709
13544
  }
@@ -12782,6 +13617,8 @@ const BotMessage = ({ botData, state, handleLikeDislike, props }) => {
12782
13617
  return jsx(TableContent, { bodyText: botData.bodyText });
12783
13618
  case "graph":
12784
13619
  return jsx(GraphContent, { bodyText: botData.bodyText });
13620
+ case "surface_frame":
13621
+ return jsx(SurfaceFrameContent, { frame: botData.bodyText });
12785
13622
  case "slider":
12786
13623
  return jsx(SliderContent, { bodyText: botData.bodyText, isFormDisabled: botData.isFormDisabled, messageIndex: botData.messageIndex });
12787
13624
  case "select":
@@ -12804,6 +13641,8 @@ const BotMessage = ({ botData, state, handleLikeDislike, props }) => {
12804
13641
  return jsx(ImageContent, { bodyText: botData.bodyText });
12805
13642
  case "html":
12806
13643
  return jsx(HtmlContent, { bodyText: botData.bodyText });
13644
+ case "allocation_plan_card":
13645
+ return jsx(AllocationPlanCard, { bodyText: botData.bodyText });
12807
13646
  case "combined":
12808
13647
  return jsx(CombinedContent, { botData: botData, props: props });
12809
13648
  case "dynamic":
@@ -13307,6 +14146,109 @@ function UploadModal(props) {
13307
14146
  return (jsx(Modal, { onClose: handleModalClose, onPrimaryButtonClick: handleFileUpload, onSecondaryButtonClick: handleModalClose, open: isUploadModalOpen, size: "small", title: "Upload Document", primaryButtonLabel: "Upload", secondaryButtonLabel: "Cancel", primaryButtonProps: { disabled: isLoading }, secondaryButtonProps: { disabled: isLoading }, children: isLoading ? (jsx(Loader, { text: "Uploading file..." })) : (jsxs("div", { className: classes.uploadModalInnerSec, children: [jsx("input", { type: "file", ref: fileInputRef, onChange: handleFileSelect, accept: ".pdf", style: { display: "none" }, disabled: isLoading }), jsx(Button, { onClick: () => fileInputRef.current.click(), variant: "outlined", disabled: isLoading, children: "Select PDF File" }), selectedFile && (jsxs("p", { style: { marginTop: "10px" }, children: ["Selected File: ", selectedFile.name] }))] })) }));
13308
14147
  }
13309
14148
 
14149
+ /** A skill is a folder: SKILL.md (its name and description, then its steps) and the files it refers to, such
14150
+ * as references/mcp-contracts.md. Picked files are read here as text, keyed by their path in that folder,
14151
+ * and saved for the signed-in user by the agent (POST {baseUrl}/chatbot/agent/skills). Unlike a paste into
14152
+ * the chat, an upload keeps the line breaks and the skill's other files. */
14153
+ const MAX_FILES = 50;
14154
+ const TEXT_EXTENSIONS = [".md", ".txt", ".json", ".yaml", ".yml", ".csv"];
14155
+ const isSkillFile = (path) => path === "SKILL.md" || path.endsWith("/SKILL.md");
14156
+ const isText = (name) => TEXT_EXTENSIONS.some((ext) => name.toLowerCase().endsWith(ext));
14157
+ /** What the agent answered; a 200 may be the object itself or wrapped as {data: {...}}. */
14158
+ const savedOf = (response) => response?.data?.data || response?.data || {};
14159
+ /** Why the agent did not save it: the 422's detail ("not saved: ..."), else the message or status. */
14160
+ const whyNot = (error) => {
14161
+ const body = error?.response?.data;
14162
+ const said = body?.detail || body?.message || body?.data?.detail;
14163
+ if (typeof said === "string" && said)
14164
+ return said;
14165
+ if (said)
14166
+ return JSON.stringify(said);
14167
+ return error?.response?.status ? `the agent answered ${error.response.status}` : String(error?.message || error);
14168
+ };
14169
+ function SkillUploadModal(props) {
14170
+ const { isOpen, setIsOpen, baseUrl, displaySnackMessages, onUseText } = props;
14171
+ const [picked, setPicked] = useState({});
14172
+ const [skipped, setSkipped] = useState(0);
14173
+ const [isSaving, setIsSaving] = useState(false);
14174
+ const [saved, setSaved] = useState(null);
14175
+ const [error, setError] = useState("");
14176
+ const folderRef = useRef(null);
14177
+ const filesRef = useRef(null);
14178
+ const classes = useStyles$b();
14179
+ const reset = () => {
14180
+ setPicked({});
14181
+ setSkipped(0);
14182
+ setSaved(null);
14183
+ setError("");
14184
+ };
14185
+ const handleClose = () => {
14186
+ if (isSaving)
14187
+ return;
14188
+ setIsOpen(false);
14189
+ reset();
14190
+ };
14191
+ const take = async (list) => {
14192
+ if (!list)
14193
+ return;
14194
+ const next = { ...picked };
14195
+ let left = 0;
14196
+ for (const file of Array.from(list)) {
14197
+ const path = file.webkitRelativePath || file.name;
14198
+ if (!isText(file.name)) {
14199
+ left += 1; // a folder may hold images or .DS_Store: only text files are a skill's
14200
+ continue;
14201
+ }
14202
+ if (!(path in next) && Object.keys(next).length >= MAX_FILES) {
14203
+ displaySnackMessages(`A skill can have at most ${MAX_FILES} files`, "error");
14204
+ break;
14205
+ }
14206
+ next[path] = await file.text();
14207
+ }
14208
+ setPicked(next);
14209
+ setSkipped(skipped + left);
14210
+ setSaved(null);
14211
+ setError("");
14212
+ };
14213
+ const paths = Object.keys(picked);
14214
+ const hasSkill = paths.some(isSkillFile);
14215
+ const handleSave = async () => {
14216
+ if (!hasSkill) {
14217
+ displaySnackMessages("Pick the skill's SKILL.md (or its folder) first", "error");
14218
+ return;
14219
+ }
14220
+ try {
14221
+ setIsSaving(true);
14222
+ setError("");
14223
+ const response = await uploadSkill(picked, baseUrl);
14224
+ setSaved(savedOf(response));
14225
+ displaySnackMessages("Skill saved", "success");
14226
+ }
14227
+ catch (err) {
14228
+ console.error("uploadSkill error:", err);
14229
+ setError(whyNot(err));
14230
+ }
14231
+ finally {
14232
+ setIsSaving(false);
14233
+ }
14234
+ };
14235
+ const use = (text) => {
14236
+ onUseText?.(text);
14237
+ setIsOpen(false);
14238
+ reset();
14239
+ };
14240
+ const files = saved?.files || [];
14241
+ const missing = saved?.missing_files || [];
14242
+ const runText = saved?.name ? `Run skill ${saved.name} in Preview mode` : "";
14243
+ return (jsx(Modal, { onClose: handleClose, onPrimaryButtonClick: saved ? handleClose : handleSave, onSecondaryButtonClick: handleClose, open: isOpen, size: "small", title: "Upload Skill", primaryButtonLabel: saved ? "Done" : "Save the skill", secondaryButtonLabel: "Cancel", primaryButtonProps: { disabled: isSaving || (!saved && !hasSkill) }, secondaryButtonProps: { disabled: isSaving }, children: isSaving ? (jsx(Loader, { text: "Saving the skill..." })) : saved ? (jsxs("div", { style: { padding: "16px 20px", lineHeight: 1.5 }, children: [jsxs("p", { style: { margin: "0 0 8px" }, children: ["Saved ", jsx("b", { children: saved.name }), " (version ", saved.version, typeof saved.characters === "number" ? `, ${saved.characters.toLocaleString()} characters` : "", files.length ? `, with ${files.join(", ")}` : "", ")."] }), missing.length > 0 && (jsxs("p", { style: { margin: "0 0 8px" }, children: ["It refers to ", missing.join(", "), ", which was not uploaded."] })), saved.trigger && (jsxs("p", { style: { margin: "0 0 8px" }, children: ["It has a trigger: it ", saved.trigger_said, ". It is not on yet. To turn it on, send Iris:", " ", jsx("i", { children: saved.turn_on })] })), jsxs("div", { style: { display: "flex", gap: "8px", flexWrap: "wrap", marginTop: "12px" }, children: [runText && (jsxs(Button, { variant: "outlined", onClick: () => use(runText), children: ["Put \"", runText, "\" in the chat"] })), saved.trigger && saved.turn_on && (jsxs(Button, { variant: "outlined", onClick: () => use(saved.turn_on), children: ["Put \"", saved.turn_on, "\" in the chat"] }))] })] })) : (jsxs("div", { className: classes.uploadModalInnerSec, style: { height: "auto", minHeight: "150px" }, children: [jsx("input", { type: "file", ref: folderRef, onChange: (e) => {
14244
+ take(e.target.files);
14245
+ e.target.value = "";
14246
+ }, style: { display: "none" }, multiple: true, ...{ webkitdirectory: "", directory: "" } }), jsx("input", { type: "file", ref: filesRef, onChange: (e) => {
14247
+ take(e.target.files);
14248
+ e.target.value = "";
14249
+ }, style: { display: "none" }, multiple: true, accept: TEXT_EXTENSIONS.join(",") }), jsxs("div", { style: { display: "flex", gap: "8px", flexWrap: "wrap", justifyContent: "center" }, children: [jsx(Button, { variant: "outlined", onClick: () => folderRef.current?.click(), children: "Pick the skill's folder" }), jsx(Button, { variant: "outlined", onClick: () => filesRef.current?.click(), children: "Pick its files" })] }), paths.length > 0 ? (jsxs("div", { style: { marginTop: "12px", width: "100%" }, children: [jsx("ul", { style: { margin: 0, paddingLeft: "18px", maxHeight: "140px", overflowY: "auto" }, children: paths.map((path) => (jsx("li", { children: path }, path))) }), !hasSkill && jsx("p", { style: { margin: "8px 0 0" }, children: "No SKILL.md picked yet." }), skipped > 0 && (jsxs("p", { style: { margin: "8px 0 0" }, children: [skipped, " file", skipped === 1 ? " was" : "s were", " left out: a skill's files are text (", TEXT_EXTENSIONS.join(" "), ")."] }))] })) : (jsx("p", { style: { marginTop: "12px", textAlign: "center" }, children: "A skill is a SKILL.md and any files it refers to. Once saved, ask Iris to run it by name, now or on a schedule." })), error && jsxs("p", { style: { marginTop: "10px", color: "#b42318" }, children: ["Not saved: ", error.replace(/^not saved:\s*/i, "")] })] })) }));
14250
+ }
14251
+
13310
14252
  const useStyles$2 = makeStyles(() => ({
13311
14253
  input: {
13312
14254
  width: "100%",
@@ -14401,6 +15343,7 @@ const ChatbotInput = (props) => {
14401
15343
  const isTransitioningStageRef = useRef(false);
14402
15344
  const shouldClearCacheRef = useRef(false);
14403
15345
  const allFilterValuesRef = useRef([]);
15346
+ const initialValueOptionsRef = useRef([]);
14404
15347
  const windowStartRef = useRef(0);
14405
15348
  const INITIAL_DISPLAY_COUNT = 500;
14406
15349
  const LOAD_MORE_COUNT = 100;
@@ -14945,6 +15888,7 @@ const ChatbotInput = (props) => {
14945
15888
  setSelectionStage("values");
14946
15889
  setSelectedFilter(filterConfig);
14947
15890
  setCurrentOptions([]);
15891
+ initialValueOptionsRef.current = [];
14948
15892
  setSelectedOptions([]);
14949
15893
  setShowMentionSelect(true);
14950
15894
  setIsSelectOpen(true);
@@ -14974,10 +15918,13 @@ const ChatbotInput = (props) => {
14974
15918
  windowStartRef.current = 0;
14975
15919
  if (allValues.length > 2000) {
14976
15920
  allFilterValuesRef.current = allValues;
14977
- setCurrentOptions(allValues.slice(0, INITIAL_DISPLAY_COUNT));
15921
+ const initialSlice = allValues.slice(0, INITIAL_DISPLAY_COUNT);
15922
+ initialValueOptionsRef.current = initialSlice;
15923
+ setCurrentOptions(initialSlice);
14978
15924
  }
14979
15925
  else {
14980
15926
  allFilterValuesRef.current = [];
15927
+ initialValueOptionsRef.current = allValues;
14981
15928
  setCurrentOptions(allValues);
14982
15929
  }
14983
15930
  // Update dropdown position again after values are loaded (DOM might have shifted)
@@ -15730,7 +16677,7 @@ const ChatbotInput = (props) => {
15730
16677
  zIndex: 10000,
15731
16678
  }, children: selectionStage === "filter" ? (
15732
16679
  // Stage 1: Filter selection - always use Select
15733
- jsx(Select, { currentOptions: currentOptions.length > 0 ? currentOptions : [], setCurrentOptions: setCurrentOptions, initialOptions: currentOptions.length > 0 ? currentOptions : [], placeholder: "Select a filter...", handleChange: handleMentionSelect, isOpen: isSelectOpen, setIsOpen: setIsSelectOpen, selectedOptions: selectedOptions, setSelectedOptions: setSelectedOptions, isCloseWhenClickOutside: false, isWithSearch: true, isMulti: false, disabled: false, isLoading: false, emptyMessage: "No filters available" })) : selectionStage === "values" && selectedFilter?.display_type &&
16680
+ jsx(Select, { currentOptions: currentOptions.length > 0 ? currentOptions : [], setCurrentOptions: setCurrentOptions, initialOptions: formattedFilterOptions.length > 0 ? formattedFilterOptions : [], placeholder: "Select a filter...", handleChange: handleMentionSelect, isOpen: isSelectOpen, setIsOpen: setIsSelectOpen, selectedOptions: selectedOptions, setSelectedOptions: setSelectedOptions, isCloseWhenClickOutside: false, isWithSearch: true, isMulti: false, disabled: false, isLoading: false, emptyMessage: "No filters available" })) : selectionStage === "values" && selectedFilter?.display_type &&
15734
16681
  selectedFilter.display_type !== "dropdown" &&
15735
16682
  selectedFilter.display_type !== "autocompleteDropdown" &&
15736
16683
  selectedFilter.display_type !== "list" ? (
@@ -15817,7 +16764,7 @@ const ChatbotInput = (props) => {
15817
16764
  cursor: "pointer"
15818
16765
  }, children: "Cancel" })] })] })) : (
15819
16766
  // Stage 2: Value selection with dropdown - use Select
15820
- jsx(Select, { currentOptions: currentOptions.length > 0 ? currentOptions : [], setCurrentOptions: setCurrentOptions, initialOptions: currentOptions.length > 0 ? currentOptions : [], placeholder: isLoadingValues
16767
+ jsx(Select, { currentOptions: currentOptions.length > 0 ? currentOptions : [], setCurrentOptions: setCurrentOptions, initialOptions: initialValueOptionsRef.current.length > 0 ? initialValueOptionsRef.current : currentOptions, placeholder: isLoadingValues
15821
16768
  ? "Loading values..."
15822
16769
  : "Select values...", handleChange: handleMentionSelect, isOpen: isSelectOpen, setIsOpen: setIsSelectOpen, selectedOptions: selectedOptions, setSelectedOptions: setSelectedOptions, isCloseWhenClickOutside: false, isWithSearch: true, onMenuScrollToBottom: () => {
15823
16770
  const allValues = allFilterValuesRef.current;
@@ -16972,6 +17919,146 @@ const MinimizedChatWidget = ({ onExpand }) => {
16972
17919
  return (jsxs("div", { className: classes.widgetContainer, onClick: handleExpandClick, children: [jsxs("div", { className: classes.widgetHeader, children: [jsxs("div", { className: classes.headerLeft, children: [jsx("div", { className: !isCompleted ? classes.headerIconLogoSpin : classes.headerIconLogo, children: jsx(SvgMimimizedIconLogo, {}) }), jsx("span", { className: classes.headerText, children: isCompleted ? "Action completed" : actionLabel }), !isCompleted && (jsx("div", { className: classes.warningIcon, children: jsx(SvgStepError, {}) }))] }), jsx("button", { className: classes.minimizeBtn, onClick: handleMinimizeClick, "aria-label": "Minimize", children: jsx(SvgMinimizeDashIcon, {}) })] }), jsx("div", { className: classes.widgetContent, children: jsxs("div", { className: stepStatus === "step_form" ? classes.innerContentStepForm : classes.innerContent, children: [jsxs("div", { className: classes.innerFirstRow, children: [jsx("span", { className: classes.stepHeaderText, title: stepHeader, children: stepHeader }), jsx("button", { className: classes.expandBtn, onClick: handleExpandClick, "aria-label": "Expand chatbot", children: jsx(SvgExpandFullscreenIcon, {}) })] }), stepSubHeader && (jsxs("div", { className: classes.innerSecondRow, children: [jsxs("div", { className: stepStatus === "step_form" ? classes.subHeaderPillStepForm : classes.subHeaderPill, children: [stepStatus === "step_form" ? (jsx("div", { className: classes.exclamationIcon, children: jsx(SvgExclamationIcon, {}) })) : !isCompleted && (jsx("div", { className: classes.loaderIcon, children: jsx(SvgLoadingCircle, {}) })), jsx("span", { className: classes.subHeaderText, title: stepSubHeader, children: stepSubHeader })] }), elapsedTime && (jsx("span", { className: classes.timeText, children: elapsedTime }))] }))] }) })] }));
16973
17920
  };
16974
17921
 
17922
+ const PanelHeader = ({ title, actions = {}, onClose, isExpanded, onToggleExpand }) => {
17923
+ const classes = useAllocationPanelStyles();
17924
+ return (jsxs("div", { className: classes.panelHeader, children: [jsxs("div", { className: classes.panelHeaderLeft, children: [actions.preview && (jsx(VisibilityOutlinedIcon, { className: classes.panelHeaderIcon })), jsx("span", { className: classes.panelTitle, title: title, children: title })] }), jsxs("div", { className: classes.panelHeaderActions, children: [actions.expand_fullscreen && (jsx(IconButton, { className: classes.panelHeaderActionBtn, size: "small", onClick: onToggleExpand, children: isExpanded ? (jsx(CloseFullscreenIcon, { sx: { fontSize: 16 } })) : (jsx(OpenInFullIcon, { sx: { fontSize: 16 } })) })), jsx(IconButton, { className: classes.panelHeaderActionBtn, size: "small", onClick: onClose, children: jsx(CloseIcon, { sx: { fontSize: 16 } }) })] })] }));
17925
+ };
17926
+
17927
+ const ReportSummaryCard = ({ reportSummary }) => {
17928
+ const classes = useAllocationPanelStyles();
17929
+ if (!reportSummary)
17930
+ return null;
17931
+ const { badge, description, baseline_plan } = reportSummary;
17932
+ return (jsxs("div", { className: classes.reportSummaryCard, children: [badge && (jsx("span", { className: classes.reportBadge, children: badge.label })), description && (jsx("div", { className: classes.reportDescription, children: description })), baseline_plan && (jsxs("div", { className: classes.baselinePlanRow, children: [jsxs("span", { children: [baseline_plan.label, ":"] }), baseline_plan.link_url ? (jsx("span", { className: classes.baselinePlanLink, onClick: () => {
17933
+ if (baseline_plan.link_url) {
17934
+ window.open(baseline_plan.link_url, "_blank");
17935
+ }
17936
+ }, children: baseline_plan.value })) : (jsx("span", { children: baseline_plan.value }))] }))] }));
17937
+ };
17938
+
17939
+ const StructuredComparison = ({ content }) => {
17940
+ const classes = useAllocationPanelStyles();
17941
+ if (!content)
17942
+ return null;
17943
+ const { subtitle, scenario_groups = [] } = content;
17944
+ return (jsxs("div", { children: [subtitle && (jsx("div", { className: classes.comparisonSubtitle, children: subtitle })), scenario_groups.map((group, groupIndex) => (jsxs("div", { children: [jsx("div", { className: classes.scenarioLabel, children: group.scenario_label }), (group.comparisons || []).map((comparison, compIndex) => (jsxs("div", { className: classes.comparisonCard, children: [jsxs("div", { className: classes.comparisonParamRow, children: [jsx("span", { className: classes.comparisonParamName, children: comparison.parameter_name }), (comparison.tags || []).map((tag, tagIndex) => (jsx("span", { className: classes.comparisonTag, children: tag.label }, `tag-${tagIndex}`)))] }), jsxs("div", { className: classes.comparisonValues, children: [jsxs("div", { className: classes.comparisonValueBox, children: [jsx("div", { className: classes.comparisonValueLabel, children: comparison.baseline?.label }), jsx("div", { className: classes.comparisonValueText, children: comparison.baseline?.value })] }), jsx(ArrowForwardIcon, { className: classes.comparisonArrow }), jsxs("div", { className: classes.comparisonValueBox, children: [jsx("div", { className: classes.comparisonValueLabel, children: comparison.new_value?.label }), jsx("div", { className: classes.comparisonValueText, children: comparison.new_value?.value })] })] })] }, `comp-${groupIndex}-${compIndex}`)))] }, `group-${groupIndex}`)))] }));
17945
+ };
17946
+
17947
+ const PanelSection = ({ section }) => {
17948
+ const classes = useAllocationPanelStyles();
17949
+ if (!section)
17950
+ return null;
17951
+ const renderContent = () => {
17952
+ switch (section.content_type) {
17953
+ case "html":
17954
+ case "custom_html":
17955
+ return (jsx("div", { className: classes.panelHtmlContainer, children: jsx(HtmlContent, { bodyText: { content: section.content } }) }));
17956
+ case "structured":
17957
+ return jsx(StructuredComparison, { content: section.content });
17958
+ default:
17959
+ return null;
17960
+ }
17961
+ };
17962
+ return (jsxs(Accordion, { defaultExpanded: section.default_expanded, className: classes.sectionAccordion, disableGutters: true, children: [jsx(AccordionSummary, { expandIcon: jsx(ExpandMoreIcon, {}), className: classes.sectionSummary, children: jsx("span", { className: classes.sectionTitle, children: section.title }) }), jsx(AccordionDetails, { className: classes.sectionDetails, children: renderContent() })] }));
17963
+ };
17964
+
17965
+ const shiftChatbot = (panelEl) => {
17966
+ const chatbot = document.querySelector(".chatbot-component-container");
17967
+ if (!chatbot)
17968
+ return;
17969
+ const panelWidth = panelEl ? panelEl.offsetWidth : 0;
17970
+ const currentLeft = parseFloat(chatbot.style.left) || 0;
17971
+ chatbot.dataset.origLeft = chatbot.style.left;
17972
+ chatbot.style.transition = "left 0.3s ease";
17973
+ chatbot.style.left = (currentLeft - panelWidth) + "px";
17974
+ };
17975
+ const restoreChatbot = () => {
17976
+ const chatbot = document.querySelector(".chatbot-component-container");
17977
+ if (!chatbot)
17978
+ return;
17979
+ if (chatbot.dataset.origLeft) {
17980
+ chatbot.style.transition = "left 0.3s ease";
17981
+ chatbot.style.left = chatbot.dataset.origLeft;
17982
+ delete chatbot.dataset.origLeft;
17983
+ // Clean up transition after animation completes
17984
+ const onEnd = () => {
17985
+ chatbot.style.transition = "";
17986
+ chatbot.removeEventListener("transitionend", onEnd);
17987
+ };
17988
+ chatbot.addEventListener("transitionend", onEnd);
17989
+ }
17990
+ };
17991
+ const AllocationDetailPanel = () => {
17992
+ const classes = useAllocationPanelStyles();
17993
+ const [panelData, setPanelData] = useState(null);
17994
+ const [activeFooterAction, setActiveFooterAction] = useState(null);
17995
+ const [isExpanded, setIsExpanded] = useState(false);
17996
+ const panelRef = useRef(null);
17997
+ const handleOpen = useCallback((e) => {
17998
+ const { panelData: data } = e.detail || {};
17999
+ if (data) {
18000
+ setPanelData(data);
18001
+ }
18002
+ }, []);
18003
+ const handleClose = useCallback(() => {
18004
+ restoreChatbot();
18005
+ setPanelData(null);
18006
+ setIsExpanded(false);
18007
+ }, []);
18008
+ useEffect(() => {
18009
+ window.addEventListener("openAllocationDetailPanel", handleOpen);
18010
+ window.addEventListener("closeAllocationDetailPanel", handleClose);
18011
+ return () => {
18012
+ window.removeEventListener("openAllocationDetailPanel", handleOpen);
18013
+ window.removeEventListener("closeAllocationDetailPanel", handleClose);
18014
+ };
18015
+ }, [handleOpen, handleClose]);
18016
+ // Shift the chatbot once the panel has rendered
18017
+ useEffect(() => {
18018
+ if (panelData && panelRef.current) {
18019
+ // Use requestAnimationFrame to ensure the panel is laid out
18020
+ requestAnimationFrame(() => {
18021
+ shiftChatbot(panelRef.current);
18022
+ });
18023
+ }
18024
+ }, [panelData]);
18025
+ // Listen for direct clicks on the impact-ui collapse button
18026
+ useEffect(() => {
18027
+ if (!panelData)
18028
+ return;
18029
+ const collapseBtn = document.querySelector('button[aria-label="Collapse chatbot"]');
18030
+ if (!collapseBtn)
18031
+ return;
18032
+ const onCollapse = () => handleClose();
18033
+ collapseBtn.addEventListener("click", onCollapse);
18034
+ return () => collapseBtn.removeEventListener("click", onCollapse);
18035
+ }, [panelData, handleClose]);
18036
+ if (!panelData)
18037
+ return null;
18038
+ const footerActions = panelData.footer_actions || [
18039
+ { label: "Purge", variant: "outlined", action: "purge", options: [] },
18040
+ { label: "Finalize Plan", variant: "primary", action: "finalize", options: [] },
18041
+ ];
18042
+ const handleOptionClick = (option) => {
18043
+ setActiveFooterAction(null);
18044
+ window.dispatchEvent(new CustomEvent("allocationPanelAction", {
18045
+ detail: { value: option.value, label: option.label },
18046
+ }));
18047
+ };
18048
+ const handleFooterBtnClick = (btn) => {
18049
+ if (btn.options && btn.options.length > 0) {
18050
+ setActiveFooterAction(activeFooterAction === btn.action ? null : btn.action);
18051
+ }
18052
+ else {
18053
+ console.log("[AllocationPanel] footer action:", btn.action);
18054
+ }
18055
+ };
18056
+ const panel = (jsxs("div", { ref: panelRef, className: `${classes.panelContainer} ${isExpanded ? classes.panelExpanded : ""}`, "data-testid": "allocation-detail-panel", children: [jsx(PanelHeader, { title: panelData.title, actions: panelData.actions || {}, onClose: handleClose, isExpanded: isExpanded, onToggleExpand: () => setIsExpanded((prev) => !prev) }), jsxs("div", { className: classes.panelScrollBody, children: [jsx(ReportSummaryCard, { reportSummary: panelData.report_summary }), (panelData.sections || []).map((section) => (jsx(PanelSection, { section: section }, section.id)))] }), jsxs("div", { className: classes.panelFooter, children: [activeFooterAction && (jsx("div", { className: classes.optionsCard, children: footerActions
18057
+ .find((a) => a.action === activeFooterAction)
18058
+ ?.options?.map((opt, idx) => (jsxs("button", { className: classes.optionRow, onClick: () => handleOptionClick(opt), children: [jsx("span", { className: classes.optionIcon, children: "\u2606" }), opt.label] }, idx))) })), footerActions.map((btn, idx) => (jsx("button", { className: btn.variant === "primary" ? classes.footerBtnPrimary : classes.footerBtnOutlined, onClick: () => handleFooterBtnClick(btn), children: btn.label }, idx)))] })] }));
18059
+ return createPortal(panel, document.body);
18060
+ };
18061
+
16975
18062
  /**
16976
18063
  * SmartBot Redux reducer.
16977
18064
  * State shape and behaviour match the consumer's core/reducers/smartBotReducer.js exactly.
@@ -17045,6 +18132,9 @@ const SmartBot = (props) => {
17045
18132
  useState(false);
17046
18133
  useState(false);
17047
18134
  const [conversation, setConversation] = useState({});
18135
+ // "Upload Skill": offered only when the agent's /info says skills.upload (asked once per base URL)
18136
+ const [skillUploadOn, setSkillUploadOn] = useState(false);
18137
+ const [isSkillUploadOpen, setIsSkillUploadOpen] = useState(false);
17048
18138
  const { chatbotContext, currentAgentChatId, minimizedStreamData } = useSelector((state) => state.smartBotReducer);
17049
18139
  const savedFilterDashboard = useSelector(selectors?.getSavedFilterDashboard ?? NULL_SELECTOR);
17050
18140
  // Per-mode conversation ID tracking — prevents cross-mode contamination when
@@ -17163,6 +18253,7 @@ const SmartBot = (props) => {
17163
18253
  // Minimize the chat window when the user follows an in-app link from a bot response
17164
18254
  const handleMinimizeRequest = () => {
17165
18255
  setPartialClose(true);
18256
+ window.dispatchEvent(new CustomEvent("closeAllocationDetailPanel"));
17166
18257
  };
17167
18258
  window.addEventListener("stepFormStreamStart", handleStepFormStreamStart);
17168
18259
  window.addEventListener("stepFormStreamEnd", handleStepFormStreamEnd);
@@ -17602,6 +18693,29 @@ const SmartBot = (props) => {
17602
18693
  useEffect(() => {
17603
18694
  fetchCustomBotConfigurations();
17604
18695
  }, [baseUrl]);
18696
+ useEffect(() => {
18697
+ let live = true;
18698
+ if (!baseUrl) {
18699
+ setSkillUploadOn(false);
18700
+ return;
18701
+ }
18702
+ fetchSkillUploadOn(baseUrl).then((on) => {
18703
+ if (live)
18704
+ setSkillUploadOn(on);
18705
+ });
18706
+ return () => {
18707
+ live = false;
18708
+ };
18709
+ }, [baseUrl]);
18710
+ // kept apart from utilityList: handleUploadAccess sets that list from its first value once its access
18711
+ // check returns, which would drop an item added meanwhile
18712
+ const skillUploadItem = {
18713
+ key: "Upload Skill",
18714
+ onClick: () => {
18715
+ setIsSkillUploadOpen(true);
18716
+ },
18717
+ icon: (jsx("div", { className: classes.memoryModalIconDiv, children: jsx(SvgUploadIcon, { style: { width: 20, height: 20 } }) })),
18718
+ };
17605
18719
  // Sync showModal state with props.showModal OR props.invokeBot (backward compatibility)
17606
18720
  // Host app passes showModal prop, but some integrations may use invokeBot
17607
18721
  useEffect(() => {
@@ -17820,7 +18934,7 @@ const SmartBot = (props) => {
17820
18934
  fetchLegacyAgentInfo(); //Disabled temporarily since this was causing issue on homepage first render
17821
18935
  }
17822
18936
  }, [location]);
17823
- const handleSendMessage = async (userInput, userExplicitInput = {}, textWithColumnNames = "") => {
18937
+ const handleSendMessage = async (userInput, userExplicitInput = {}, textWithColumnNames = "", uiContext = null) => {
17824
18938
  try {
17825
18939
  // if (localStorage.getItem("isStreaming") === "true") {
17826
18940
  // displaySnackMessages(
@@ -17884,6 +18998,7 @@ const SmartBot = (props) => {
17884
18998
  userExplicitInput: userExplicitInput,
17885
18999
  textWithColumnNames: textWithColumnNames,
17886
19000
  answerMode: answerMode,
19001
+ ...(uiContext ? { uiContext } : {}),
17887
19002
  };
17888
19003
  // if(!isEmpty(userInput)) {
17889
19004
  // Clear the previous response's completed state so the incoming
@@ -17933,12 +19048,25 @@ const SmartBot = (props) => {
17933
19048
  sessionStorage.removeItem("stepForm_chatId");
17934
19049
  // dispatch(setChatbotContext({}));
17935
19050
  setUserInput(params?.text);
17936
- handleSendMessage(params?.text, params?.userExplicitInput, params?.textWithColumnNames);
19051
+ handleSendMessage(params?.text, params?.userExplicitInput, params?.textWithColumnNames, params?.uiContext);
17937
19052
  }
17938
19053
  catch (error) {
17939
19054
  console.error("onSendIconClick error", error);
17940
19055
  }
17941
19056
  };
19057
+ // A follow-up asked from a generated surface (SurfaceFrameContent's "iris:prompt"): sent as the user's next
19058
+ // message, with the surface's context as ui_context. Not while a turn runs or a form waits for its Submit.
19059
+ const surfacePromptRef = useRef(null);
19060
+ surfacePromptRef.current = (detail) => {
19061
+ if (!detail?.text || isStop || !isEmpty$1(chatbotContext))
19062
+ return;
19063
+ onSendIconClick({ text: detail.text, uiContext: detail.uiContext });
19064
+ };
19065
+ useEffect(() => {
19066
+ const onSurfacePrompt = (event) => surfacePromptRef.current?.(event.detail);
19067
+ window.addEventListener("iris:prompt", onSurfacePrompt);
19068
+ return () => window.removeEventListener("iris:prompt", onSurfacePrompt);
19069
+ }, []);
17942
19070
  const onStopIconClick = (params) => {
17943
19071
  try {
17944
19072
  setIsStop(false);
@@ -18172,9 +19300,35 @@ const SmartBot = (props) => {
18172
19300
  if (!root)
18173
19301
  return;
18174
19302
  const collapseBtn = root.querySelector('button[aria-label="Collapse chatbot"]');
18175
- if (collapseBtn)
19303
+ if (collapseBtn) {
18176
19304
  collapseBtn.click();
19305
+ window.dispatchEvent(new CustomEvent("closeAllocationDetailPanel"));
19306
+ }
18177
19307
  }, []);
19308
+ // Expand the chatbot to its full docked view by programmatically clicking
19309
+ // impact-ui's "Expand chatbot" button. Used when the allocation panel opens
19310
+ // from minimized state.
19311
+ const expandChatBotIfCollapsed = useCallback(() => {
19312
+ setShowModal(true);
19313
+ setPartialClose(false);
19314
+ // Use a short delay so the chatbot DOM renders before we look for the button
19315
+ setTimeout(() => {
19316
+ const root = smartBotWrapperRef.current;
19317
+ if (!root)
19318
+ return;
19319
+ const expandBtn = root.querySelector('button[aria-label="Expand chatbot"]');
19320
+ if (expandBtn) {
19321
+ expandBtn.click();
19322
+ }
19323
+ }, 100);
19324
+ }, []);
19325
+ // Listen for smartBotMaximize events (e.g. from allocation plan card)
19326
+ useEffect(() => {
19327
+ window.addEventListener("smartBotMaximize", expandChatBotIfCollapsed);
19328
+ return () => {
19329
+ window.removeEventListener("smartBotMaximize", expandChatBotIfCollapsed);
19330
+ };
19331
+ }, [expandChatBotIfCollapsed]);
18178
19332
  // Auto-collapse to draggable mode when the user interacts outside the bot.
18179
19333
  useEffect(() => {
18180
19334
  const handleOutsideInteraction = (e) => {
@@ -18196,6 +19350,9 @@ const SmartBot = (props) => {
18196
19350
  // Ignore clicks inside the expanded table modal portal
18197
19351
  if (e.target.closest?.(".test-modal"))
18198
19352
  return;
19353
+ // Ignore clicks inside the allocation detail panel
19354
+ if (e.target.closest?.('[data-testid="allocation-detail-panel"]'))
19355
+ return;
18199
19356
  collapseChatBotIfExpanded();
18200
19357
  };
18201
19358
  document.addEventListener("mousedown", handleOutsideInteraction, true);
@@ -18216,7 +19373,7 @@ const SmartBot = (props) => {
18216
19373
  return (jsxs(Fragment, { children: [partialClose && (minimizedStreamData?.isStreaming || minimizedStreamData?.stepStatus === "step_form") && (jsx(MinimizedChatWidget, { onExpand: () => {
18217
19374
  setShowModal(true);
18218
19375
  setPartialClose(false);
18219
- } })), jsxs("div", { ref: smartBotWrapperRef, className: `${classes.agentStyleOverride} ${partialClose || !(showModal || forceOpen) ? classes.hideBotStyle : ""} `, children: [jsx(RenameModal, { open: renameOpen, renameValue: renameValue, setRenameValue: setRenameValue, onConfirm: handleRenameConfirm, onCancel: handleRenameCancel }), jsx(DeleteConfirmModal, { open: deleteOpen, onConfirm: handleDeleteConfirm, onCancel: handleDeleteCancel }), jsx(MemoryModal, { isModalOpen: isModalOpen, setIsModalOpen: setIsModalOpen, displaySnackMessages: displaySnackMessages }), jsx(UploadModal, { isUploadModalOpen: isUploadModalOpen, setIsUploadModalOpen: setIsUploadModalOpen, displaySnackMessages: displaySnackMessages }), jsx(ChatBotComponent, { isFullWidth: forceOpen, userName: userName, showHistoryPanel: enableMultiChat, customInputComponent: currentMode === "agent" && !showSavedFilters ? (jsx(ChatbotInput, { newChatScreen: newChatScreen, inputValue: userInput, setInputValue: setUserInput, isStopIcon: isStop, onSendIconClick: onSendIconClick, onStopIconClick: onStopIconClick, currentMode: currentMode, filterOptions: filterOptions,
19376
+ } })), jsxs("div", { ref: smartBotWrapperRef, className: `${classes.agentStyleOverride} ${partialClose || !(showModal || forceOpen) ? classes.hideBotStyle : ""} `, children: [jsx(RenameModal, { open: renameOpen, renameValue: renameValue, setRenameValue: setRenameValue, onConfirm: handleRenameConfirm, onCancel: handleRenameCancel }), jsx(DeleteConfirmModal, { open: deleteOpen, onConfirm: handleDeleteConfirm, onCancel: handleDeleteCancel }), jsx(MemoryModal, { isModalOpen: isModalOpen, setIsModalOpen: setIsModalOpen, displaySnackMessages: displaySnackMessages }), jsx(UploadModal, { isUploadModalOpen: isUploadModalOpen, setIsUploadModalOpen: setIsUploadModalOpen, displaySnackMessages: displaySnackMessages }), skillUploadOn && (jsx(SkillUploadModal, { isOpen: isSkillUploadOpen, setIsOpen: setIsSkillUploadOpen, baseUrl: baseUrl, displaySnackMessages: displaySnackMessages, onUseText: (text) => setUserInput(text) })), jsx(ChatBotComponent, { isFullWidth: forceOpen, userName: userName, showHistoryPanel: enableMultiChat, isConversationLoading: conversationLoading, customInputComponent: currentMode === "agent" && !showSavedFilters ? (jsx(ChatbotInput, { newChatScreen: newChatScreen, inputValue: userInput, setInputValue: setUserInput, isStopIcon: isStop, onSendIconClick: onSendIconClick, onStopIconClick: onStopIconClick, currentMode: currentMode, filterOptions: filterOptions,
18220
19377
  // onSaveClick={saveCurrentChat}
18221
19378
  savedFilterSets: savedFilterSets, selectedFilterSet: selectedFilterSet, onFilterSetSelect: (filterSet) => setSelectedFilterSet(filterSet), onClearFilterSet: () => setSelectedFilterSet(null), onTriggerRefresh: triggerRefreshAction, answerMode: answerMode, setAnswerMode: setAnswerMode })) : showSavedFilters ? jsx(Fragment, {}) : null, isChatBotOpen: showModal || forceOpen, historyPanelData: historyPanelData, onHistorySearchChange: (params) => { console.log("History Search Change", params); }, onHistorySelectConversation: (params) => {
18222
19379
  const convId = params?.conversation_id;
@@ -18322,16 +19479,17 @@ const SmartBot = (props) => {
18322
19479
  dispatch(setMinimizedStreamData(null));
18323
19480
  }
18324
19481
  setPartialClose(true);
19482
+ window.dispatchEvent(new CustomEvent("closeAllocationDetailPanel"));
18325
19483
  }
18326
19484
  },
18327
19485
  // assistantChats={assistantChats}
18328
19486
  onSendIconClick: onSendIconClick, conversation: conversation, onModuleClick: (id, name, param) => {
18329
19487
  // activeTab.current.activeTab = name.toLowerCase();
18330
19488
  handleModuleSelect(name);
18331
- }, moduleList: modules, tabList: tabList, utilityList: utilityList, isAssistantThinking: false, isCustomScreen: showChatPlaceholder ? showChatPlaceholder : showSavedFilters, customScreenJsx: showChatPlaceholder ?
19489
+ }, moduleList: modules, tabList: tabList, utilityList: skillUploadOn ? [...utilityList, skillUploadItem] : utilityList, isAssistantThinking: false, isCustomScreen: showChatPlaceholder ? showChatPlaceholder : showSavedFilters, customScreenJsx: showChatPlaceholder ?
18332
19490
  jsx(ChatPlaceholder, { dateFormat: dateFormat, chatDataRef: chatDataRef, currentMode: currentMode, setShowChatPlaceholder: setShowChatPlaceholder, setLoader: setLoader, setCurrentAgentId: setCurrentAgentId, baseUrl: baseUrl, setBaseUrl: setBaseUrl, setCurrentSessionId: setCurrentSessionId, customChatConfig: customChatConfig, chatDataInfoRef: chatDataInfoRef, setChatDataState: setChatDataState, userInput: userInput, legacyAgentScreen: legacyAgentScreen, activeConversationId: activeConversationId, chatBodyRef: chatBodyRef, chatbotContext: chatbotContext, setInitValue: setInitValue, setSessionId: setSessionId, thinkingContent: thinkingContext?.thinkingContent, setThinkingContent: setThinkingContent, isThinking: isThinking, setIsThinking: setIsThinking, chatId: chatId, setChatId: setChatId, isStop: isStop, setIsStop: setIsStop, functionsRef: functionsRef, functionsState: functionsState, setFunctionsState: setFunctionsState, thinkingHeaderMessage: thinkingContext?.thinkingHeaderMessage, setThinkingHeaderMessage: setThinkingHeaderMessage, uniqueChatId: uniqueChatId, setUniqueChatId: setUniqueChatId, fieldNumber: fieldNumber, setFieldNumber: setFieldNumber, setAdditionalArgs: setAdditionalArgs, displayQuestions: displayQuestions, questions: questions, setActiveConversationId: setActiveConversationId, selectedFilterSet: selectedFilterSet, answerMode: answerMode })
18333
19491
  :
18334
- components?.FilterComponent ? jsx(components.FilterComponent, { savedFilterSets: savedFilterSets, partialClose: partialClose, chatBotWidth: chatBotWidth, onSetFilterConfiguration: callbacks?.onSetFilterConfiguration }) : null, inputText: userInput, threadList: ["Home"], hideMenuArrow: hideMenu, newChatScreen: newChatScreen, isModuleListLoading: modulesLoading, suggestionBanner: {
19492
+ components?.FilterComponent ? jsx(components.FilterComponent, { savedFilterSets: savedFilterSets, partialClose: partialClose, chatBotWidth: chatBotWidth, onSetFilterConfiguration: callbacks?.onSetFilterConfiguration }) : null, inputText: userInput, threadList: ["Home"], hideMenuArrow: true, newChatScreen: newChatScreen, isModuleListLoading: modulesLoading, suggestionBanner: {
18335
19493
  freeTextHeading: "Try adding more details :",
18336
19494
  freeTextContent: "Iris works better when you provide more context and pointed questions",
18337
19495
  }, isStopIcon: isStop, onStopIconClick: onStopIconClick, footerText: "AI-generated responses may contain errors\u2014please verify important information", showSuggestionBanner: showSavedFilters ? false : showSuggestionBanner, onCloseSuggestionBanner: () => {
@@ -18352,7 +19510,8 @@ const SmartBot = (props) => {
18352
19510
  setChatBotWidth(params);
18353
19511
  }, onMinimiseChatBot: () => {
18354
19512
  setPartialClose(true);
18355
- } })] })] }));
19513
+ window.dispatchEvent(new CustomEvent("closeAllocationDetailPanel"));
19514
+ } })] }), jsx(AllocationDetailPanel, {})] }));
18356
19515
  };
18357
19516
 
18358
19517
  export { ChatbotProvider, clearPersistedFormValues, SmartBot as default, setChatbotContext, setChatbotFilterOptions, setCurrentAgentChatId, setHierarchyKeyValue, setIsSmartBotRestricted, setMinimizedStreamData, setPersistedFormValues, setSavedFilterSets, setSmartBotActive, setStepFormRestreamPayload, setStepFormStreamData, setThinkingContext, smartBotInitialState, smartBotReducer, useChatbotDeps };