@cognizant-ai-lab/ui-common 1.9.0 → 1.11.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.
Files changed (70) hide show
  1. package/dist/components/AgentChat/ChatCommon/ChatCommon.js +32 -10
  2. package/dist/components/AgentChat/ChatCommon/Const.d.ts +1 -0
  3. package/dist/components/AgentChat/ChatCommon/Const.js +2 -0
  4. package/dist/components/AgentChat/ChatCommon/SlyDataDialog.d.ts +29 -0
  5. package/dist/components/AgentChat/ChatCommon/SlyDataDialog.js +150 -0
  6. package/dist/components/AgentChat/ChatCommon/Thinking.js +2 -2
  7. package/dist/components/AgentChat/Common/LlmChatButton.d.ts +4 -6
  8. package/dist/components/AgentChat/Common/LlmChatButton.js +0 -2
  9. package/dist/components/AgentChat/Common/Utils.d.ts +0 -11
  10. package/dist/components/AgentChat/Common/Utils.js +0 -16
  11. package/dist/components/Common/ConfirmationModal.d.ts +3 -2
  12. package/dist/components/Common/Footer.js +4 -0
  13. package/dist/components/Common/Navbar.d.ts +2 -1
  14. package/dist/components/Common/Navbar.js +3 -3
  15. package/dist/components/ErrorPage/ErrorPage.js +4 -4
  16. package/dist/components/MultiAgentAccelerator/AgentFlow/AgentFlow.d.ts +7 -7
  17. package/dist/components/MultiAgentAccelerator/AgentFlow/AgentFlow.js +161 -376
  18. package/dist/components/MultiAgentAccelerator/AgentFlow/AgentNode.js +7 -5
  19. package/dist/components/MultiAgentAccelerator/AgentFlow/GraphLayouts.js +10 -7
  20. package/dist/components/MultiAgentAccelerator/AgentFlow/GraphStructure.d.ts +1 -1
  21. package/dist/components/MultiAgentAccelerator/Editor/AgentNodeEditor.d.ts +24 -0
  22. package/dist/components/MultiAgentAccelerator/Editor/AgentNodeEditor.js +128 -0
  23. package/dist/components/MultiAgentAccelerator/Editor/NetworkEditorDock.d.ts +21 -0
  24. package/dist/components/MultiAgentAccelerator/Editor/NetworkEditorDock.js +305 -0
  25. package/dist/components/MultiAgentAccelerator/MultiAgentAccelerator.js +112 -116
  26. package/dist/components/MultiAgentAccelerator/NeuroSanStudioCallout.d.ts +2 -0
  27. package/dist/components/MultiAgentAccelerator/NeuroSanStudioCallout.js +38 -0
  28. package/dist/components/MultiAgentAccelerator/PanelSeparator.d.ts +5 -0
  29. package/dist/components/MultiAgentAccelerator/PanelSeparator.js +46 -0
  30. package/dist/components/MultiAgentAccelerator/Sidebar/AgentNetworkTreeItem.d.ts +2 -0
  31. package/dist/components/MultiAgentAccelerator/Sidebar/AgentNetworkTreeItem.js +23 -31
  32. package/dist/components/MultiAgentAccelerator/Sidebar/Sidebar.d.ts +0 -2
  33. package/dist/components/MultiAgentAccelerator/Sidebar/Sidebar.js +11 -9
  34. package/dist/components/MultiAgentAccelerator/Sidebar/TreeBuilder.d.ts +2 -2
  35. package/dist/components/MultiAgentAccelerator/Sidebar/TreeBuilder.js +13 -13
  36. package/dist/components/MultiAgentAccelerator/TemporaryNetworks.d.ts +3 -17
  37. package/dist/components/MultiAgentAccelerator/TemporaryNetworks.js +17 -40
  38. package/dist/components/MultiAgentAccelerator/Tour/MainTourSteps.js +10 -8
  39. package/dist/components/MultiAgentAccelerator/const.d.ts +12 -11
  40. package/dist/components/MultiAgentAccelerator/const.js +24 -22
  41. package/dist/components/Settings/ApiKeyErrorBanner.d.ts +22 -0
  42. package/dist/components/Settings/ApiKeyErrorBanner.js +26 -0
  43. package/dist/components/Settings/ApiKeyInput.d.ts +5 -2
  44. package/dist/components/Settings/ApiKeyInput.js +10 -4
  45. package/dist/components/Settings/SettingsDialog.js +22 -5
  46. package/dist/const.d.ts +0 -1
  47. package/dist/const.js +0 -1
  48. package/dist/controller/llm/Providers.d.ts +19 -2
  49. package/dist/controller/llm/Providers.js +45 -31
  50. package/dist/state/Announcements.d.ts +24 -0
  51. package/dist/state/Announcements.js +29 -0
  52. package/dist/state/ChatHistory.d.ts +10 -1
  53. package/dist/state/ChatHistory.js +8 -0
  54. package/dist/state/Environment.d.ts +2 -0
  55. package/dist/state/Environment.js +2 -0
  56. package/dist/state/Settings.d.ts +14 -0
  57. package/dist/state/Settings.js +6 -2
  58. package/dist/state/TemporaryNetworks.js +12 -21
  59. package/dist/tsconfig.build.tsbuildinfo +1 -1
  60. package/dist/utils/AgentName.d.ts +17 -0
  61. package/dist/utils/AgentName.js +46 -0
  62. package/dist/utils/Authentication.d.ts +7 -0
  63. package/dist/utils/Authentication.js +19 -5
  64. package/dist/utils/SlyData.d.ts +56 -0
  65. package/dist/utils/SlyData.js +106 -0
  66. package/package.json +7 -6
  67. package/dist/components/MultiAgentAccelerator/AgentNodePopup.d.ts +0 -30
  68. package/dist/components/MultiAgentAccelerator/AgentNodePopup.js +0 -80
  69. package/dist/components/MultiAgentAccelerator/Sidebar/ImportNetworkModal.d.ts +0 -67
  70. package/dist/components/MultiAgentAccelerator/Sidebar/ImportNetworkModal.js +0 -585
@@ -27,7 +27,6 @@ import { keyframes, styled, useTheme } from "@mui/material/styles";
27
27
  import Tooltip from "@mui/material/Tooltip";
28
28
  import Typography from "@mui/material/Typography";
29
29
  import { Handle, Position } from "@xyflow/react";
30
- import { useState } from "react";
31
30
  import { usePalette, useSettingsStore } from "../../../state/Settings.js";
32
31
  import { isLightColor } from "../../../Theme/Theme.js";
33
32
  import { getZIndex } from "../../../utils/zIndexLayers.js";
@@ -154,7 +153,6 @@ export const AgentNode = (props) => {
154
153
  const glowColor = isLightColor(theme.palette.background.default)
155
154
  ? theme.palette.common.black
156
155
  : theme.palette.common.white;
157
- const [isHovered, setIsHovered] = useState(false);
158
156
  // Insert zero-width spaces into the agent name to give the browser hints where to wrap.
159
157
  const wrappedAgentName = agentName
160
158
  // Allow wrap after underscore
@@ -165,7 +163,7 @@ export const AgentNode = (props) => {
165
163
  .replaceAll(/(?<abbr>[A-Z])(?<word>[A-Z][a-z])/gu, `$<abbr>${ZERO_WIDTH_SPACE}$<word>`);
166
164
  const height = NODE_HEIGHT * (isFrontman ? FRONTMAN_SIZE_MULTIPLIER : 1.0);
167
165
  const width = height;
168
- const getEditButton = () => (_jsx(Tooltip, { title: "Edit", placement: "top", disableInteractive: true, children: _jsx(IconButton, { sx: {
166
+ const getEditButton = () => (_jsx(Tooltip, { title: "Edit", placement: "top", disableInteractive: true, children: _jsx(IconButton, { className: "agent-node-edit-icon", "aria-hidden": true, tabIndex: -1, sx: {
169
167
  position: "absolute",
170
168
  top: 0,
171
169
  right: 0,
@@ -197,13 +195,17 @@ export const AgentNode = (props) => {
197
195
  width,
198
196
  zIndex: getZIndex(1, theme),
199
197
  }, children: wrappedAgentName }) }));
200
- const getNode = () => (_jsxs(AnimatedNode, { id: agentId, "data-testid": agentId, glowColor: glowColor, isActive: isActiveAgent, onMouseEnter: () => setIsHovered(true), onMouseLeave: () => setIsHovered(false), sx: {
198
+ const getNode = () => (_jsxs(AnimatedNode, { id: agentId, "data-testid": agentId, glowColor: glowColor, isActive: isActiveAgent, sx: {
201
199
  backgroundColor,
202
200
  color,
203
201
  cursor: isEditable ? "pointer" : "grab",
204
202
  height,
205
203
  width,
206
204
  zIndex: getZIndex(1, theme),
207
- }, children: [getDisplayAsIcon(), isHovered && isEditable && getEditButton(), _jsx(Handle, { id: `${agentId}-left-handle`, position: Position.Left, type: "source", style: { visibility: handleVisibility } }), _jsx(Handle, { id: `${agentId}-right-handle`, position: Position.Right, type: "source", style: { visibility: handleVisibility } }), _jsx(Handle, { id: `${agentId}-top-handle`, position: Position.Top, type: "source", style: { visibility: handleVisibility } }), _jsx(Handle, { id: `${agentId}-bottom-handle`, position: Position.Bottom, type: "source", style: { visibility: handleVisibility } })] }));
205
+ // Reveal the edit icon on hover, or when a keyboard user tabs to the node.
206
+ "& .agent-node-edit-icon": { opacity: 0, transition: "opacity 0.15s ease-in-out" },
207
+ "&:hover .agent-node-edit-icon": { opacity: 1 },
208
+ ".react-flow__node:focus-visible & .agent-node-edit-icon": { opacity: 1 },
209
+ }, children: [getDisplayAsIcon(), isEditable && getEditButton(), _jsx(Handle, { id: `${agentId}-left-handle`, position: Position.Left, type: "source", style: { visibility: handleVisibility } }), _jsx(Handle, { id: `${agentId}-right-handle`, position: Position.Right, type: "source", style: { visibility: handleVisibility } }), _jsx(Handle, { id: `${agentId}-top-handle`, position: Position.Top, type: "source", style: { visibility: handleVisibility } }), _jsx(Handle, { id: `${agentId}-bottom-handle`, position: Position.Bottom, type: "source", style: { visibility: handleVisibility } })] }));
208
210
  return (_jsxs(_Fragment, { children: [getNode(), getNodeName()] }));
209
211
  };
@@ -20,7 +20,8 @@ import dagre from "@dagrejs/dagre";
20
20
  import { MarkerType } from "@xyflow/react";
21
21
  import cloneDeep from "lodash-es/cloneDeep.js";
22
22
  import { FRONTMAN_SIZE_MULTIPLIER, NODE_HEIGHT, NODE_WIDTH } from "./AgentNode.js";
23
- import { cleanUpAgentName, KNOWN_MESSAGE_TYPES_FOR_PLASMA } from "../../AgentChat/Common/Utils.js";
23
+ import { cleanUpAgentName } from "../../../utils/AgentName.js";
24
+ import { KNOWN_MESSAGE_TYPES_FOR_PLASMA } from "../../AgentChat/Common/Utils.js";
24
25
  import { BASE_RADIUS, DEFAULT_FRONTMAN_X_POS, DEFAULT_FRONTMAN_Y_POS, LEVEL_SPACING } from "../const.js";
25
26
  import { getFrontman, getParentAgents, getParents } from "./GraphStructure.js";
26
27
  import { isEditableAgent } from "../TemporaryNetworks.js";
@@ -75,6 +76,8 @@ const getEdgeProperties = (sourceId, targetId, sourceHandle, targetHandle, isAni
75
76
  type: isAnimated ? "plasmaEdge" : undefined,
76
77
  };
77
78
  };
79
+ // An agent is editable if it belongs to a temporary network and is of an editable type.
80
+ const isNodeEditable = (displayAs, isTemporaryNetwork) => isTemporaryNetwork && isEditableAgent(displayAs);
78
81
  export const layoutRadial = ({ agentCounts, agentIconSuggestions = null, agentsInNetwork, currentConversations, isAgentNetworkDesignerMode, isAwaitingLlm, isTemporaryNetwork = false, thoughtBubbleEdges, useNativeNames, }) => {
79
82
  const nodesInNetwork = [];
80
83
  const edgesInNetwork = [];
@@ -119,6 +122,7 @@ export const layoutRadial = ({ agentCounts, agentIconSuggestions = null, agentsI
119
122
  const x = DEFAULT_FRONTMAN_X_POS + radius * Math.cos(angle);
120
123
  const y = DEFAULT_FRONTMAN_Y_POS + radius * Math.sin(angle);
121
124
  const isFrontman = frontman?.origin === nodeId;
125
+ const displayAs = agentsInNetwork.find((a) => a.origin === nodeId)?.display_as;
122
126
  const parentNodes = getParents(nodeId, parentAgents);
123
127
  // Create an edge from each parent node to this node
124
128
  for (const parentNode of parentNodes) {
@@ -159,13 +163,12 @@ export const layoutRadial = ({ agentCounts, agentIconSuggestions = null, agentsI
159
163
  agentCounts,
160
164
  agentName: useNativeNames ? nodeId : cleanUpAgentName(nodeId),
161
165
  depth,
162
- displayAs: agentsInNetwork.find((a) => a.origin === nodeId)?.display_as,
166
+ displayAs,
163
167
  // Use current conversations for node highlighting (cleared at end)
164
168
  getConversations: () => currentConversations,
165
169
  isAwaitingLlm,
166
170
  agentIconSuggestion: agentIconSuggestions?.[nodeId],
167
- isEditable: isTemporaryNetwork &&
168
- isEditableAgent(agentsInNetwork.find((a) => a.origin === nodeId)?.display_as),
171
+ isEditable: isNodeEditable(displayAs, isTemporaryNetwork),
169
172
  },
170
173
  // position: allow for Frontman being larger
171
174
  position: isFrontman
@@ -193,7 +196,7 @@ export const layoutLinear = ({ agentCounts, agentIconSuggestions = null, agentsI
193
196
  // Do these calculations outside the loop for efficiency
194
197
  const parentAgents = getParentAgents(agentsInNetwork);
195
198
  const frontman = getFrontman(agentsInNetwork);
196
- agentsInNetwork.forEach(({ origin: nodeId }) => {
199
+ agentsInNetwork.forEach(({ display_as: displayAs, origin: nodeId }) => {
197
200
  const parentIds = getParents(nodeId, parentAgents);
198
201
  const isFrontman = frontman?.origin === nodeId;
199
202
  nodesInNetwork.push({
@@ -202,13 +205,13 @@ export const layoutLinear = ({ agentCounts, agentIconSuggestions = null, agentsI
202
205
  data: {
203
206
  agentCounts,
204
207
  agentName: useNativeNames ? nodeId : cleanUpAgentName(nodeId),
205
- displayAs: agentsInNetwork.find((a) => a.origin === nodeId)?.display_as,
208
+ displayAs,
206
209
  // Use current conversations for node highlighting (cleared at end)
207
210
  getConversations: () => currentConversations,
208
211
  isAwaitingLlm,
209
212
  depth: undefined, // Depth will be computed later,
210
213
  agentIconSuggestion: agentIconSuggestions?.[nodeId],
211
- isEditable: isTemporaryNetwork && isEditableAgent(agentsInNetwork.find((a) => a.origin === nodeId)?.display_as),
214
+ isEditable: isNodeEditable(displayAs, isTemporaryNetwork),
212
215
  },
213
216
  position: isFrontman ? { x: DEFAULT_FRONTMAN_X_POS, y: DEFAULT_FRONTMAN_Y_POS } : { x: 0, y: 0 },
214
217
  style: {
@@ -9,7 +9,7 @@ export declare const getParentAgents: <T extends ConnectivityInfo>(agents: reado
9
9
  *
10
10
  * Consumed by the graph layouts (to seed the depth-0 node) and by the network import flow.
11
11
  */
12
- export declare const getFrontman: <T extends ConnectivityInfo>(agents: readonly T[]) => T | undefined;
12
+ export declare const getFrontman: (agents: readonly ConnectivityInfo[]) => ConnectivityInfo | undefined;
13
13
  /**
14
14
  * Returns the "origins" (node names) of the _immediate_ parents of a node in the agent network. Grandparents and
15
15
  * higher are not included.
@@ -0,0 +1,24 @@
1
+ import { Dispatch, FC, SetStateAction } from "react";
2
+ import { AgentNetworkDefinitionEntry } from "../const.js";
3
+ export interface AgentNodeEditorProps {
4
+ readonly agentId: string;
5
+ /** The agent's display name — shown read-only in the dialog header area. */
6
+ readonly agentName: string;
7
+ /** Whether the dialog is open. */
8
+ readonly isOpen: boolean;
9
+ /** Initial instructions text shown in the editable field. Defaults to an empty string. */
10
+ readonly initialInstructions?: string;
11
+ /** Initial description text shown in the editable field. Defaults to an empty string. */
12
+ readonly initialDescription?: string;
13
+ readonly networkId: string;
14
+ readonly onSaveAgent: (agentName: string, updated: AgentNetworkDefinitionEntry[], agentNetworkName: string | undefined, signal: AbortSignal) => Promise<void>;
15
+ readonly setIsPopupOpen: Dispatch<SetStateAction<boolean>>;
16
+ }
17
+ /**
18
+ * A popup dialog for viewing and editing an agent node's instructions and description.
19
+ *
20
+ * - Agent name is displayed read-only in the dialog header.
21
+ * - Both instructions and description are editable.
22
+ * - Saving updates the temporary definition and delegates persistence to `onSaveAgent`
23
+ */
24
+ export declare const AgentNodeEditor: FC<AgentNodeEditorProps>;
@@ -0,0 +1,128 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ /*
3
+ Copyright 2025 Cognizant Technology Solutions Corp, www.cognizant.com.
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
16
+ */
17
+ import Box from "@mui/material/Box";
18
+ import Button from "@mui/material/Button";
19
+ import CircularProgress from "@mui/material/CircularProgress";
20
+ import TextField from "@mui/material/TextField";
21
+ import { useEffect, useRef, useState } from "react";
22
+ import { useTempNetworksStore } from "../../../state/TemporaryNetworks.js";
23
+ import { ConfirmationModal } from "../../Common/ConfirmationModal.js";
24
+ import { MUIDialog } from "../../Common/MUIDialog.js";
25
+ import { NotificationType, sendNotification } from "../../Common/notification.js";
26
+ //#endregion: Types
27
+ //#region: Constants
28
+ const AGENT_SAVE_TIMEOUT_MS = 60_000;
29
+ //#endregion: Constants
30
+ /**
31
+ * A popup dialog for viewing and editing an agent node's instructions and description.
32
+ *
33
+ * - Agent name is displayed read-only in the dialog header.
34
+ * - Both instructions and description are editable.
35
+ * - Saving updates the temporary definition and delegates persistence to `onSaveAgent`
36
+ */
37
+ export const AgentNodeEditor = ({ agentId, agentName, initialDescription = "", initialInstructions = "", isOpen, networkId, onSaveAgent, setIsPopupOpen, }) => {
38
+ const [instructionsText, setInstructionsText] = useState(initialInstructions);
39
+ const [descriptionText, setDescriptionText] = useState(initialDescription);
40
+ const isDirty = instructionsText !== initialInstructions || descriptionText !== initialDescription;
41
+ // True, while the agent-edit request is in-flight so we can disable the Save button.
42
+ const [isSavingAgent, setIsSavingAgent] = useState(false);
43
+ // AbortController for the in-flight save request — stored in a ref so handlePopupClose can cancel it.
44
+ const saveAbortControllerRef = useRef(null);
45
+ const [displayConfirmationModal, setDisplayConfirmationModal] = useState(false);
46
+ const tempNetworks = useTempNetworksStore((state) => state.tempNetworks);
47
+ const updateTempNetworkDefinition = useTempNetworksStore((state) => state.updateTempNetworkDefinition);
48
+ // Keep local fields in sync when the dialog opens or if initial values change while open.
49
+ // Guarding on isOpen prevents resetting the text during the close animation, which would cause a visible flash.
50
+ useEffect(() => {
51
+ if (isOpen) {
52
+ setInstructionsText(initialInstructions);
53
+ setDescriptionText(initialDescription);
54
+ }
55
+ }, [initialInstructions, initialDescription, isOpen]);
56
+ const onSave = async () => {
57
+ if (!agentId)
58
+ return;
59
+ // Find the temp network entry for the currently selected network.
60
+ const currentTempNetwork = networkId
61
+ ? tempNetworks.find((n) => n.agentInfo.agent_name === networkId)
62
+ : undefined;
63
+ // Produce a new array with the saved agent's fields updated; all other entries pass through unchanged.
64
+ const currentDefinitions = currentTempNetwork?.agentNetworkDefinition ?? [];
65
+ const updatedDefinitions = currentDefinitions.map((entry) => entry.origin === agentId ? { ...entry, instructions: instructionsText, description: descriptionText } : entry);
66
+ if (networkId) {
67
+ updateTempNetworkDefinition(networkId, updatedDefinitions);
68
+ }
69
+ setIsSavingAgent(true);
70
+ const saveController = new AbortController();
71
+ saveAbortControllerRef.current = saveController;
72
+ const saveTimeoutId = setTimeout(() => saveController.abort(new DOMException("Save timed out", "TimeoutError")), AGENT_SAVE_TIMEOUT_MS);
73
+ try {
74
+ await onSaveAgent(agentName, updatedDefinitions, currentTempNetwork?.agentNetworkName, saveController.signal);
75
+ }
76
+ catch (e) {
77
+ console.error(`Error saving network ${agentName}. See onSaveAgent implementation for details.`, e);
78
+ sendNotification(NotificationType.error, `Failed to save agent "${agentName}".`, String(e), undefined, null // show indefinitely until the user dismisses
79
+ );
80
+ }
81
+ finally {
82
+ clearTimeout(saveTimeoutId);
83
+ saveAbortControllerRef.current = null;
84
+ setIsSavingAgent(false);
85
+ setIsPopupOpen(false);
86
+ }
87
+ };
88
+ const onClose = () => {
89
+ // If a save is in-flight, abort it immediately so the stream doesn't hang.
90
+ saveAbortControllerRef.current?.abort();
91
+ saveAbortControllerRef.current = null;
92
+ setIsPopupOpen(false);
93
+ setIsSavingAgent(false);
94
+ };
95
+ const handleClose = () => {
96
+ if (isSavingAgent) {
97
+ return;
98
+ }
99
+ if (isDirty) {
100
+ setDisplayConfirmationModal(true);
101
+ return;
102
+ }
103
+ setInstructionsText(initialInstructions);
104
+ setDescriptionText(initialDescription);
105
+ onClose();
106
+ };
107
+ const footer = (_jsx(Box, { sx: {
108
+ display: "flex",
109
+ alignItems: "flex-start",
110
+ justifyContent: "flex-end",
111
+ width: "100%",
112
+ gap: 1,
113
+ }, children: _jsxs(Box, { sx: { display: "flex", gap: 1 }, children: [_jsx(Button, { id: "agent-node-popup-cancel-btn", onClick: handleClose, variant: "outlined", size: "small", disabled: isSavingAgent, children: "Cancel" }), _jsx(Button, { id: "agent-node-popup-save-btn", onClick: onSave, variant: "contained", size: "small", disabled: isSavingAgent || !isDirty, startIcon: isSavingAgent ? (_jsx(CircularProgress, { size: 14, color: "inherit" })) : undefined, children: isSavingAgent ? "Applying changes..." : "Save" })] }) }));
114
+ const getConfirmationModal = () => (_jsx(ConfirmationModal, { id: "agent-node-popup-unsaved-changes-modal", cancelBtnLabel: "Discard changes", closeable: false, content: _jsx("p", { children: "You have unsaved edits. Are you sure you want to discard your changes and close the dialog?" }), handleCancel: () => {
115
+ setDisplayConfirmationModal(false);
116
+ setInstructionsText(initialInstructions);
117
+ setDescriptionText(initialDescription);
118
+ onClose();
119
+ }, handleOk: onSave, maskCloseable: false, okBtnLabel: "Save changes", title: "Unsaved Changes" }));
120
+ const getEditPopup = () => (_jsxs(MUIDialog, { footer: footer, id: "agent-node-popup", isOpen: isOpen, onClose: handleClose, paperProps: { minWidth: "480px", maxWidth: "600px", width: "100%" }, title: agentName, children: [_jsx(TextField, { disabled: isSavingAgent, fullWidth: true, id: "agent-node-popup-description-field", label: "Description", multiline: true, onChange: (e) => setDescriptionText(e.target.value), onKeyDown: (e) => {
121
+ if (e.key !== "Escape")
122
+ e.stopPropagation();
123
+ }, placeholder: "Enter a short description of this agent\u2026", rows: 6, slotProps: { htmlInput: { style: { fontSize: "0.85rem" } } }, size: "small", value: descriptionText }), _jsx(TextField, { autoFocus: true, disabled: isSavingAgent, fullWidth: true, id: "agent-node-popup-instructions-field", label: "Instructions", multiline: true, onChange: (e) => setInstructionsText(e.target.value), onKeyDown: (e) => {
124
+ if (e.key !== "Escape")
125
+ e.stopPropagation();
126
+ }, placeholder: "Enter instructions for this agent\u2026", rows: 6, slotProps: { htmlInput: { style: { fontSize: "0.85rem" } } }, size: "small", sx: { marginTop: 2 }, value: instructionsText })] }));
127
+ return (_jsxs(_Fragment, { children: [displayConfirmationModal && getConfirmationModal(), getEditPopup()] }));
128
+ };
@@ -0,0 +1,21 @@
1
+ import { FC } from "react";
2
+ import { TemporaryNetwork } from "../../../state/TemporaryNetworks.js";
3
+ export declare const BANNER_AUTO_DISMISS_MS = 5000;
4
+ export type NetworkEditorDockProps = {
5
+ readonly currentUser: string;
6
+ readonly id: string;
7
+ readonly isEditingNetwork: boolean;
8
+ readonly networkId: string;
9
+ readonly neuroSanURL: string;
10
+ readonly setIsEditingNetwork: (isEditing: boolean) => void;
11
+ /**
12
+ * Setter for changing the selected network.
13
+ */
14
+ readonly setSelectedNetwork: (network: string | null) => void;
15
+ readonly tempNetworks: TemporaryNetwork[];
16
+ };
17
+ /**
18
+ * Implements the dock that appears at the bottom of the screen when the user is editing a network. Allows user to
19
+ * enter plain-language instructions for modifying the overall network.
20
+ */
21
+ export declare const NetworkEditorDock: FC<NetworkEditorDockProps>;
@@ -0,0 +1,305 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import CloseIcon from "@mui/icons-material/Close";
3
+ import Backdrop from "@mui/material/Backdrop";
4
+ import Box from "@mui/material/Box";
5
+ import Button from "@mui/material/Button";
6
+ import CircularProgress from "@mui/material/CircularProgress";
7
+ import IconButton from "@mui/material/IconButton";
8
+ import Paper from "@mui/material/Paper";
9
+ import { alpha, useTheme } from "@mui/material/styles";
10
+ import TextField from "@mui/material/TextField";
11
+ import Typography from "@mui/material/Typography";
12
+ import { useCallback, useEffect, useRef, useState } from "react";
13
+ import { sendChatQuery } from "../../../controller/agent/Agent.js";
14
+ import { StreamingUnit } from "../../../controller/llm/LlmChat.js";
15
+ import { useAgentChatHistoryStore } from "../../../state/ChatHistory.js";
16
+ import { useTempNetworksStore } from "../../../state/TemporaryNetworks.js";
17
+ import { getZIndex } from "../../../utils/zIndexLayers.js";
18
+ import { chatMessageFromChunk } from "../../AgentChat/Common/Utils.js";
19
+ import { MUIAlert } from "../../Common/MUIAlert.js";
20
+ import { AGENT_NETWORK_DEFINITION_KEY, AGENT_NETWORK_DESIGNER_ID, AGENT_NETWORK_NAME_KEY, } from "../const.js";
21
+ import { convertReservationsToNetworks, extractNetworkHocon, extractReservations, mergeNetworks, } from "../TemporaryNetworks.js";
22
+ //#region Constants
23
+ const PROMPT_PLACEHOLDER = "Describe a change to the network";
24
+ const STREAM_TIMEOUT_MS = 120_000;
25
+ // How long the dock's status banner stays visible before auto-dismissing. Error banners persist until dismissed.
26
+ // Exported for tests.
27
+ export const BANNER_AUTO_DISMISS_MS = 5_000;
28
+ //#endregion Interfaces and Types
29
+ /**
30
+ * Implements the dock that appears at the bottom of the screen when the user is editing a network. Allows user to
31
+ * enter plain-language instructions for modifying the overall network.
32
+ */
33
+ export const NetworkEditorDock = ({ neuroSanURL, currentUser, id, isEditingNetwork, networkId, setIsEditingNetwork, setSelectedNetwork, tempNetworks, }) => {
34
+ const theme = useTheme();
35
+ // Inline status banner shown above the dock header after an "apply" succeeds, is canceled, or fails.
36
+ const [banner, setBanner] = useState(null);
37
+ const bannerTimeoutRef = useRef(null);
38
+ // Dock (edit-mode prompt bar) state
39
+ const [dockPrompt, setDockPrompt] = useState("");
40
+ // "idle" = no apply in flight, "applying" = applying save, "confirmingStop" = abort confirmation dialog is open
41
+ const [state, setState] = useState("idle");
42
+ const isPending = state !== "idle";
43
+ const abortControllerRef = useRef(null);
44
+ // Show a dock banner. Success/cancel banners auto-dismiss; error banners persist until dismissed.
45
+ const showBanner = useCallback((bannerInfo) => {
46
+ clearTimeout(bannerTimeoutRef.current);
47
+ setBanner(bannerInfo);
48
+ if (bannerInfo.severity !== "error") {
49
+ bannerTimeoutRef.current = setTimeout(() => setBanner(null), BANNER_AUTO_DISMISS_MS);
50
+ }
51
+ }, []);
52
+ const handleStopClick = useCallback(() => {
53
+ setState("confirmingStop");
54
+ }, []);
55
+ const handleKeepApplying = useCallback(() => {
56
+ setState("applying");
57
+ }, []);
58
+ const handleDismissBanner = useCallback(() => {
59
+ clearTimeout(bannerTimeoutRef.current);
60
+ setBanner(null);
61
+ }, []);
62
+ const handleStopAndDiscard = useCallback(() => {
63
+ abortControllerRef.current?.abort();
64
+ abortControllerRef.current = null;
65
+ setState("idle");
66
+ showBanner({
67
+ severity: "info",
68
+ title: "Applying cancelled.",
69
+ detail: "Nothing was changed. Your prompt is restored below.",
70
+ });
71
+ }, [showBanner]);
72
+ const handleExitEditMode = useCallback(() => {
73
+ if (isPending) {
74
+ abortControllerRef.current?.abort();
75
+ abortControllerRef.current = null;
76
+ setState("idle");
77
+ }
78
+ setIsEditingNetwork(false);
79
+ }, [isPending, setIsEditingNetwork]);
80
+ // Add an event listener to allow the user to exit edit mode using Escape
81
+ useEffect(() => {
82
+ if (!isEditingNetwork) {
83
+ return undefined;
84
+ }
85
+ const handleEscape = (e) => {
86
+ if (e.key === "Escape")
87
+ handleExitEditMode();
88
+ };
89
+ document.addEventListener("keydown", handleEscape);
90
+ return () => document.removeEventListener("keydown", handleEscape);
91
+ }, [handleExitEditMode, isEditingNetwork]);
92
+ /**
93
+ * Applies the networks returned by the designer: upserts them and triggers navigation if needed.
94
+ * Returns true when a matching reservation was applied, false (and surfaces an error banner) otherwise.
95
+ */
96
+ const saveUpdates = useCallback((newNetworksFromSave, currentAgentNetworkName) => {
97
+ if (newNetworksFromSave.length === 0) {
98
+ showBanner({
99
+ severity: "error",
100
+ title: "Failed to apply network change.",
101
+ detail: "The network designer did not return a reservation. Please try again.",
102
+ });
103
+ return false;
104
+ }
105
+ // Find the returned reservation that stands in for the current network (matched by name). When
106
+ // present, persist every returned network, then carry the open network's chat history over to the
107
+ // replacement and notify the parent so it can navigate to the new reservation.
108
+ const replacement = newNetworksFromSave.find((n) => n.agentNetworkName === currentAgentNetworkName);
109
+ if (replacement) {
110
+ useTempNetworksStore.getState().upsertTempNetworks(newNetworksFromSave);
111
+ if (networkId) {
112
+ useAgentChatHistoryStore.getState().copyHistory(networkId, replacement.agentInfo.agent_name);
113
+ setSelectedNetwork(replacement.agentInfo.agent_name);
114
+ }
115
+ return true;
116
+ }
117
+ // Reservations came back, but none matched the current network — surface this in the dock banner.
118
+ showBanner({
119
+ severity: "error",
120
+ title: "Failed to apply network change.",
121
+ detail: "A reservation was returned but did not match the current network. Please try again.",
122
+ });
123
+ return false;
124
+ }, [networkId, setSelectedNetwork, showBanner]);
125
+ /**
126
+ * Streams the Agent Network Designer endpoint with a natural-language prompt and the current
127
+ * network definition, collecting any returned reservations.
128
+ */
129
+ const applyNetworkDesignerChanges = useCallback(async (signal, userPrompt, currentDefinition, agentNetworkName) => {
130
+ let newNetworks = [];
131
+ await sendChatQuery(neuroSanURL, signal, userPrompt, AGENT_NETWORK_DESIGNER_ID, (chunk) => {
132
+ const chatMessage = chatMessageFromChunk(chunk);
133
+ if (!chatMessage) {
134
+ return;
135
+ }
136
+ const reservations = extractReservations(chatMessage);
137
+ if (reservations.length === 0) {
138
+ return;
139
+ }
140
+ const networkHocon = extractNetworkHocon(chatMessage);
141
+ const agentNetworkNameFromMessage = chatMessage.sly_data?.[AGENT_NETWORK_NAME_KEY];
142
+ const networkName = agentNetworkName ?? agentNetworkNameFromMessage;
143
+ const definitionFromMessage = chatMessage.sly_data?.[AGENT_NETWORK_DEFINITION_KEY];
144
+ const converted = convertReservationsToNetworks(reservations, networkHocon, definitionFromMessage ?? currentDefinition, networkName);
145
+ newNetworks = mergeNetworks(newNetworks, converted);
146
+ }, null, {
147
+ [AGENT_NETWORK_DEFINITION_KEY]: currentDefinition,
148
+ ...(agentNetworkName ? { [AGENT_NETWORK_NAME_KEY]: agentNetworkName } : {}),
149
+ }, currentUser, StreamingUnit.Line);
150
+ return newNetworks;
151
+ }, [currentUser, neuroSanURL]);
152
+ const handleApply = useCallback(async () => {
153
+ const readyToApplyEdit = Boolean(dockPrompt.trim() && neuroSanURL && currentUser);
154
+ if (!readyToApplyEdit) {
155
+ return;
156
+ }
157
+ const currentTempNetwork = networkId
158
+ ? tempNetworks.find((n) => n.agentInfo.agent_name === networkId)
159
+ : undefined;
160
+ const currentDefinition = currentTempNetwork?.agentNetworkDefinition ?? [];
161
+ setState("applying");
162
+ const controller = new AbortController();
163
+ abortControllerRef.current = controller;
164
+ let hasTimedOut = false;
165
+ const timeoutId = setTimeout(() => {
166
+ hasTimedOut = true;
167
+ controller.abort();
168
+ }, STREAM_TIMEOUT_MS);
169
+ try {
170
+ const newNetworks = await applyNetworkDesignerChanges(controller.signal, dockPrompt, currentDefinition, currentTempNetwork?.agentNetworkName);
171
+ const appliedSuccess = saveUpdates(newNetworks, currentTempNetwork?.agentNetworkName);
172
+ if (appliedSuccess) {
173
+ setDockPrompt("");
174
+ showBanner({
175
+ severity: "success",
176
+ title: "Changes applied.",
177
+ detail: "Your network has been updated.",
178
+ });
179
+ }
180
+ }
181
+ catch (e) {
182
+ const isAbort = e instanceof DOMException && e.name === "AbortError";
183
+ if (isAbort) {
184
+ if (hasTimedOut) {
185
+ showBanner({
186
+ severity: "error",
187
+ title: "Failed to apply network change.",
188
+ detail: "The request timed out. Please try again.",
189
+ });
190
+ }
191
+ }
192
+ else {
193
+ showBanner({ severity: "error", title: "Failed to apply network change.", detail: String(e) });
194
+ }
195
+ }
196
+ finally {
197
+ clearTimeout(timeoutId);
198
+ abortControllerRef.current = null;
199
+ setState("idle");
200
+ }
201
+ }, [
202
+ applyNetworkDesignerChanges,
203
+ currentUser,
204
+ dockPrompt,
205
+ networkId,
206
+ neuroSanURL,
207
+ saveUpdates,
208
+ showBanner,
209
+ tempNetworks,
210
+ ]);
211
+ // Clear the banner auto-dismiss timer on unmount.
212
+ useEffect(() => {
213
+ return () => {
214
+ clearTimeout(bannerTimeoutRef.current);
215
+ abortControllerRef.current?.abort();
216
+ abortControllerRef.current = null;
217
+ };
218
+ }, []);
219
+ const getBackdrop = () => isPending && (_jsx(Backdrop, { id: "network-editor-dock-backdrop", open: isPending, sx: { zIndex: (t) => t.zIndex.modal + 1 }, children: state === "confirmingStop" ? (_jsxs(Paper, { elevation: 6, sx: {
220
+ display: "flex",
221
+ flexDirection: "column",
222
+ gap: 2,
223
+ px: 4,
224
+ py: 3,
225
+ borderRadius: 2,
226
+ maxWidth: 420,
227
+ }, children: [_jsx(Typography, { variant: "body1", sx: { fontWeight: "bold" }, children: "Abort changes?" }), _jsx(Typography, { variant: "body2", color: "text.secondary", children: "The in-progress update will be cancelled and discarded. Your network will not be modified." }), _jsxs(Box, { sx: {
228
+ display: "flex",
229
+ gap: 1.5,
230
+ justifyContent: "flex-end",
231
+ }, children: [_jsx(Button, { variant: "outlined", onClick: handleKeepApplying, children: "Keep applying" }), _jsx(Button, { variant: "contained", color: "error", startIcon: _jsx("span", { style: { fontSize: "0.7rem" }, children: "\u25A0" }), onClick: handleStopAndDiscard, children: "Stop & discard" })] })] })) : (_jsxs(Paper, { elevation: 6, sx: {
232
+ display: "flex",
233
+ alignItems: "center",
234
+ gap: 2,
235
+ px: 4,
236
+ py: 2.5,
237
+ borderRadius: 2,
238
+ maxWidth: 480,
239
+ }, children: [_jsx(CircularProgress, { size: 24 }), _jsxs(Box, { sx: { flex: 1 }, children: [_jsx(Typography, { variant: "body1", sx: { fontWeight: "bold" }, children: "Applying changes to network" }), dockPrompt && (_jsx(Typography, { variant: "body2", color: "text.secondary", sx: { mt: 0.25 }, children: dockPrompt }))] }), _jsx(Button, { variant: "outlined", size: "small", startIcon: _jsx("span", { style: { fontSize: "0.65rem" }, children: "\u25A0" }), onClick: handleStopClick, sx: {
240
+ whiteSpace: "nowrap",
241
+ flexShrink: 0,
242
+ color: theme.palette.common.white,
243
+ borderColor: theme.palette.common.white,
244
+ fontWeight: "bold",
245
+ "&:hover": {
246
+ borderColor: theme.palette.error.main,
247
+ color: theme.palette.error.main,
248
+ backgroundColor: alpha(theme.palette.error.main, 0.08),
249
+ },
250
+ }, children: "Stop" })] })) }));
251
+ const getBanner = () => (_jsx(MUIAlert, { closeable: true, id: id, onClose: handleDismissBanner, severity: banner.severity, sx: {
252
+ borderRadius: 0,
253
+ // Override MUIAlert's default 1rem bottom margin so the banner sits flush
254
+ // against the dock header below it.
255
+ marginBottom: 0,
256
+ py: 0,
257
+ // Match the dock header's right padding so the banner's close X lines up
258
+ // vertically with the header's close X below it.
259
+ paddingRight: 0.5,
260
+ alignItems: "center",
261
+ // Frost the banner like the dock header, so the graph doesn't show through the
262
+ // app's translucent paper background; keep a tinted, mostly opaque severity wash.
263
+ "& .MuiAlert-action": {
264
+ alignItems: "center",
265
+ marginRight: 0,
266
+ paddingTop: 0,
267
+ },
268
+ }, children: _jsxs(Typography, { variant: "caption", component: "span", children: [_jsx("strong", { children: banner.title }), ` ${banner.detail}`] }) }));
269
+ const getEditDock = () => isEditingNetwork && (_jsxs(Box, { sx: {
270
+ backdropFilter: "blur(8px)",
271
+ backgroundColor: alpha(theme.palette.background.paper, 0.2),
272
+ borderTop: `2px solid ${theme.palette.primary.main}`,
273
+ flexShrink: 0,
274
+ position: "relative",
275
+ zIndex: getZIndex(2, theme),
276
+ }, children: [banner && getBanner(), _jsxs(Box, { sx: {
277
+ backdropFilter: "blur(6px)",
278
+ borderBottom: "1px solid divider",
279
+ display: "flex",
280
+ alignItems: "center",
281
+ justifyContent: "space-between",
282
+ paddingLeft: 1.25,
283
+ paddingRight: 0.25,
284
+ }, children: [_jsx(Typography, { variant: "overline", sx: { fontWeight: "bold", letterSpacing: 1, lineHeight: 1.8 }, children: "Network Editor" }), _jsx(IconButton, { size: "small", "aria-label": "close edit mode", onClick: handleExitEditMode, children: _jsx(CloseIcon, { fontSize: "small" }) })] }), _jsxs(Box, { sx: {
285
+ display: "flex",
286
+ gap: 1,
287
+ px: 1,
288
+ py: 0.5,
289
+ alignItems: "center",
290
+ }, children: [_jsx(TextField, { autoFocus: true, fullWidth: true, placeholder: PROMPT_PLACEHOLDER, variant: "outlined", size: "small", value: dockPrompt, onChange: (e) => setDockPrompt(e.target.value), onKeyDown: (e) => {
291
+ if (e.key === "Enter" && !e.shiftKey) {
292
+ e.preventDefault();
293
+ void handleApply();
294
+ }
295
+ }, disabled: isPending, slotProps: { htmlInput: { style: { fontSize: "0.75rem" } } } }), _jsx(Button, { variant: "contained", onClick: () => void handleApply(), disabled: isPending || !dockPrompt.trim(), sx: {
296
+ fontSize: 16,
297
+ marginBottom: "1px",
298
+ marginRight: 0,
299
+ minWidth: 110,
300
+ paddingTop: 0.3,
301
+ paddingBottom: 0.3,
302
+ whiteSpace: "nowrap",
303
+ }, startIcon: isPending ? (_jsx(CircularProgress, { size: 16, color: "inherit" })) : undefined, children: isPending ? "Applying..." : "Apply" })] })] }));
304
+ return (_jsxs(_Fragment, { children: [getBackdrop(), getEditDock()] }));
305
+ };