From 3ffb6d11f0f219a1d57b1377b28e8d22d699b6c9 Mon Sep 17 00:00:00 2001 From: Krrish Mittal <11722204+takyyon@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:34:12 -0800 Subject: [PATCH 1/3] fix(designer-v2): improve node authoring and monitoring parity Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- Localize/lang/strings.json | 22 ++ .../.storybook/check-inventory.mjs | 6 + libs/designer-ui-v2/README.md | 6 +- .../src/nodes/__test__/compactCards.spec.tsx | 14 + .../src/nodes/__test__/compactTitle.spec.ts | 33 ++ .../nodes/__test__/nodeHoverPlacement.spec.ts | 23 ++ .../__test__/useEdgeActiveState.spec.tsx | 8 +- .../src/nodes/cards/ActionNodeCard.tsx | 10 +- .../src/nodes/cards/LoopNodeCard.tsx | 31 +- .../src/nodes/cards/NodeHoverCard.tsx | 29 +- .../src/nodes/cards/NodeInfoCard.tsx | 6 +- .../src/nodes/cards/TriggerNodeCard.tsx | 9 +- .../src/nodes/cards/nodeHoverPlacement.ts | 31 ++ libs/designer-ui-v2/src/nodes/cards/shared.ts | 2 + libs/designer-ui-v2/src/nodes/compactTitle.ts | 69 ++-- libs/designer-ui-v2/src/nodes/index.ts | 4 + libs/designer-ui-v2/src/nodes/metrics.ts | 7 +- .../src/nodes/overviewStyles.ts | 28 ++ .../src/nodes/primitives/LoopBodyJoin.tsx | 49 +++ .../src/nodes/primitives/NodeAddButton.tsx | 10 +- .../nodes/primitives/NodeBranchActions.tsx | 68 ++++ .../src/nodes/primitives/NodeBranchShell.tsx | 55 ++++ .../src/nodes/primitives/NodeCard.tsx | 15 +- .../src/nodes/primitives/NodeIconTile.tsx | 4 +- .../src/nodes/primitives/NodeLine.tsx | 19 +- .../src/nodes/primitives/NodeText.tsx | 31 +- libs/designer-ui-v2/src/theme/tokens.ts | 3 + libs/designer-ui-v2/stories/API.mdx | 21 +- libs/designer-ui-v2/stories/Introduction.mdx | 4 +- .../stories/LoopBodyJoin.stories.tsx | 29 ++ .../stories/NodeBranchActions.stories.tsx | 36 +++ .../stories/NodeBranchShell.stories.tsx | 18 ++ .../bjsworkflow/__test__/copypaste.spec.ts | 20 +- .../bjsworkflow/__test__/undoRedo.spec.ts | 16 + .../bjsworkflow/__test__/wrapInScope.spec.ts | 33 ++ .../lib/core/actions/bjsworkflow/copypaste.ts | 17 +- .../lib/core/actions/bjsworkflow/delete.ts | 3 +- .../lib/core/actions/bjsworkflow/undoRedo.ts | 7 + .../core/actions/bjsworkflow/wrapInScope.ts | 4 + .../__test__/familyPresentation.spec.ts | 60 ++++ .../src/lib/core/graphlayout/elklayout.tsx | 19 +- .../src/lib/core/graphlayout/helpers.ts | 14 + .../lib/core/parsers/updateAgenticGraph.ts | 1 + .../lib/core/queries/__test__/runs.spec.ts | 31 +- libs/designer-v2/src/lib/core/queries/runs.ts | 33 ++ .../state/designerOptions/workflowEditLock.ts | 5 + .../designerView/designerViewInterfaces.ts | 2 + .../core/state/undoRedo/undoRedoSelectors.ts | 5 +- .../workflowSlice.graphBehavior.spec.ts | 84 ++++- .../core/state/workflow/workflowInterfaces.ts | 1 + .../lib/core/state/workflow/workflowSlice.ts | 51 ++- libs/designer-v2/src/lib/core/utils/graph.ts | 12 +- .../src/lib/core/utils/loopRepetitions.ts | 15 + .../lib/ui/CustomNodes/GraphContainerNode.tsx | 26 +- .../lib/ui/CustomNodes/OperationCardNode.tsx | 76 ++++- .../src/lib/ui/CustomNodes/ScopeCardNode.tsx | 180 ++++++++++- .../lib/ui/CustomNodes/SubgraphCardNode.tsx | 199 +++++++++++- .../__test__/GraphContainerNode.spec.tsx | 1 + .../__test__/OperationCardNode.spec.tsx | 127 +++++++- .../__test__/ScopeCardNode.spec.tsx | 299 +++++++++++++++++- .../__test__/SubgraphCardNode.spec.tsx | 156 ++++++++- .../components/card/SharedActionCard.tsx | 11 +- .../components/card/SharedFamilyCards.tsx | 128 +++++--- .../components/card/SharedNodeHoverCard.tsx | 41 ++- .../card/__test__/SharedFamilyCards.spec.tsx | 86 +++++ .../components/card/nodeUiStrings.ts | 13 + .../components/handles/DefaultHandle.tsx | 2 + .../components/handles/handles.styles.ts | 1 + .../lib/ui/CustomNodes/useLoopGroupHover.ts | 61 ++++ libs/designer-v2/src/lib/ui/Designer.tsx | 14 +- .../src/lib/ui/DesignerReactFlow.tsx | 151 +++++---- .../src/lib/ui/__test__/Designer.spec.tsx | 10 + .../lib/ui/common/DeleteModal/DeleteModal.tsx | 19 +- .../DeleteModal/MultiSelectDeleteModal.tsx | 19 +- .../__test__/monitoringDeletion.spec.tsx | 85 +++++ .../DesignerContextualMenu.tsx | 53 +++- .../__test__/DesignerContextualMenu.spec.tsx | 50 ++- .../EdgeContextualMenu/EdgeContextualMenu.tsx | 9 +- .../src/lib/ui/common/LoopsPager/helper.ts | 59 ++-- .../connections/__tests__/dropzone.spec.tsx | 44 ++- .../src/lib/ui/connections/dropzone.tsx | 37 ++- .../src/lib/ui/connections/edge.tsx | 6 + .../src/lib/ui/connections/mergeHover.ts | 4 + .../lib/ui/connections/sharedEdgeArrowCap.tsx | 3 + .../src/lib/ui/menuItems/deleteMenuItem.tsx | 5 +- .../SharedExtractionPreviewNode.tsx | 26 +- .../SharedWorkflowExtractionPreview.spec.tsx | 39 +++ .../__test__/multiSelectPanel.spec.tsx | 13 + .../multiSelectPanel/multiSelectPanel.tsx | 12 +- .../ui/panel/runTreeView/TreeActionItem.tsx | 55 +++- .../__tests__/TreeActionItem.spec.tsx | 51 ++- 91 files changed, 2963 insertions(+), 341 deletions(-) create mode 100644 libs/designer-ui-v2/src/nodes/__test__/compactTitle.spec.ts create mode 100644 libs/designer-ui-v2/src/nodes/__test__/nodeHoverPlacement.spec.ts create mode 100644 libs/designer-ui-v2/src/nodes/cards/nodeHoverPlacement.ts create mode 100644 libs/designer-ui-v2/src/nodes/overviewStyles.ts create mode 100644 libs/designer-ui-v2/src/nodes/primitives/LoopBodyJoin.tsx create mode 100644 libs/designer-ui-v2/src/nodes/primitives/NodeBranchActions.tsx create mode 100644 libs/designer-ui-v2/src/nodes/primitives/NodeBranchShell.tsx create mode 100644 libs/designer-ui-v2/stories/LoopBodyJoin.stories.tsx create mode 100644 libs/designer-ui-v2/stories/NodeBranchActions.stories.tsx create mode 100644 libs/designer-ui-v2/stories/NodeBranchShell.stories.tsx create mode 100644 libs/designer-v2/src/lib/core/actions/bjsworkflow/__test__/wrapInScope.spec.ts create mode 100644 libs/designer-v2/src/lib/core/state/designerOptions/workflowEditLock.ts create mode 100644 libs/designer-v2/src/lib/core/utils/loopRepetitions.ts create mode 100644 libs/designer-v2/src/lib/ui/CustomNodes/useLoopGroupHover.ts create mode 100644 libs/designer-v2/src/lib/ui/common/DeleteModal/__test__/monitoringDeletion.spec.tsx create mode 100644 libs/designer-v2/src/lib/ui/connections/mergeHover.ts diff --git a/Localize/lang/strings.json b/Localize/lang/strings.json index 39f84014fcb..1a6ade9f8a0 100644 --- a/Localize/lang/strings.json +++ b/Localize/lang/strings.json @@ -82,6 +82,7 @@ "/mjH84": "Show raw outputs", "/n13VL": "Properties", "/nKih3": "Opens in a new tab", + "/oWzBF": "False", "/qCaDo": "Indicates to template users whether the parameter must be filled to proceed", "/qchXQ": "Required. The collection to join items from.", "/qrBuJ": "Create", @@ -178,6 +179,7 @@ "1KFpTX": "(UTC+03:00) Minsk", "1KMc+6": "The integer should be between [{min}, {max}]", "1LSKq8": "Basics", + "1MO/b/": "Enter a unique case name.", "1NBvKu": "Convert the parameter argument to a floating-point number", "1NVeRR": "This assistant can help you learn about your workflows, answer questions about Azure Logic Apps, and make changes to your workflow.", "1OIW6v": "Set up now", @@ -542,6 +544,7 @@ "7pjV7b": "Project details", "7rItIH": "Cancel", "7rokiZ": "Embedded chat is unavailable with authentication enabled. Click to open in new tab: {url}", + "7smF3w": "{label}, branch taken", "7tPvNK": "After you turn on concurrency control and publish the workflow, this setting can't be changed.", "7uQSsD": "Parameters", "7yEdSt": "Show more", @@ -691,6 +694,7 @@ "AhvQ7r": "Remove and clear all advanced parameters and their values", "Aid5oX": "Handoff description", "Ak2Lka": "Not connected to", + "Ak8mfG": "Edit test data", "AkKqDo": "Built-in Tools", "AlPxuK": "Description", "AlWFOS": "Collapse chat panel", @@ -1222,6 +1226,7 @@ "Ld62T8": "Delete", "LdITnG": "(UTC-03:00) Cayenne, Fortaleza", "LeR+TX": "Zoom in", + "Leu34C": "Rename case", "Lft/is": "Add new", "LgCmeY": "The specified path does not exist or is not accessible.", "LiRX1e": "Replacement", @@ -1256,6 +1261,7 @@ "M8Aqm4": "Optional. The name of the scoped action where you want the inputs and outputs from the top-level actions inside that scope.", "M9LjqI": "Conversational agents (Preview)", "MAX7xS": "Show more", + "MBA7Al": "Rename case", "MCzWDc": "Preview", "MDbmMw": "Required. The collections to evaluate. An object must be in all collections passed in to appear in the result.", "MDmYah": "Filter by resource group", @@ -1519,6 +1525,7 @@ "QwAEWd": "Select a project", "QxEQwD": "Status", "QzjaQG": "Connection updated", + "R+8B9G": "More case actions", "R/aiRy": "(UTC+12:00) Coordinated Universal Time+12", "R0Skk9": "Confirm that you want to delete this artifact? You can't undo this action.", "R7UxBX": "Learn more", @@ -2016,6 +2023,7 @@ "ZmSjQV": "Learn how to set up a logic app", "Zo2BOK": "Condition", "ZtLSVc": "Search", + "Zwdunb": "True", "ZyDq4/": "Show a different suggestion", "ZyntX1": "Add a description", "ZzQUve": "Save this API key in a secure place. You can't view the key later. Previous API keys still work based on their expiration date. However, regenerating access tokens invalidates all previous API keys.", @@ -2102,6 +2110,7 @@ "_/mjH84.comment": "Show outputs text", "_/n13VL.comment": "Properties text", "_/nKih3.comment": "Accessible description for the extracted child workflow navigation action", + "_/oWzBF.comment": "False branch label", "_/qCaDo.comment": "Description for the required field", "_/qchXQ.comment": "Required collection parameter to apply join function on", "_/qrBuJ.comment": "Button text for creating the workflow", @@ -2198,6 +2207,7 @@ "_1KFpTX.comment": "Time zone value ", "_1KMc+6.comment": "Error validation message for integers being out of range", "_1LSKq8.comment": "Accessibility label for the basics section", + "_1MO/b/.comment": "Validation message when a switch-case key rename is invalid", "_1NBvKu.comment": "Label for description of custom float Function", "_1NVeRR.comment": "Chatbot introduction message when workflow editing is enabled", "_1OIW6v.comment": "Button text to start Azure connector setup", @@ -2562,6 +2572,7 @@ "_7pjV7b.comment": "Title for the details section", "_7rItIH.comment": "Cancel button text for deployment model resource", "_7rokiZ.comment": "Tooltip for chat button", + "_7smF3w.comment": "Announced phrase for the branch that ran in monitoring", "_7tPvNK.comment": "Message for the confirmation dialog before enabling trigger concurrency control", "_7uQSsD.comment": "Label for the parameters status column", "_7yEdSt.comment": "Toggle button text for showing advanced parameters", @@ -2711,6 +2722,7 @@ "_AhvQ7r.comment": "Button tooltip to remove all advanced parameters", "_Aid5oX.comment": "Label text for the input field to enter a description of the handoff", "_Ak2Lka.comment": "Chatbot text stating connection to api not made", + "_Ak8mfG.comment": "Open the selected action’s Testing tab", "_AkKqDo.comment": "Header label for the built-in tools section in agent loop settings", "_AlPxuK.comment": "This is for a label for a badge, it is used for screen readers and not shown on the screen.", "_AlWFOS.comment": "Collapse button title", @@ -3242,6 +3254,7 @@ "_Ld62T8.comment": "Button text for deleting selected workflows", "_LdITnG.comment": "Time zone value ", "_LeR+TX.comment": "Aria label for a button that zooms in on the workflow", + "_Leu34C.comment": "Accessible label for the switch-case rename action", "_Lft/is.comment": "Button to add a new connection", "_LgCmeY.comment": "Specified path does not exist or is not accessible message text", "_LiRX1e.comment": "Extraction replacement expression column", @@ -3276,6 +3289,7 @@ "_M8Aqm4.comment": "Optional string parameter to determine specific actions inside top-level actions", "_M9LjqI.comment": "Conversational agent workflow option", "_MAX7xS.comment": "Label for show more text.", + "_MBA7Al.comment": "Dialog title shown when renaming a switch-case lane", "_MCzWDc.comment": "Recurrence preview title", "_MDbmMw.comment": "Required collection parameters to check intersection function on", "_MDmYah.comment": "Filter resource groups label", @@ -3539,6 +3553,7 @@ "_QwAEWd.comment": "Select the project to use for this connection", "_QxEQwD.comment": "Status filter label", "_QzjaQG.comment": "Notification title for successful connection update", + "_R+8B9G.comment": "Accessible label for the switch-case overflow actions menu", "_R/aiRy.comment": "Time zone value ", "_R0Skk9.comment": "Content for the delete artifact", "_R7UxBX.comment": "Link text for learning more about knowledge base group", @@ -4036,6 +4051,7 @@ "_ZmSjQV.comment": "Title for the setup instructions link", "_Zo2BOK.comment": "Conditional action title", "_ZtLSVc.comment": "Search label", + "_Zwdunb.comment": "True branch label", "_ZyDq4/.comment": "Text for the show different suggestion flow button", "_ZyntX1.comment": "Text that tells you to select for adding a description", "_ZzQUve.comment": "Description for the MCP server workflows section", @@ -4459,6 +4475,7 @@ "_hrbDu6.comment": "Label text for retry duration", "_hrs5f4.comment": "The description for button text of saving the template as testing status", "_htj+eZ.comment": "Header to update target schema", + "_hu8PnM.comment": "Button text to dismiss switch-case rename dialog", "_huLRj0.comment": "Error message when the hub name is invalid regex.", "_hvbclb.comment": "MSI Audience Label Display Name", "_hwgU6Y.comment": "Error message when name is empty", @@ -4538,6 +4555,7 @@ "_j2v8BE.comment": "Text to show no connections present in the template.", "_j4OKkU.comment": "label to set text color", "_j5z8Vd.comment": "Label for array connection", + "_j6+gS9.comment": "Input label for renaming a switch-case key", "_j6RrLt.comment": "Project setup section title", "_j7HEKm.comment": "Text for days", "_jA6Wrp.comment": "label to inform to upload or select target schema to be used", @@ -4701,6 +4719,7 @@ "_m8Q61y.comment": "Parameter Field Name Title", "_m8z4Yr.comment": "placeholder for pagination setting", "_mB14zV.comment": "HTTP queries label", + "_mBHY52.comment": "Button text to confirm renaming a switch-case key", "_mCKsFw.comment": "Time zone value ", "_mCzkXX.comment": "Text for button to add a new action", "_mE7w9G.comment": "Message on deleting connection", @@ -5895,6 +5914,7 @@ "hrbDu6": "Duration", "hrs5f4": "Save + publish for testing", "htj+eZ": "Update target schema", + "hu8PnM": "Cancel", "huLRj0": "Enter a unique name under 244 characters with only letters and numbers.", "hvbclb": "Audience", "hwgU6Y": "Name is required", @@ -5974,6 +5994,7 @@ "j2v8BE": "No connections are needed in this template", "j4OKkU": "Text color", "j5z8Vd": "Repeating", + "j6+gS9": "Case name", "j6RrLt": "Project setup", "j7HEKm": "days", "jA6Wrp": "Add or select a target schema to use for your map.", @@ -6137,6 +6158,7 @@ "m8Q61y": "Name", "m8z4Yr": "Threshold of items to return", "mB14zV": "Queries", + "mBHY52": "Save", "mCKsFw": "(UTC+07:00) Barnaul, Gorno-Altaysk", "mCzkXX": "Add an action", "mE7w9G": "Function deleted.", diff --git a/libs/designer-ui-v2/.storybook/check-inventory.mjs b/libs/designer-ui-v2/.storybook/check-inventory.mjs index 223447c07ca..a372fb1ddc7 100644 --- a/libs/designer-ui-v2/.storybook/check-inventory.mjs +++ b/libs/designer-ui-v2/.storybook/check-inventory.mjs @@ -33,6 +33,9 @@ const visualExports = [ 'NodeLabeledHandle', 'NodeBranchOutputs', 'NodeBranchLabel', + 'NodeBranchActions', + 'NodeBranchShell', + 'LoopBodyJoin', 'NodeLine', 'NodeActionAdd', 'IfIconRegular', @@ -83,6 +86,9 @@ const nonvisualExports = [ 'useEdgeActiveState', 'useNodeHeaderButtonStyles', 'NODE_HOVER_CARD_IGNORE_ATTRIBUTE', + 'NODE_BRANCH_ACTIONS_MAX_RESERVE_PX', + 'useLoopBodyHoverClass', + 'useNodeOverviewStyles', ]; function assertPublicValueInventory(actual, visual, nonvisual) { diff --git a/libs/designer-ui-v2/README.md b/libs/designer-ui-v2/README.md index 85b40af9277..c39e4cf65df 100644 --- a/libs/designer-ui-v2/README.md +++ b/libs/designer-ui-v2/README.md @@ -21,10 +21,10 @@ exports with explicit visual/nonvisual classifications; new unclassified values fail until classified. It also checks exact visual metadata coverage and supported public imports, while excluding type-only exports from runtime counts. -Start with **Start here / Introduction** and **API and boundaries**. All **37** +Start with **Start here / Introduction** and **API and boundaries**. All **40** public visual exports (including `DesignerUiScope` and both condition icons) have individual typed metadata, native Overview docs, and supported examples. -The API page documents all **31** nonvisual runtime exports and public types without +The API page documents all **39** nonvisual runtime exports and public types without inventing UI for helpers or metrics. Add/collapse/selection/dismissal examples show visible local state; they are not workflow execution or a fake backend. @@ -130,6 +130,8 @@ All added props are optional; omitted values retain the previous behavior. | `NodeRunAfterIndicator` | Required `statuses` uses `succeeded`, `timedOut`, `skipped`, `failed`; fixed dot order is preserved. `collapsedCount` defaults to none (dots); when supplied it renders `×N`. `strings` defaults to `defaultNodeRunAfterStrings`, including the accessible summary. | | `NodeLine` | `variant='solid'`, `length=85`, `orientation='horizontal'`, `state='default'`. `NodeLineState` is `default`, `taken`, `notTaken`, `highlighted`, `running`. Only canonical solid owns an arrow; running dashes become static under reduced motion. `getNodeLineStroke(variant, { state? } = {})` composes static state over `nodeLineStrokes`; it does not animate or infer evidence. | | `NodeBranchLabel` | Required literal `label`; `tone='neutral'` (also success/danger); `state` omitted leaves it undimmed (also taken/notTaken); `action` defaults to none; `strings.taken` defaults to `defaultBranchTakenString`. Taken text is announced, not color-only. Position and action behavior belong to the host. | +| `NodeBranchShell` / `NodeBranchActions` | A lane header surface and optional compact buttons. The host supplies the tone, selection, disabled state, localized labels, and callbacks. Commands and confirmation belong to the host. | +| `LoopBodyJoin` | An arrowless decoration at host-supplied `x` and `y` with the given vertical `length`. Use `useLoopBodyHoverClass` to paint the header and body when the host marks the group active. | | `NodeBranchOutputs` | `labels` defaults to English True/False; `slots` defaults to none; `activeIndex` omitted leaves all outputs undimmed; `takenLabel=defaultBranchTakenString`. These are host-provided branch captions, port slots and evidence. | | `ConditionNodeCard` | `mode='multiOutput'`; trunk is opt-in for Switch only and has one visual tick with semantic slots retained. `caseCount=4`, `takenOutput` omitted; `action`, `inputSlot`, `outputSlots` default to none; `inputVariant` defaults to the neutral input handle. If preserves success/danger exits. | | `NodeFrame` | `tone='neutral'`, `collapsed=false`, `subtitlePlacement='inline'`, `handles=false`, `handleAxis='horizontal'`, `showInputHandle=true`, `inputVariant='neutral'`, `headerAppearance='default'`, `motion='none'`. `actionCount`, `action`, `inputSlot`, `outputSlot`, `handleTop`, `handleLeft` default to none. Slots imply handles; hiding input does not remove output. Title omitted/empty means no header. Host-supplied border-relative offsets are compensated once for the thin border. `strings.frame` defaults to `defaultNodeFrameStrings`. | diff --git a/libs/designer-ui-v2/src/nodes/__test__/compactCards.spec.tsx b/libs/designer-ui-v2/src/nodes/__test__/compactCards.spec.tsx index 02debc9fd0b..287f264fc63 100644 --- a/libs/designer-ui-v2/src/nodes/__test__/compactCards.spec.tsx +++ b/libs/designer-ui-v2/src/nodes/__test__/compactCards.spec.tsx @@ -63,6 +63,20 @@ describe('Standard compact preset', () => { expect(title.whiteSpace).toBe('normal'); }); + it('lets a long title replace a decorative caption without hiding a status or count', () => { + const title = 'Validate every line item before authorizing payment'; + const shared = { title, titleLines: 2 as const, density: 'compact' as const, prioritizeTitle: true }; + const { rerender } = render(); + expect(screen.queryByText('Internal operation')).not.toBeInTheDocument(); + + rerender(); + expect(screen.getByText('2 actions')).toBeVisible(); + + rerender(); + expect(screen.getByText('Failed')).toBeVisible(); + expect(screen.getByText('1 s')).toBeVisible(); + }); + it('keeps compact trigger pills semicircular at either height', () => { const { unmount } = render(); expect(getComputedStyle(surfaceOf('trigger').surface).borderTopLeftRadius).toBe(`${compactNodeMetrics.card.height / 2}px`); diff --git a/libs/designer-ui-v2/src/nodes/__test__/compactTitle.spec.ts b/libs/designer-ui-v2/src/nodes/__test__/compactTitle.spec.ts new file mode 100644 index 00000000000..d31394c09be --- /dev/null +++ b/libs/designer-ui-v2/src/nodes/__test__/compactTitle.spec.ts @@ -0,0 +1,33 @@ +import { expect, it, vi } from 'vitest'; + +it('reuses measurements across reserves, evicts old titles and remeasures after fonts load', async () => { + const measureText = vi.fn(() => ({ width: 130 }) as TextMetrics); + const canvas = vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({ measureText } as CanvasRenderingContext2D); + const fonts = new EventTarget(); + const previous = Object.getOwnPropertyDescriptor(document, 'fonts'); + Object.defineProperty(document, 'fonts', { configurable: true, value: fonts }); + try { + const { getCompactTitleLines } = await import('../compactTitle'); + expect(getCompactTitleLines('Old title')).toBe(1); + expect(getCompactTitleLines('Old title', 20)).toBe(2); + expect(measureText).toHaveBeenCalledTimes(1); + + for (let index = 0; index < 512; index++) { + getCompactTitleLines(`Operation ${index}`); + } + measureText.mockClear(); + getCompactTitleLines('Old title'); + expect(measureText).toHaveBeenCalledOnce(); + + fonts.dispatchEvent(new Event('loadingdone')); + measureText.mockReturnValue({ width: 160 } as TextMetrics); + expect(getCompactTitleLines('Old title')).toBe(2); + } finally { + canvas.mockRestore(); + if (previous) { + Object.defineProperty(document, 'fonts', previous); + } else { + Reflect.deleteProperty(document, 'fonts'); + } + } +}); diff --git a/libs/designer-ui-v2/src/nodes/__test__/nodeHoverPlacement.spec.ts b/libs/designer-ui-v2/src/nodes/__test__/nodeHoverPlacement.spec.ts new file mode 100644 index 00000000000..81843efe9f1 --- /dev/null +++ b/libs/designer-ui-v2/src/nodes/__test__/nodeHoverPlacement.spec.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest'; +import { getClearHoverSide } from '../cards/nodeHoverPlacement'; + +const anchor = { left: 250, right: 350, top: 200, bottom: 250 }; +const card = { width: 200, height: 100 }; +const viewport = { width: 650, height: 500 }; +const rightSibling = { left: 400, right: 500, top: 200, bottom: 250 }; +const leftSibling = { left: 100, right: 200, top: 200, bottom: 250 }; + +describe('node hover placement', () => { + it('flips away from a parallel sibling in both LTR and RTL', () => { + expect(getClearHoverSide(anchor, card, viewport, [rightSibling], false)).toBe('before'); + expect(getClearHoverSide(anchor, card, viewport, [leftSibling], true)).toBe('before'); + }); + + it('uses a vertical gap when the viewport edge and neighboring card block the sides', () => { + expect(getClearHoverSide(anchor, card, { ...viewport, width: 450 }, [leftSibling], false)).toBe('below'); + }); + + it('delegates to the viewport-aware fallback if no clear placement fits', () => { + expect(getClearHoverSide(anchor, card, viewport, [{ left: 0, top: 0, right: 650, bottom: 500 }], false)).toBeUndefined(); + }); +}); diff --git a/libs/designer-ui-v2/src/nodes/__test__/useEdgeActiveState.spec.tsx b/libs/designer-ui-v2/src/nodes/__test__/useEdgeActiveState.spec.tsx index 49140c26ee2..2bae7332acc 100644 --- a/libs/designer-ui-v2/src/nodes/__test__/useEdgeActiveState.spec.tsx +++ b/libs/designer-ui-v2/src/nodes/__test__/useEdgeActiveState.spec.tsx @@ -28,14 +28,14 @@ const renderProbe = () => ); describe('useEdgeActiveState', () => { - it.each(['line', 'wrapper'])('activates only while the %s is hovered', async (target) => { - const user = userEvent.setup(); + it.each(['line', 'wrapper'])('activates only while the %s is hovered', (target) => { renderProbe(); + const surface = screen.getByTestId(target); expect(screen.getByTestId('active')).toHaveTextContent('false'); - await user.hover(screen.getByTestId(target)); + fireEvent.mouseOver(surface); expect(screen.getByTestId('hovered')).toHaveTextContent('true'); expect(screen.getByTestId('active')).toHaveTextContent('true'); - await user.unhover(screen.getByTestId(target)); + fireEvent.mouseOut(surface); expect(screen.getByTestId('hovered')).toHaveTextContent('false'); expect(screen.getByTestId('active')).toHaveTextContent('false'); }); diff --git a/libs/designer-ui-v2/src/nodes/cards/ActionNodeCard.tsx b/libs/designer-ui-v2/src/nodes/cards/ActionNodeCard.tsx index 30fc833369c..ed78a69c969 100644 --- a/libs/designer-ui-v2/src/nodes/cards/ActionNodeCard.tsx +++ b/libs/designer-ui-v2/src/nodes/cards/ActionNodeCard.tsx @@ -36,6 +36,7 @@ export const ActionNodeCard = forwardRef(fu inputVariant, density, titleLines, + prioritizeTitle, ...rest }, ref @@ -67,7 +68,14 @@ export const ActionNodeCard = forwardRef(fu artwork={iconArtwork} {...resolveNodeIcons({ icon, selectedIcon }, categoryNodeIcons.action)} /> - + {handles ? : null} diff --git a/libs/designer-ui-v2/src/nodes/cards/LoopNodeCard.tsx b/libs/designer-ui-v2/src/nodes/cards/LoopNodeCard.tsx index 78a76240cb3..f31e23e380d 100644 --- a/libs/designer-ui-v2/src/nodes/cards/LoopNodeCard.tsx +++ b/libs/designer-ui-v2/src/nodes/cards/LoopNodeCard.tsx @@ -13,12 +13,20 @@ import type { NodeHandleVariant } from '../types'; import { resolveCardDensity, resolveNodeIcons } from './shared'; import type { BaseNodeCardProps, CompactNodeCardProps } from './shared'; import { useNodeCount } from '../countLabel'; +import { nodeMetrics } from '../metrics'; const END_OUTPUTS = ['neutral', 'neutral'] as const; const NEXT_OUTPUT = ['neutral'] as const; const DEFAULT_ICONS = { icon: , selectedIcon: }; const useStyles = makeStyles({ bottom: { position: 'absolute', bottom: 0, left: '50%', transform: 'translate(-50%, 50%)', zIndex: 1 }, + pagerRow: { + position: 'relative', + height: `${nodeMetrics.iterationPager.height}px`, + display: 'flex', + justifyContent: 'center', + alignItems: 'start', + }, }); /** end: body/done outputs; bottom: body below and next trailing; none: next only. */ @@ -33,10 +41,12 @@ export interface LoopNodeCardProps extends Omit, C bodySlot?: ReactNode; /** Host control on the bottom edge, replacing the bottom body dot. */ bodyToggle?: ReactNode; + /** Optional vertical monitoring row; the next port belongs below the controls. */ + iterationPager?: ReactNode; strings?: LoopNodeCardStrings; } -/** Canonical Otto loop card; body contents and run paging belong in the host's frame. */ +/** Canonical loop card; the host supplies body contents and optional run paging. */ export const LoopNodeCard = forwardRef(function LoopNodeCard( { title, @@ -56,10 +66,12 @@ export const LoopNodeCard = forwardRef(functi outputSlots, bodySlot, bodyToggle, + iterationPager, strings = defaultNodeStrings, handles = true, density, titleLines, + prioritizeTitle, ...rest }, ref @@ -74,6 +86,7 @@ export const LoopNodeCard = forwardRef(functi {bodySlot} ) : null; const nodeCount = useNodeCount(countLabel, strings, rest['aria-describedby']); + const outputs = handles ? : null; return ( (functi strings={strings} data-node-card="foreach" data-body-placement={bodyPlacement} + after={ + iterationPager ? ( + <> + {rest.after} +
+ {iterationPager} + {outputs} +
+ + ) : ( + rest.after + ) + } > {handles ? {inputSlot} : null} @@ -104,9 +130,10 @@ export const LoopNodeCard = forwardRef(functi subtitle={subtitle ?? strings.loop.foreach} subtitleKind={subtitleKind} titleLines={layout.titleLines} + prioritizeTitle={prioritizeTitle} {...nodeCount.textProps} /> - {handles ? : null} + {iterationPager ? null : outputs} {handles ? bottom : null}
diff --git a/libs/designer-ui-v2/src/nodes/cards/NodeHoverCard.tsx b/libs/designer-ui-v2/src/nodes/cards/NodeHoverCard.tsx index b0499211406..22156ec3af3 100644 --- a/libs/designer-ui-v2/src/nodes/cards/NodeHoverCard.tsx +++ b/libs/designer-ui-v2/src/nodes/cards/NodeHoverCard.tsx @@ -5,6 +5,7 @@ import { nodeHoverCardTiming, nodeMetrics } from '../metrics'; import { NodeHoverCardActiveContext } from '../primitives/NodeText'; import { useDesignerUiOutlet } from '../../theme/DesignerUiScope'; import { useNodeHoverCardGroup } from './nodeHoverCardGroup'; +import { getClearHoverSide } from './nodeHoverPlacement'; /** * Opt-out marker for interactive descendants (tool rows, add/expand buttons) embedded in a hover trigger. @@ -62,6 +63,8 @@ export interface NodeHoverCardProps extends Omit, * with vertical flows do not cover the upstream node or its incoming edge. */ placement?: 'above' | 'side'; + /** The host identifies neighboring content to keep visible. Measured only for an open side popover. */ + getObstacles?: (trigger: HTMLElement) => DOMRectReadOnly[]; } export const NodeHoverCard = forwardRef(function NodeHoverCard( { @@ -73,6 +76,7 @@ export const NodeHoverCard = forwardRef(func externalFocusTarget, triggerRef, placement = 'above', + getObstacles, className, ...rest }, @@ -87,6 +91,25 @@ export const NodeHoverCard = forwardRef(func const [open, setOpen] = useState(false); const [target, setTarget] = useState(null); const surface = useRef(null); + const [clearSide, setClearSide] = useState>(); + const avoidObstacles = useCallback(() => { + const doc = target?.ownerDocument; + if (!target || !surface.current || !doc?.defaultView || !getObstacles) { + return; + } + // Fluent calls this after measuring the real card, including wrapped headings and localized text. + const { clientWidth: width, clientHeight: height } = doc.documentElement; + setClearSide( + getClearHoverSide( + target.getBoundingClientRect(), + surface.current.getBoundingClientRect(), + { width, height }, + getObstacles(target), + doc.defaultView.getComputedStyle(target).direction === 'rtl' + ) + ); + }, [getObstacles, target]); + const side = getObstacles ? clearSide : undefined; // Timers are created and cleared through the trigger's owner window so iframe-hosted designers stay isolated. const timer = useRef<{ owner: Window; id: number }>(); // Direction of the pending timer: true = opening, false = closing, undefined = none. Repeated events in the same @@ -167,6 +190,7 @@ export const NodeHoverCard = forwardRef(func return; } openRef.current = true; + setClearSide(undefined); setOpen(true); }); }, [cancelLocalPending, clearTimer, closeNow, group, openDelay, owner, startTimer, target]); @@ -398,10 +422,11 @@ export const NodeHoverCard = forwardRef(func placement === 'side' ? { target, - position: 'after', - align: 'top', + position: side ?? 'after', + align: side === 'above' || side === 'below' ? 'start' : 'top', offset: nodeMetrics.hoverCard.offset, fallbackPositions: ['before', 'below', 'above'], + onPositioningEnd: getObstacles ? avoidObstacles : undefined, } : { target, position: 'above', align: 'start', offset: nodeMetrics.hoverCard.offset } } diff --git a/libs/designer-ui-v2/src/nodes/cards/NodeInfoCard.tsx b/libs/designer-ui-v2/src/nodes/cards/NodeInfoCard.tsx index b0d1bfc0cd0..737079680a2 100644 --- a/libs/designer-ui-v2/src/nodes/cards/NodeInfoCard.tsx +++ b/libs/designer-ui-v2/src/nodes/cards/NodeInfoCard.tsx @@ -51,6 +51,7 @@ const useStyles = makeStyles({ lineHeight: tokens.lineHeightBase300, color: tokens.colorNeutralForeground1, }, + wrappedTitle: { whiteSpace: 'normal', overflowWrap: 'anywhere' }, header: { gridTemplateColumns: 'min-content minmax(0, 1fr) auto', '& .fui-CardHeader__header, & .fui-CardHeader__description': { minWidth: 0 }, @@ -116,6 +117,8 @@ export interface NodeInfoCardProps extends Omit, category: NodeCategory; icon: ReactNode; title: string; + /** Allow the full title to wrap rather than relying on a mouse-only native tooltip. */ + wrapTitle?: boolean; subtitle?: string; configured?: boolean; description?: ReactNode; @@ -136,6 +139,7 @@ export const NodeInfoCard = forwardRef(functi category, icon, title, + wrapTitle, subtitle, configured, description, @@ -182,7 +186,7 @@ export const NodeInfoCard = forwardRef(functi /> } header={ -

+

{title}

} diff --git a/libs/designer-ui-v2/src/nodes/cards/TriggerNodeCard.tsx b/libs/designer-ui-v2/src/nodes/cards/TriggerNodeCard.tsx index 0e9a7f2446b..b02391a08a1 100644 --- a/libs/designer-ui-v2/src/nodes/cards/TriggerNodeCard.tsx +++ b/libs/designer-ui-v2/src/nodes/cards/TriggerNodeCard.tsx @@ -28,6 +28,7 @@ export const TriggerNodeCard = forwardRef( handles = true, density, titleLines, + prioritizeTitle, ...rest }, ref @@ -57,7 +58,13 @@ export const TriggerNodeCard = forwardRef( artwork={iconArtwork} {...resolveNodeIcons({ icon, selectedIcon }, categoryNodeIcons.trigger)} /> - + {handles ? : null} diff --git a/libs/designer-ui-v2/src/nodes/cards/nodeHoverPlacement.ts b/libs/designer-ui-v2/src/nodes/cards/nodeHoverPlacement.ts new file mode 100644 index 00000000000..c7d82b05004 --- /dev/null +++ b/libs/designer-ui-v2/src/nodes/cards/nodeHoverPlacement.ts @@ -0,0 +1,31 @@ +import { nodeMetrics } from '../metrics'; + +type Rect = Pick; +type Size = Pick; +type Side = 'after' | 'before' | 'below' | 'above'; + +const intersects = (a: Rect, b: Rect) => a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top; + +/** Leave fallback to Fluent when none of the preferred placements fits without covering canvas content. */ +export function getClearHoverSide(anchor: Rect, card: Size, viewport: Size, obstacles: Rect[], rtl: boolean): Side | undefined { + const gap = nodeMetrics.hoverCard.offset; + const right = anchor.right + gap; + const left = anchor.left - gap - card.width; + const start = rtl ? anchor.right - card.width : anchor.left; + const candidates: [Side, number, number][] = [ + ['after', rtl ? left : right, anchor.top], + ['before', rtl ? right : left, anchor.top], + ['below', start, anchor.bottom + gap], + ['above', start, anchor.top - gap - card.height], + ]; + return candidates.find(([, left, top]) => { + const box = { left, top, right: left + card.width, bottom: top + card.height }; + return ( + box.left >= 0 && + box.top >= 0 && + box.right <= viewport.width && + box.bottom <= viewport.height && + !obstacles.some((obstacle) => intersects(box, obstacle)) + ); + })?.[0]; +} diff --git a/libs/designer-ui-v2/src/nodes/cards/shared.ts b/libs/designer-ui-v2/src/nodes/cards/shared.ts index 9d14fab2e44..c60fe4e7726 100644 --- a/libs/designer-ui-v2/src/nodes/cards/shared.ts +++ b/libs/designer-ui-v2/src/nodes/cards/shared.ts @@ -49,6 +49,8 @@ export interface CompactNodeCardProps { density?: NodeCardDensity; /** Compact only: hosts pass the same line count they used to size layout (see getCompactTitleLines). */ titleLines?: 1 | 2; + /** Opt-in to use the decorative caption row for a wrapped title. */ + prioritizeTitle?: boolean; } export const resolveCardDensity = ({ density = 'default', titleLines = 1 }: CompactNodeCardProps) => density === 'compact' diff --git a/libs/designer-ui-v2/src/nodes/compactTitle.ts b/libs/designer-ui-v2/src/nodes/compactTitle.ts index 7f6a9150fa8..e8f35726c76 100644 --- a/libs/designer-ui-v2/src/nodes/compactTitle.ts +++ b/libs/designer-ui-v2/src/nodes/compactTitle.ts @@ -1,43 +1,52 @@ import { compactNodeMetrics, type CompactTitleLines } from './metrics'; -const compactTitleLineCache = new Map(); -let measureContext: CanvasRenderingContext2D | null | undefined; -const compactTitleFontFamily = - "'Segoe UI', 'Segoe UI Web (West European)', -apple-system, BlinkMacSystemFont, Roboto, 'Helvetica Neue', sans-serif"; -// Average 14px semibold Segoe UI advance; used when canvas text metrics are unavailable (SSR, jsdom). +const maxCachedTitles = 512; const fallbackCharWidth = 7.4; +const { weight, size, family } = compactNodeMetrics.titleFont; +const measurements = new WeakMap number>(); -const measureTitleWidth = (title: string): number => { - if (measureContext === undefined) { - try { - measureContext = typeof document === 'undefined' ? null : document.createElement('canvas').getContext('2d'); - } catch { - measureContext = null; +function createTitleMeasurer(document: Document) { + const widths = new Map(); + const context = document.createElement('canvas').getContext('2d'); + if (!context) { + return fallbackWidth; + } + context.font = `${weight} ${size}px ${family}`; + // Font loading can replace fallback glyphs without changing the CSS font string. + document.fonts?.addEventListener('loadingdone', () => widths.clear()); + return (title: string) => { + const cached = widths.get(title); + if (cached !== undefined) { + widths.delete(title); + widths.set(title, cached); + return cached; } - if (measureContext) { - const { weight, size } = compactNodeMetrics.titleFont; - measureContext.font = `${weight} ${size}px ${compactTitleFontFamily}`; + const width = context.measureText(title).width || fallbackWidth(title); + if (widths.size === maxCachedTitles) { + const oldest = widths.keys().next(); + if (!oldest.done) { + widths.delete(oldest.value); + } } - } - const measured = measureContext?.measureText(title).width; - return typeof measured === 'number' && measured > 0 ? measured : title.length * fallbackCharWidth; -}; + widths.set(title, width); + return width; + }; +} + +const fallbackWidth = (title: string) => title.length * fallbackCharWidth; /** - * Hosts compute this once per title and feed the same value to layout (height) and the card (line clamp), - * so a misestimate can only cost an ellipsis or spare space, never a handle/edge misalignment. + * Hosts feed this result to both layout and the rendered card. Width measurements are shared + * across reservations: a corner control reduces available space, not the width of the text. */ -export const getCompactTitleLines = (title: string | undefined, textEndReserve = 0): CompactTitleLines => { +export function getCompactTitleLines(title: string | undefined, textEndReserve = 0): CompactTitleLines { if (!title) { return 1; } - // The reserve narrows the column (e.g. a host's corner control), so it is part of the cache identity. - const cacheKey = `${textEndReserve}|${title}`; - const cached = compactTitleLineCache.get(cacheKey); - if (cached) { - return cached; + let measure = fallbackWidth; + if (typeof document !== 'undefined') { + measure = measurements.get(document) ?? createTitleMeasurer(document); + measurements.set(document, measure); } - const lines: CompactTitleLines = measureTitleWidth(title) > compactNodeMetrics.textWidth - textEndReserve ? 2 : 1; - compactTitleLineCache.set(cacheKey, lines); - return lines; -}; + return measure(title) > compactNodeMetrics.textWidth - textEndReserve ? 2 : 1; +} diff --git a/libs/designer-ui-v2/src/nodes/index.ts b/libs/designer-ui-v2/src/nodes/index.ts index 24e88a724ea..33e5de311ab 100644 --- a/libs/designer-ui-v2/src/nodes/index.ts +++ b/libs/designer-ui-v2/src/nodes/index.ts @@ -15,7 +15,10 @@ export * from './primitives/NodeToolConnector'; export * from './primitives/NodeLabeledHandle'; export * from './primitives/NodeBranchOutputs'; export * from './primitives/NodeBranchLabel'; +export * from './primitives/NodeBranchActions'; +export * from './primitives/NodeBranchShell'; export * from './primitives/NodeLine'; +export * from './primitives/LoopBodyJoin'; export * from './primitives/NodeActionAdd'; export * from './primitives/IfIcon'; export * from './cards/shared'; @@ -40,3 +43,4 @@ export * from './primitives/collapseReveal'; export * from './primitives/nodeHeaderButton'; export * from './lineGeometry'; export * from './primitives/useEdgeActiveState'; +export { useNodeOverviewStyles } from './overviewStyles'; diff --git a/libs/designer-ui-v2/src/nodes/metrics.ts b/libs/designer-ui-v2/src/nodes/metrics.ts index e784ff9e6d5..50d4f28d4a5 100644 --- a/libs/designer-ui-v2/src/nodes/metrics.ts +++ b/libs/designer-ui-v2/src/nodes/metrics.ts @@ -44,7 +44,12 @@ export const compactNodeMetrics = { icon: 20, gap: 8, textWidth: 142, - titleFont: { size: 14, weight: 600, lineHeight: 20 }, + titleFont: { + size: 14, + weight: 600, + lineHeight: 20, + family: "'Segoe UI', 'Segoe UI Web (West European)', -apple-system, BlinkMacSystemFont, Roboto, 'Helvetica Neue', sans-serif", + }, } as const; export type CompactTitleLines = 1 | 2; diff --git a/libs/designer-ui-v2/src/nodes/overviewStyles.ts b/libs/designer-ui-v2/src/nodes/overviewStyles.ts new file mode 100644 index 00000000000..9fbad1a757c --- /dev/null +++ b/libs/designer-ui-v2/src/nodes/overviewStyles.ts @@ -0,0 +1,28 @@ +import { makeStyles, tokens } from '@fluentui/react-components'; + +/** Apply to the canvas at overview zoom, not to a card or to its hover-card portal. */ +export const useNodeOverviewStyles = makeStyles({ + canvas: { + '& [data-node-card] [data-node-title]': { + fontSize: tokens.fontSizeBase400, + lineHeight: tokens.lineHeightBase300, + }, + '& [data-node-card] [data-node-caption]': { display: 'none' }, + '& [data-node-card] [data-node-status-icon]': { fontSize: tokens.fontSizeBase400 }, + // Enlarge the glyph within its existing tile, not the tile or the card. + '& [data-node-card] [data-node-glyph]': { transform: 'scale(1.2)' }, + '& [data-node-card$="-frame"]:not([data-selected="true"])': { + // Paint inside the existing boundary so handles and fitted bounds do not move. + outline: `${tokens.strokeWidthThick} dashed ${tokens.colorNeutralForeground3}`, + outlineOffset: `calc(-1 * ${tokens.strokeWidthThin})`, + }, + '& :is(path[data-line], [data-line] > path, [data-branch-convergence] > path)': { + // Host-managed edges also pass their normal stroke width inline. + strokeWidth: `${tokens.strokeWidthThick} !important`, + }, + '@media (forced-colors: none)': { + '& :is(path[data-line="solid"], path[data-line="dashedNeutral"], [data-line="solid"] > path, [data-line-cap="solid"], [data-line-cap="dashedNeutral"], [data-branch-convergence] > path):not([data-line-highlighted])': + { stroke: `${tokens.colorNeutralForeground3} !important` }, + }, + }, +}); diff --git a/libs/designer-ui-v2/src/nodes/primitives/LoopBodyJoin.tsx b/libs/designer-ui-v2/src/nodes/primitives/LoopBodyJoin.tsx new file mode 100644 index 00000000000..ef5dcdb108a --- /dev/null +++ b/libs/designer-ui-v2/src/nodes/primitives/LoopBodyJoin.tsx @@ -0,0 +1,49 @@ +import { makeStyles, tokens } from '@fluentui/react-components'; +import { NodeLine } from './NodeLine'; + +const useStyles = makeStyles({ + join: { + position: 'absolute', + transform: 'translateX(-50%)', + pointerEvents: 'none', + '[data-loop-active] > & > path': { + stroke: tokens.colorBrandStroke1, + '@media (forced-colors: active)': { stroke: 'Highlight' }, + }, + }, + header: { + '&[data-loop-group-header][data-loop-active]:not([data-selected])': { + outline: `${tokens.strokeWidthThin} solid ${tokens.colorBrandStroke1}`, + outlineOffset: '-1px', + '@media (forced-colors: active)': { outlineColor: 'Highlight' }, + }, + }, + body: { + '&[data-loop-active] > [data-node-card="loop-frame"]:not([data-selected])': { + outlineStyle: 'solid', + outlineWidth: tokens.strokeWidthThin, + outlineColor: tokens.colorBrandStroke1, + outlineOffset: '-1px', + '@media (forced-colors: active)': { outlineColor: 'Highlight' }, + }, + }, +}); + +export function LoopBodyJoin({ x, y, length }: { x: number; y: number; length: number }) { + const styles = useStyles(); + return ( + + ); +} + +/** Hover is a paint-only accent, independent of status tint and selection. */ +export function useLoopBodyHoverClass(part: 'header' | 'body') { + return useStyles()[part]; +} diff --git a/libs/designer-ui-v2/src/nodes/primitives/NodeAddButton.tsx b/libs/designer-ui-v2/src/nodes/primitives/NodeAddButton.tsx index d0958f1cba8..e5e5eec50f5 100644 --- a/libs/designer-ui-v2/src/nodes/primitives/NodeAddButton.tsx +++ b/libs/designer-ui-v2/src/nodes/primitives/NodeAddButton.tsx @@ -13,15 +13,21 @@ const useStyles = makeStyles({ paddingInline: 0, color: tokens.colorNeutralForeground4, }, + active: { + color: tokens.colorBrandForeground1, + backgroundColor: tokens.colorBrandBackground2, + '@media (forced-colors: active)': { outline: `${tokens.strokeWidthThick} solid Highlight` }, + }, }); export interface NodeAddButtonProps extends Omit, 'type' | 'children'> { label?: string; + active?: boolean; } /** Canonical standalone ActionAdd button; the host supplies any routed terminal path. */ export const NodeAddButton = forwardRef(function NodeAddButton( - { label = defaultNodeStrings.addAction, onClick, disabled, className, ...rest }, + { label = defaultNodeStrings.addAction, onClick, disabled, active, className, ...rest }, ref ) { const styles = useStyles(); @@ -31,7 +37,7 @@ export const NodeAddButton = forwardRef(f ref={ref} type="button" shape="circular" - className={mergeClasses(styles.button, className)} + className={mergeClasses(styles.button, active && styles.active, className)} appearance="subtle" icon={} aria-label={label} diff --git a/libs/designer-ui-v2/src/nodes/primitives/NodeBranchActions.tsx b/libs/designer-ui-v2/src/nodes/primitives/NodeBranchActions.tsx new file mode 100644 index 00000000000..d152e793892 --- /dev/null +++ b/libs/designer-ui-v2/src/nodes/primitives/NodeBranchActions.tsx @@ -0,0 +1,68 @@ +import { Button, makeStyles, mergeClasses, tokens } from '@fluentui/react-components'; +import type { ReactNode } from 'react'; +import { nodeMetrics } from '../metrics'; + +export interface NodeBranchActionItem { + key: string; + icon: ReactNode; + ariaLabel: string; + automationId?: string; + hasPopup?: boolean; + disabled?: boolean; + onInvoke: (anchor: HTMLElement) => void; +} + +// Reserve enough right-side header room for two compact actions (rename + overflow). +export const NODE_BRANCH_ACTIONS_MAX_RESERVE_PX = nodeMetrics.toolsHeader * 2 + 12; + +const useStyles = makeStyles({ + root: { + position: 'absolute', + insetInlineEnd: tokens.spacingHorizontalS, + top: '4px', + display: 'inline-flex', + alignItems: 'center', + gap: tokens.spacingHorizontalXXS, + }, + button: { + width: `${nodeMetrics.toolsHeader}px`, + height: `${nodeMetrics.toolsHeader}px`, + minWidth: '0', + padding: '0', + }, + icon: { + width: `${nodeMetrics.toolsActionIcon}px`, + height: `${nodeMetrics.toolsActionIcon}px`, + fontSize: `${nodeMetrics.toolsActionIcon}px`, + }, +}); + +export const NodeBranchActions = ({ items, className }: { items: readonly NodeBranchActionItem[]; className?: string }) => { + const styles = useStyles(); + if (!items.length) { + return null; + } + return ( +
+ {items.map((item) => ( +
+ ); +}; diff --git a/libs/designer-ui-v2/src/nodes/primitives/NodeBranchShell.tsx b/libs/designer-ui-v2/src/nodes/primitives/NodeBranchShell.tsx new file mode 100644 index 00000000000..390a51bfde0 --- /dev/null +++ b/libs/designer-ui-v2/src/nodes/primitives/NodeBranchShell.tsx @@ -0,0 +1,55 @@ +import { makeStyles, mergeClasses, tokens } from '@fluentui/react-components'; +import type { HTMLAttributes } from 'react'; +import { nodeMetrics } from '../metrics'; +import { NODE_BRANCH_ACTIONS_MAX_RESERVE_PX } from './NodeBranchActions'; + +const useStyles = makeStyles({ + root: { + position: 'relative', + boxSizing: 'border-box', + display: 'grid', + gridTemplateColumns: 'minmax(0, 1fr)', + alignItems: 'center', + textAlign: 'center', + height: '100%', + paddingInline: tokens.spacingHorizontalXXL, + borderRadius: tokens.borderRadius2XLarge, + color: tokens.colorNeutralForeground1, + }, + success: { backgroundColor: tokens.colorStatusSuccessBackground1 }, + danger: { backgroundColor: tokens.colorStatusDangerBackground1 }, + neutral: { backgroundColor: tokens.colorNeutralBackground3 }, + info: { backgroundColor: tokens.colorPaletteBlueBackground2 }, + selected: { outline: `${tokens.strokeWidthThick} solid ${tokens.colorCompoundBrandStroke}`, outlineOffset: '-2px' }, + inactive: { opacity: nodeMetrics.inactiveOpacity }, + withActions: { + paddingInlineEnd: `calc(${tokens.spacingHorizontalXXL} + ${NODE_BRANCH_ACTIONS_MAX_RESERVE_PX + nodeMetrics.toolsHeader + 8}px)`, + }, +}); + +export interface NodeBranchShellProps extends HTMLAttributes { + tone: 'success' | 'danger' | 'neutral' | 'info'; + selected?: boolean; + inactive?: boolean; + ancestorInactive?: boolean; + hasActions?: boolean; +} + +/** Branch-header surface only. The host supplies lane identity, children, and graph commands. */ +export function NodeBranchShell({ tone, selected, inactive, ancestorInactive, hasActions, className, ...props }: NodeBranchShellProps) { + const styles = useStyles(); + return ( +
+ ); +} diff --git a/libs/designer-ui-v2/src/nodes/primitives/NodeCard.tsx b/libs/designer-ui-v2/src/nodes/primitives/NodeCard.tsx index ba650996f01..c3bf4edf59c 100644 --- a/libs/designer-ui-v2/src/nodes/primitives/NodeCard.tsx +++ b/libs/designer-ui-v2/src/nodes/primitives/NodeCard.tsx @@ -16,7 +16,12 @@ const footerBg = nodeCardVars.footerBackground; const useStyles = makeStyles({ root: { position: 'relative', boxSizing: 'border-box', display: 'flex', flexDirection: 'column', fontFamily: 'inherit' }, compact: { width: `${nodeMetrics.cards.condition.width}px` }, - standardCompact: { width: `${compactNodeMetrics.card.width}px` }, + standardCompact: { + width: `${compactNodeMetrics.card.width}px`, + [nodeCardVars.titleFamily]: compactNodeMetrics.titleFont.family, + [nodeCardVars.titleSize]: `${compactNodeMetrics.titleFont.size}px`, + [nodeCardVars.titleWeight]: `${compactNodeMetrics.titleFont.weight}`, + }, standard: { width: `${nodeMetrics.cards.action.width}px` }, wide: { width: `${nodeMetrics.cards.agent.width}px` }, fill: { width: '100%' }, @@ -85,7 +90,10 @@ const useStyles = makeStyles({ outlineOffset: '-2px', '@media (forced-colors: active)': { ...shorthands.borderColor('Highlight'), outlineColor: 'Highlight' }, }, - focus: { ':focus-visible': { outline: `${tokens.strokeWidthThick} solid ${tokens.colorStrokeFocus2}`, outlineOffset: '2px' } }, + focus: { + ':focus-visible': { outline: `${tokens.strokeWidthThick} solid ${tokens.colorStrokeFocus2}`, outlineOffset: '2px' }, + '@media (forced-colors: active)': { ':focus-visible': { outlineColor: 'CanvasText' } }, + }, badge: { position: 'absolute', top: 0, left: '50%', transform: 'translate(-50%, -50%)', zIndex: 1 }, // Vertical-axis cards centre their input handle on the top edge. The badge starts past that handle and grows away // from it, so no label length can cover the handle (right anchoring grew labels leftward across the centreline). @@ -102,7 +110,7 @@ const useStyles = makeStyles({ ...shorthands.border('2px', 'solid', 'transparent'), pointerEvents: 'none', zIndex: 1, - '@media (forced-colors: active)': { ...shorthands.borderColor('CanvasText') }, + '@media (forced-colors: active)': { ...shorthands.borderColor('CanvasText'), ...shorthands.borderStyle('dashed') }, }, perimeterSuccess: { ...shorthands.borderColor(tokens.colorStatusSuccessBorder2) }, perimeterDanger: { ...shorthands.borderColor(tokens.colorStatusDangerBorder2) }, @@ -245,6 +253,7 @@ export const NodeCard = forwardRef(function NodeC /> ) : null}
(funct data-artwork={artwork || undefined} aria-hidden="true" > - {selected ? (selectedIcon ?? icon) : icon} + + {selected ? (selectedIcon ?? icon) : icon} + ); }); diff --git a/libs/designer-ui-v2/src/nodes/primitives/NodeLine.tsx b/libs/designer-ui-v2/src/nodes/primitives/NodeLine.tsx index f1c24b9044d..a3e8b9a7ebf 100644 --- a/libs/designer-ui-v2/src/nodes/primitives/NodeLine.tsx +++ b/libs/designer-ui-v2/src/nodes/primitives/NodeLine.tsx @@ -52,13 +52,13 @@ const useNodeLineStateStyles = makeStyles({ default: {}, taken: { strokeWidth: nodeLineStateOverrides.taken.strokeWidth, - '@media (forced-colors: active)': { stroke: 'Highlight' }, + '@media (forced-colors: active)': { stroke: 'Highlight !important' }, }, notTaken: { opacity: nodeLineStateOverrides.notTaken.opacity }, highlighted: { stroke: nodeLineStateOverrides.highlighted.stroke, strokeWidth: nodeLineStateOverrides.highlighted.strokeWidth, - '@media (forced-colors: active)': { stroke: 'Highlight' }, + '@media (forced-colors: active)': { stroke: 'Highlight !important' }, }, running: { stroke: nodeLineStateOverrides.running.stroke, @@ -74,7 +74,14 @@ const useNodeLineStateStyles = makeStyles({ }); export const useNodeLineStyles = makeStyles({ - base: { fill: 'none', strokeWidth: tokens.strokeWidthThin, '@media (forced-colors: active)': { stroke: 'CanvasText' } }, + base: { + fill: 'none', + strokeWidth: tokens.strokeWidthThin, + '@media (forced-colors: active)': { + stroke: 'CanvasText !important', + '&[data-line-highlighted]': { stroke: 'Highlight !important' }, + }, + }, solid: { stroke: nodeLineStrokes.solid.stroke }, solidSuccess: { stroke: nodeLineStrokes.solidSuccess.stroke, @@ -129,7 +136,11 @@ export const NodeLine = forwardRef(function NodeLi data-state={state === 'default' ? undefined : state} data-arrow={variant === 'solid' && !showArrow ? 'false' : undefined} > - + ); }); diff --git a/libs/designer-ui-v2/src/nodes/primitives/NodeText.tsx b/libs/designer-ui-v2/src/nodes/primitives/NodeText.tsx index 62903a3a50c..e131d8c5a78 100644 --- a/libs/designer-ui-v2/src/nodes/primitives/NodeText.tsx +++ b/libs/designer-ui-v2/src/nodes/primitives/NodeText.tsx @@ -13,8 +13,9 @@ const useStyles = makeStyles({ textOverflow: 'ellipsis', whiteSpace: 'nowrap', paddingInlineEnd: `var(${nodeCardVars.textEndReserve}, 0)`, - fontSize: tokens.fontSizeBase300, - fontWeight: tokens.fontWeightSemibold, + fontFamily: `var(${nodeCardVars.titleFamily}, inherit)`, + fontSize: `var(${nodeCardVars.titleSize}, ${tokens.fontSizeBase300})`, + fontWeight: `var(${nodeCardVars.titleWeight}, ${tokens.fontWeightSemibold})`, lineHeight: tokens.lineHeightBase300, color: tokens.colorNeutralForeground1, }, @@ -26,6 +27,11 @@ const useStyles = makeStyles({ whiteSpace: 'normal', overflowWrap: 'anywhere', }, + titleFirst: { + // Reuse the wrapped card's subtitle space without growing its accepted layout bounds. + WebkitLineClamp: 3, + lineHeight: `calc(${tokens.lineHeightBase300} - ${tokens.spacingVerticalXXS})`, + }, subtitle: { overflow: 'hidden', textOverflow: 'ellipsis', @@ -87,6 +93,8 @@ export interface NodeTextProps extends HTMLAttributes { subtitleKind?: 'default' | 'status'; /** Maximum title lines; defaults to a single ellipsized line. */ titleLines?: 1 | 2; + /** In a wrapped card, let the title use the decorative caption's row. Status and counts keep their row. */ + prioritizeTitle?: boolean; /** Preformatted count (for example "3 actions") shown after the subtitle on collapsed container cards. */ count?: string; countUnit?: NodeFrameCountUnit; @@ -95,7 +103,7 @@ export interface NodeTextProps extends HTMLAttributes { } export const NodeHoverCardActiveContext = createContext(false); export const NodeText = forwardRef(function NodeText( - { title, subtitle, subtitleKind = 'default', titleLines = 1, count, countUnit, countId, className, ...rest }, + { title, subtitle, subtitleKind = 'default', titleLines = 1, prioritizeTitle, count, countUnit, countId, className, ...rest }, ref ) { const styles = useStyles(); @@ -103,15 +111,22 @@ export const NodeText = forwardRef(function Node const statusContext = useContext(NodeCardStatusContext); const statusSubtitle = subtitleKind === 'status' ? statusContext : undefined; const statusTitle = statusSubtitle ? [statusSubtitle.statusLabel, statusSubtitle.statusDetail].filter(Boolean).join(' ') : undefined; + const useCaptionRow = prioritizeTitle && titleLines === 2 && subtitleKind !== 'status' && !count; return ( - + {title} {statusSubtitle ? ( - {getNodeStatusIcon(statusSubtitle.status, styles.statusIcon)} + + {getNodeStatusIcon(statusSubtitle.status, styles.statusIcon)} + {statusSubtitle.statusLabel} {statusSubtitle.statusDetail ? {statusSubtitle.statusDetail} : null} @@ -129,7 +144,7 @@ export const NodeText = forwardRef(function Node ) : count ? ( {subtitle ? ( - + {subtitle} - ) : subtitle ? ( - + ) : subtitle && !useCaptionRow ? ( + {subtitle} ) : null} diff --git a/libs/designer-ui-v2/src/theme/tokens.ts b/libs/designer-ui-v2/src/theme/tokens.ts index 935d6105cbf..4141ebbaced 100644 --- a/libs/designer-ui-v2/src/theme/tokens.ts +++ b/libs/designer-ui-v2/src/theme/tokens.ts @@ -28,4 +28,7 @@ export const nodeCardVars = { background: '--designer-ui-v2-node-card-background', footerBackground: '--designer-ui-v2-node-card-footer-background', textEndReserve: '--designer-ui-v2-node-text-end-reserve', + titleFamily: '--designer-ui-v2-node-title-family', + titleSize: '--designer-ui-v2-node-title-size', + titleWeight: '--designer-ui-v2-node-title-weight', } as const; diff --git a/libs/designer-ui-v2/stories/API.mdx b/libs/designer-ui-v2/stories/API.mdx index 36c7f84304c..18b68983e62 100644 --- a/libs/designer-ui-v2/stories/API.mdx +++ b/libs/designer-ui-v2/stories/API.mdx @@ -28,7 +28,7 @@ components or hooks. `/package.json` exposes manifest metadata. Source/build deep imports and a package `/nodes` subpath are unsupported. Storybook's exact source aliases do not change the package export map. -## All 31 nonvisual runtime exports +## All 39 nonvisual runtime exports @@ -132,13 +132,14 @@ source aliases do not change the package export map.
-The additional 13 Phase 1a/1b runtime exports are: +Other nonvisual exports: | Export | Contract | |---|---| | `NodeInactiveContext` | Boolean presentation context (default false); nested cards/ports avoid applying opacity twice. | | `defaultBranchTakenString` | `(label) => "
) ) : null} + + + + {intlText.renameCaseTitle} + + + + + + + + + + + +
); }; diff --git a/libs/designer-v2/src/lib/ui/CustomNodes/__test__/GraphContainerNode.spec.tsx b/libs/designer-v2/src/lib/ui/CustomNodes/__test__/GraphContainerNode.spec.tsx index ce8ad1f2385..9b4328241cc 100644 --- a/libs/designer-v2/src/lib/ui/CustomNodes/__test__/GraphContainerNode.spec.tsx +++ b/libs/designer-v2/src/lib/ui/CustomNodes/__test__/GraphContainerNode.spec.tsx @@ -26,6 +26,7 @@ vi.mock('../../../core/state/panel/panelSelectors', () => ({ })); vi.mock('../../../core/state/workflow/workflowSelectors', () => ({ + useIsGraphCollapsed: () => false, useActionMetadata: vi.fn(), useNodeMetadata: vi.fn(), useNodeDisplayName: () => 'Actual graph display name', diff --git a/libs/designer-v2/src/lib/ui/CustomNodes/__test__/OperationCardNode.spec.tsx b/libs/designer-v2/src/lib/ui/CustomNodes/__test__/OperationCardNode.spec.tsx index e6ecd159ed1..51dec4f0163 100644 --- a/libs/designer-v2/src/lib/ui/CustomNodes/__test__/OperationCardNode.spec.tsx +++ b/libs/designer-v2/src/lib/ui/CustomNodes/__test__/OperationCardNode.spec.tsx @@ -54,10 +54,15 @@ vi.mock('../../../core/state/designerOptions/designerOptionsSelectors', () => ({ useSharedNodeUi: () => mockUseSharedNodeUi(), useMonitoringView: () => mockUseMonitoringView(), useReadOnly: () => mockUseReadOnly(), + usePanelTabHideKeys: () => [], useSuppressDefaultNodeSelectFunctionality: () => mockUseSuppressDefault(), useNodeSelectAdditionalCallback: () => mockUseNodeSelectCallback(), })); +vi.mock('../../../core/state/staticresultschema/staitcresultsSelector', () => ({ + useHasSchema: () => false, +})); + vi.mock('../../../core/state/designerView/designerViewSlice', () => ({ setNodeContextMenuData: vi.fn((payload) => ({ type: 'designerView/setNodeContextMenuData', payload })), setShowDeleteModalNodeId: vi.fn((payload) => ({ type: 'designerView/setShowDeleteModalNodeId', payload })), @@ -167,8 +172,25 @@ vi.mock('../../../core/state/workflow/workflowSlice', () => ({ })); vi.mock('../../common/LoopsPager/helper', () => ({ + getAgentRepetitionIdentity: vi.fn((...args: any[]) => { + const first = args[0]; + const params = + typeof first === 'object' && first !== null + ? first + : { + runId: args[0], + ownerNodeId: args[1], + repetitionName: args[2], + repetitionIndex: args[3], + parentStatus: args[4], + }; + const { runId, ownerNodeId, repetitionName, repetitionIndex, parentStatus } = params; + return runId && ownerNodeId && repetitionName !== undefined && repetitionIndex !== undefined + ? [runId, ownerNodeId, repetitionName, String(repetitionIndex), parentStatus ?? ''].join('|') + : undefined; + }), getRepetitionName: vi.fn().mockReturnValue('000000'), - getScopeRepetitionName: vi.fn().mockReturnValue('000000'), + getScopeRepetitionName: vi.fn((index) => String(index).padStart(6, '0')), useRepetitionName: vi.fn().mockReturnValue(''), })); @@ -360,6 +382,91 @@ describe('OperationCardNode (v2)', () => { expect(screen.queryByTestId(absent)).toBeNull(); }); + it('hides the shared MCP tool pager while metadata is for a different selected iteration', () => { + mockUseSharedNodeUi.mockReturnValue(true); + mockUseMonitoringView.mockReturnValue(true); + mockUseRunInstance.mockReturnValue({ id: 'run-1' }); + mockUseRunIndex.mockReturnValue(2); + mockUseParentNodeId.mockImplementation((id?: string) => { + if (id === 'testNode') { + return 'actual-agent'; + } + if (id === 'actual-agent') { + return 'agent-parent'; + } + return undefined; + }); + mockUseRunData.mockImplementation((id?: string) => { + if (id === 'agent-parent') { + return { status: 'Succeeded' }; + } + return undefined; + }); + mockUseActionMetadata.mockImplementation((id?: string) => (id === 'actual-agent' ? { type: 'Agent' } : undefined)); + const staleMetadata = { + graphId: 'actual-agent', + parentNodeId: 'actual-agent', + subgraphType: 'MCP_CLIENT', + toolRunData: { repetitionCount: 2 }, + agentRepetitionIdentity: 'run-1|actual-agent|000001|1|Succeeded', + }; + mockUseNodeMetadata.mockReturnValue(staleMetadata); + + const { rerender } = render(); + expect(screen.queryByTestId('shared-loops-pager-testNode')).toBeNull(); + + mockUseNodeMetadata.mockReturnValue({ + ...staleMetadata, + agentRepetitionIdentity: 'run-1|actual-agent|000002|2|Succeeded', + }); + rerender(); + expect(screen.getByTestId('shared-loops-pager-testNode')).toBeInTheDocument(); + + mockUseRunData.mockImplementation((id?: string) => (id === 'testNode' || id === 'agent-parent' ? { status: 'Succeeded' } : undefined)); + mockUseNodeMetadata.mockReturnValue({ + ...staleMetadata, + toolRunData: undefined, + agentRepetitionIdentity: 'run-1|actual-agent|000002|2|Succeeded', + }); + rerender(); + expect(screen.getByRole('button')).not.toHaveAttribute('data-status', 'succeeded'); + }); + + it('uses the action status inside a conditional Agent tool rather than requiring a direct tool stamp', () => { + mockUseSharedNodeUi.mockReturnValue(true); + mockUseMonitoringView.mockReturnValue(true); + mockUseRunInstance.mockReturnValue({ id: 'run-1' }); + mockUseRunIndex.mockReturnValue(2); + mockUseParentNodeId.mockReturnValue('actual-agent'); + mockUseActionMetadata.mockImplementation((id?: string) => (id === 'actual-agent' ? { type: 'Agent' } : undefined)); + mockUseNodeMetadata.mockReturnValue({ graphId: 'conditional-tool', parentNodeId: 'actual-agent' }); + mockUseRunData.mockImplementation((id?: string) => (id === 'testNode' ? { status: 'Succeeded' } : undefined)); + + render(); + + expect(screen.getByRole('button')).toHaveAttribute('data-status', 'succeeded'); + }); + + it('updates run data when the selected repetition response has no actionTrackingId', () => { + mockUseMonitoringView.mockReturnValue(true); + mockUseRunInstance.mockReturnValue({ id: 'run-1' }); + mockUseParentRunIndex.mockReturnValue(0); + mockUseNodeRepetition.mockReturnValue({ + isFetching: false, + data: { properties: { status: 'Succeeded', inputsLink: null, outputsLink: null } }, + }); + mockUseRunData.mockReturnValue(undefined); + + render(); + + expect(mockDispatch).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'workflow/setRepetitionRunData', + payload: expect.objectContaining({ nodeId: 'testNode' }), + }) + ); + }); + it('uses actual immediate Agent parent metadata for tool identity, never the display name', () => { mockUseSharedNodeUi.mockReturnValue(true); mockUseParentNodeId.mockReturnValue('actual-agent'); @@ -543,6 +650,24 @@ describe('OperationCardNode (v2)', () => { ); }); + it.each([false, true])('does not request Delete from a focused monitoring operation (Shared: %s)', (sharedOption) => { + mockUseReadOnly.mockReturnValue(true); + mockUseMonitoringView.mockReturnValue(true); + const { container } = render(); + if (sharedOption) { + const card = container.querySelector('#msla-node-testNode'); + expect(card).toBeInTheDocument(); + if (card) { + fireEvent.keyDown(card, { key: 'Delete' }); + } + } else { + // The Legacy card test double exposes the same callback as the real Delete-key handler. + expect(screen.queryByTestId('delete-btn')).not.toBeInTheDocument(); + } + + expect(mockDispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'designerView/setShowDeleteModalNodeId' })); + }); + it('defers the leaf DropZone until initial mount settles without changing accepted shared geometry', () => { mockUseIsLeafNode.mockReturnValue(true); mockUseInitialMountSettled.mockReturnValue(false); diff --git a/libs/designer-v2/src/lib/ui/CustomNodes/__test__/ScopeCardNode.spec.tsx b/libs/designer-v2/src/lib/ui/CustomNodes/__test__/ScopeCardNode.spec.tsx index 7f1f0927185..98907699925 100644 --- a/libs/designer-v2/src/lib/ui/CustomNodes/__test__/ScopeCardNode.spec.tsx +++ b/libs/designer-v2/src/lib/ui/CustomNodes/__test__/ScopeCardNode.spec.tsx @@ -30,10 +30,16 @@ vi.mock('../../../core/actions/bjsworkflow/move', () => ({ moveOperation: vi.fn((payload) => ({ type: 'moveOperation', payload })), })); +const mockUseNodeRepetition = vi.fn(); +const mockUseAgentRepetition = vi.fn(); +const mockUseAgentActionsRepetition = vi.fn(); +const mockUseConditionOutputs = vi.fn(); + vi.mock('../../../core/queries/runs', () => ({ - useNodeRepetition: () => ({ isFetching: false, data: undefined }), - useAgentRepetition: () => ({ isFetching: false, data: undefined }), - useAgentActionsRepetition: () => ({ isFetching: false, data: undefined }), + useNodeRepetition: () => mockUseNodeRepetition(), + useConditionOutputs: () => mockUseConditionOutputs(), + useAgentRepetition: () => mockUseAgentRepetition(), + useAgentActionsRepetition: () => mockUseAgentActionsRepetition(), })); const mockUseMonitoringView = vi.fn().mockReturnValue(false); @@ -151,8 +157,25 @@ vi.mock('../../../core/state/workflow/workflowSlice', () => ({ })); vi.mock('../../common/LoopsPager/helper', () => ({ + getAgentRepetitionIdentity: vi.fn((...args: any[]) => { + const first = args[0]; + const params = + typeof first === 'object' && first !== null + ? first + : { + runId: args[0], + ownerNodeId: args[1], + repetitionName: args[2], + repetitionIndex: args[3], + parentStatus: args[4], + }; + const { runId, ownerNodeId, repetitionName, repetitionIndex, parentStatus } = params; + return runId && ownerNodeId && repetitionName !== undefined && repetitionIndex !== undefined + ? [runId, ownerNodeId, repetitionName, String(repetitionIndex), parentStatus ?? ''].join('|') + : undefined; + }), getRepetitionName: vi.fn().mockReturnValue('000000'), - getScopeRepetitionName: vi.fn().mockReturnValue('000000'), + getScopeRepetitionName: vi.fn((index) => String(index).padStart(6, '0')), useRepetitionName: vi.fn().mockReturnValue(''), })); @@ -251,6 +274,10 @@ describe('ScopeCardNode (v2)', () => { const defaultProps = { id: 'testScope-#scope' } as NodeProps; beforeEach(() => { + mockUseNodeRepetition.mockReturnValue({ isFetching: false, data: undefined }); + mockUseAgentRepetition.mockReturnValue({ isFetching: false, data: undefined }); + mockUseAgentActionsRepetition.mockReturnValue({ isFetching: false, data: undefined }); + mockUseConditionOutputs.mockReturnValue(undefined); mockUseSharedNodeUi.mockReturnValue(false); vi.clearAllMocks(); cleanup(); @@ -317,6 +344,141 @@ describe('ScopeCardNode (v2)', () => { if (type === 'Agent') expect(screen.getByText('actual-model')).toBeInTheDocument(); }); + it('maps a shared If takenOutput only from authoritative expressionResult for the selected repetition', () => { + mockUseSharedNodeUi.mockReturnValue(true); + mockUseMonitoringView.mockReturnValue(true); + mockUseActionMetadata.mockReturnValue({ type: 'If', runAfter: {} }); + mockUseRunData.mockReturnValue({ status: 'Succeeded', outputs: { expressionResult: true } }); + const { container } = render( + + ); + expect(container.querySelector('[data-branch="true"][data-taken="true"]')).not.toBeNull(); + expect(container.querySelector('[data-branch="false"][data-taken="true"]')).toBeNull(); + expect(screen.getByText('True, branch taken')).toBeInTheDocument(); + }); + + it('suppresses shared If takenOutput when no authoritative expressionResult is present', () => { + mockUseSharedNodeUi.mockReturnValue(true); + mockUseMonitoringView.mockReturnValue(true); + mockUseActionMetadata.mockReturnValue({ type: 'If', runAfter: {} }); + mockUseRunData.mockReturnValue({ status: 'Succeeded', outputs: {} }); + const { container } = render( + + ); + expect(container.querySelector('[data-branch][data-taken="true"]')).toBeNull(); + expect(screen.queryByText(/branch taken/)).toBeNull(); + }); + + it('does not show a previous If outcome while the selected repetition is loading', () => { + mockUseSharedNodeUi.mockReturnValue(true); + mockUseMonitoringView.mockReturnValue(true); + mockUseActionMetadata.mockReturnValue({ type: 'If', runAfter: {} }); + mockUseRunInstance.mockReturnValue({ id: 'run' }); + mockUseParentRunIndex.mockReturnValue(1); + mockUseIsActionInSelectedTimelineRepetition.mockReturnValue(true); + mockUseRunData.mockReturnValue({ status: 'Succeeded', outputs: { expressionResult: true } }); + mockUseNodeRepetition.mockReturnValue({ isFetching: true }); + const props = { + ...defaultProps, + data: { + presentation: { shared: true, family: 'if' }, + branchPorts: [ + { id: 'testScope-actions', subgraphType: 'CONDITIONAL_TRUE' }, + { id: 'testScope-elseActions', subgraphType: 'CONDITIONAL_FALSE' }, + ], + }, + }; + const { rerender } = render(); + expect(screen.queryByText(/branch taken/)).not.toBeInTheDocument(); + + mockUseNodeRepetition.mockReturnValue({ + isFetching: false, + data: { properties: { status: 'Succeeded', outputs: { expressionResult: false } } }, + }); + rerender(); + expect(screen.getByText('False, branch taken')).toBeInTheDocument(); + expect(screen.queryByText('True, branch taken')).not.toBeInTheDocument(); + }); + + it('maps shared Switch takenOutput from expressionResult when it matches a declared case value', () => { + mockUseSharedNodeUi.mockReturnValue(true); + mockUseMonitoringView.mockReturnValue(true); + mockUseActionMetadata.mockReturnValue({ + type: 'Switch', + runAfter: {}, + cases: { + firstCase: { case: 'first' }, + secondCase: { case: 'second' }, + }, + }); + mockUseRunData.mockReturnValue({ status: 'Succeeded', outputs: { expressionResult: 'second' } }); + const { container } = render( + + ); + const handles = container.querySelectorAll('[data-testid="node-output-handles"] [data-handle]'); + expect(handles).toHaveLength(3); + expect(handles[0]).toHaveAttribute('data-inactive', 'true'); + expect(handles[1]).not.toHaveAttribute('data-inactive'); + expect(handles[2]).toHaveAttribute('data-inactive', 'true'); + }); + + it('does not infer a shared Switch takenOutput when expressionResult does not map to a declared case', () => { + mockUseSharedNodeUi.mockReturnValue(true); + mockUseMonitoringView.mockReturnValue(true); + mockUseActionMetadata.mockReturnValue({ + type: 'Switch', + runAfter: {}, + cases: { + firstCase: { case: 'first' }, + }, + }); + mockUseRunData.mockReturnValue({ status: 'Succeeded', outputs: { expressionResult: 'firstCase' } }); + const { container } = render( + + ); + const handles = container.querySelectorAll('[data-testid="node-output-handles"] [data-handle]'); + expect(handles).toHaveLength(2); + expect(handles[0]).not.toHaveAttribute('data-inactive'); + expect(handles[1]).not.toHaveAttribute('data-inactive'); + }); + it.each([ [false, 'loops-pager-testScope', 'shared-loops-pager-testScope'], [true, 'shared-loops-pager-testScope', 'loops-pager-testScope'], @@ -325,11 +487,138 @@ describe('ScopeCardNode (v2)', () => { mockUseMonitoringView.mockReturnValue(true); mockUseActionMetadata.mockReturnValue({ type: 'Foreach', runAfter: {} }); mockUseNodeMetadata.mockReturnValue({ graphId: 'root', actionCount: 2, runData: { status: 'Succeeded', repetitionCount: 3 } }); - render(); + render(); expect(screen.getByTestId(present)).toBeInTheDocument(); expect(screen.queryByTestId(absent)).toBeNull(); }); + it('only admits the selected Agent response, even when both inputs links are missing', () => { + mockUseMonitoringView.mockReturnValue(true); + mockUseSharedNodeUi.mockReturnValue(true); + mockUseActionMetadata.mockReturnValue({ type: 'Agent', runAfter: {} }); + mockUseRunInstance.mockReturnValue({ id: 'run-1' }); + mockUseRunIndex.mockReturnValue(2); + mockUseIsActionInSelectedTimelineRepetition.mockReturnValue(true); + mockUseParentNodeId.mockReturnValue('parentScope'); + mockUseRunData.mockImplementation((id: string) => { + if (id === 'parentScope') { + return { status: 'Succeeded' }; + } + if (id === 'testScope') { + return { status: 'Succeeded', inputsLink: null, outputsLink: null, repetitionCount: 3 }; + } + return undefined; + }); + mockUseNodeMetadata.mockReturnValue({ + graphId: 'root', + actionCount: 2, + runData: { status: 'Succeeded', inputsLink: null, outputsLink: null, repetitionCount: 3 }, + agentRepetitionIdentity: 'run-1|testScope|000001|1|Succeeded', + }); + const properties = { status: 'Failed', tools: {}, inputsLink: null, outputsLink: null }; + const card = () => ; + const metadataDispatch = () => mockDispatch.mock.calls.find(([action]) => action?.type === 'workflow/updateAgenticMetadata'); + mockUseAgentRepetition.mockReturnValue({ isFetching: false, data: { name: '000001', properties } }); + const { rerender } = render(card()); + expect(metadataDispatch()).toBeUndefined(); + + mockUseAgentRepetition.mockReturnValue({ isFetching: true, data: { name: '000002', properties } }); + rerender(card()); + expect(metadataDispatch()).toBeUndefined(); + + mockUseAgentRepetition.mockReturnValue({ isFetching: false, data: { name: '000002', properties } }); + rerender(card()); + expect(metadataDispatch()?.[0]?.payload).toEqual( + expect.objectContaining({ + nodeId: 'testScope', + agentRepetitionIdentity: 'run-1|testScope|000002|2|Succeeded', + }) + ); + }); + + it.each([ + [undefined, 'Test Scope, Running'], + [0, 'Test Scope'], + ])('keeps an Agent summary separate from stale repetition status (parent index %s)', (parentIndex, expectedName) => { + mockUseSharedNodeUi.mockReturnValue(true); + mockUseMonitoringView.mockReturnValue(true); + mockUseActionMetadata.mockReturnValue({ type: 'Agent', runAfter: {} }); + mockUseRunInstance.mockReturnValue({ id: 'run-1', properties: { actions: { testScope: { status: 'Running' } } } }); + mockUseParentRunIndex.mockReturnValue(parentIndex); + mockUseRunIndex.mockReturnValue(2); + mockUseIsActionInSelectedTimelineRepetition.mockReturnValue(true); + const previousPage = { status: 'Failed', repetitionCount: 3 }; + mockUseRunData.mockReturnValue(previousPage); + mockUseNodeMetadata.mockReturnValue({ + graphId: 'root', + actionCount: 2, + runData: previousPage, + agentRepetitionIdentity: 'run-1|testScope|000001|1|', + }); + + const { container } = render(); + + expect(container.querySelector('#msla-node-testScope')).toHaveAccessibleName(expectedName); + }); + + it('keeps the Agent iteration selector usable while new tool metadata loads', () => { + mockUseSharedNodeUi.mockReturnValue(true); + mockUseMonitoringView.mockReturnValue(true); + mockUseActionMetadata.mockReturnValue({ type: 'Agent', runAfter: {} }); + mockUseRunInstance.mockReturnValue({ id: 'run-1' }); + mockUseRunIndex.mockReturnValue(2); + mockUseIsActionInSelectedTimelineRepetition.mockReturnValue(true); + mockUseParentNodeId.mockReturnValue('parentScope'); + mockUseRunData.mockImplementation((id: string) => { + if (id === 'parentScope') { + return { status: 'Succeeded' }; + } + if (id === 'testScope') { + return { status: 'Succeeded', repetitionCount: 3 }; + } + return undefined; + }); + const metadataBase = { + graphId: 'root', + actionCount: 2, + runData: { status: 'Succeeded', repetitionCount: 3 }, + }; + mockUseNodeMetadata.mockImplementation((id: string) => + id === 'testScope' + ? { ...metadataBase, agentRepetitionIdentity: 'run-1|testScope|000001|1|Succeeded' } + : { graphId: 'root', actionCount: 0 } + ); + + const { rerender } = render(); + expect(screen.getByTestId('shared-loops-pager-testScope')).toBeInTheDocument(); + + mockUseNodeMetadata.mockImplementation((id: string) => + id === 'testScope' + ? { ...metadataBase, agentRepetitionIdentity: 'run-1|testScope|000002|2|Succeeded' } + : { graphId: 'root', actionCount: 0 } + ); + rerender(); + expect(screen.getByTestId('shared-loops-pager-testScope')).toBeInTheDocument(); + }); + + it('keeps legacy no-runId agent pager behavior unchanged', () => { + mockUseSharedNodeUi.mockReturnValue(true); + mockUseMonitoringView.mockReturnValue(true); + mockUseActionMetadata.mockReturnValue({ type: 'Agent', runAfter: {} }); + mockUseRunInstance.mockReturnValue(undefined); + mockUseRunIndex.mockReturnValue(2); + mockUseIsActionInSelectedTimelineRepetition.mockReturnValue(true); + mockUseNodeMetadata.mockReturnValue({ + graphId: 'root', + actionCount: 2, + runData: { status: 'Succeeded', repetitionCount: 3 }, + }); + mockUseRunData.mockReturnValue({ status: 'Succeeded', repetitionCount: 3 }); + + render(); + expect(screen.getByTestId('shared-loops-pager-testScope')).toBeInTheDocument(); + }); + it('keeps the accepted legacy scope renderer during a pending shared toggle', () => { mockUseSharedNodeUi.mockReturnValue(true); render(); diff --git a/libs/designer-v2/src/lib/ui/CustomNodes/__test__/SubgraphCardNode.spec.tsx b/libs/designer-v2/src/lib/ui/CustomNodes/__test__/SubgraphCardNode.spec.tsx index f01af7b48d8..4797d73fa2b 100644 --- a/libs/designer-v2/src/lib/ui/CustomNodes/__test__/SubgraphCardNode.spec.tsx +++ b/libs/designer-v2/src/lib/ui/CustomNodes/__test__/SubgraphCardNode.spec.tsx @@ -84,10 +84,12 @@ const mockUseNewAdditiveSubgraphId = vi.fn().mockReturnValue('newCase-1'); const mockUseNodeDisplayName = vi.fn().mockReturnValue('Test Subgraph'); const mockUseNodeMetadata = vi.fn().mockReturnValue({ graphId: 'graph1', subgraphType: SUBGRAPH_TYPES.SWITCH_CASE, actionCount: 2 }); const mockUseParentNodeId = vi.fn().mockReturnValue(undefined); +const mockUseReplacedIds = vi.fn().mockReturnValue({}); const mockUseRunData = vi.fn().mockReturnValue(undefined); const mockUseRunIndex = vi.fn().mockReturnValue(0); const mockUseRunInstance = vi.fn().mockReturnValue(undefined); const mockUseWorkflowNode = vi.fn().mockReturnValue({ id: 'graph1', children: [] }); +const mockUseNodesMetadata = vi.fn().mockReturnValue({}); const mockUseFlowErrorsForNode = vi.fn().mockReturnValue([]); const mockUseBranchValidationCount = vi.fn().mockReturnValue(0); @@ -99,16 +101,19 @@ vi.mock('../../../core/state/workflow/workflowSelectors', () => ({ useNodeDisplayName: (...args: any[]) => mockUseNodeDisplayName(...args), useNodeMetadata: (...args: any[]) => mockUseNodeMetadata(...args), useParentNodeId: (...args: any[]) => mockUseParentNodeId(...args), + useReplacedIds: (...args: any[]) => mockUseReplacedIds(...args), useRunData: (...args: any[]) => mockUseRunData(...args), useRunIndex: (...args: any[]) => mockUseRunIndex(...args), useRunInstance: (...args: any[]) => mockUseRunInstance(...args), useWorkflowNode: (...args: any[]) => mockUseWorkflowNode(...args), + useNodesMetadata: (...args: any[]) => mockUseNodesMetadata(...args), useFlowErrorsForNode: (...args: any[]) => mockUseFlowErrorsForNode(...args), useBranchValidationCount: (...args: any[]) => mockUseBranchValidationCount(...args), })); vi.mock('../../../core/state/workflow/workflowSlice', () => ({ addSwitchCase: vi.fn((payload) => ({ type: 'workflow/addSwitchCase', payload })), + replaceId: vi.fn((payload) => ({ type: 'workflow/replaceId', payload })), setFocusNode: vi.fn((payload) => ({ type: 'workflow/setFocusNode', payload })), toggleCollapsedGraphId: vi.fn((payload) => ({ type: 'workflow/toggleCollapsedGraphId', payload })), })); @@ -118,7 +123,24 @@ vi.mock('../../../core/actions/bjsworkflow/monitoring', () => ({ })); vi.mock('../../common/LoopsPager/helper', () => ({ - getScopeRepetitionName: vi.fn().mockReturnValue('000000'), + getAgentRepetitionIdentity: vi.fn((...args: any[]) => { + const first = args[0]; + const params = + typeof first === 'object' && first !== null + ? first + : { + runId: args[0], + ownerNodeId: args[1], + repetitionName: args[2], + repetitionIndex: args[3], + parentStatus: args[4], + }; + const { runId, ownerNodeId, repetitionName, repetitionIndex, parentStatus } = params; + return runId && ownerNodeId && repetitionName !== undefined && repetitionIndex !== undefined + ? [runId, ownerNodeId, repetitionName, String(repetitionIndex), parentStatus ?? ''].join('|') + : undefined; + }), + getScopeRepetitionName: vi.fn((index) => String(index).padStart(6, '0')), })); vi.mock('../../common/LoopsPager/SharedLoopsPager', () => ({ @@ -201,6 +223,8 @@ describe('SubgraphCardNode (v2)', () => { mockUseRunIndex.mockReturnValue(0); mockUseRunInstance.mockReturnValue(undefined); mockUseWorkflowNode.mockReturnValue({ id: 'graph1', children: [] }); + mockUseReplacedIds.mockReturnValue({}); + mockUseNodesMetadata.mockReturnValue({}); mockUseFlowErrorsForNode.mockReturnValue([]); mockUseBranchValidationCount.mockReturnValue(0); mockUseIconUri.mockReturnValue('test-icon-uri'); @@ -238,6 +262,14 @@ describe('SubgraphCardNode (v2)', () => { expect(mockDispatch).toHaveBeenCalledWith({ type: 'panel/changePanelNode', payload: 'testNode' }); }); + it('opts shared condition false branches into the neutral identity without changing legacy defaults', () => { + mockUseSharedNodeUi.mockReturnValue(true); + mockUseNodeMetadata.mockReturnValue({ graphId: 'graph1', subgraphType: SUBGRAPH_TYPES.CONDITIONAL_FALSE, actionCount: 0 }); + const { container } = render(); + expect(container.querySelector('[data-branch="false"]')).toBeInTheDocument(); + expect(container.querySelector('[data-branch="false"] [data-icon-name="DismissRegular"]')).toBeNull(); + }); + it('passes resolved MCP server art to the shared tool row untinted', () => { mockUseSharedNodeUi.mockReturnValue(true); mockUseActionMetadata.mockReturnValue({ type: 'McpClientTool', kind: 'Managed', runAfter: {} }); @@ -334,6 +366,85 @@ describe('SubgraphCardNode (v2)', () => { expect(container.querySelector('[data-node-count]')).toBeNull(); }); + it('renames a shared switch-case key through the edit glyph without touching case values', () => { + mockUseSharedNodeUi.mockReturnValue(true); + mockUseNodeMetadata.mockReturnValue({ graphId: 'graph1', subgraphType: SUBGRAPH_TYPES.SWITCH_CASE, actionCount: 2 }); + mockUseNodesMetadata.mockReturnValue({ ExistingCase: { graphId: 'graph1' } }); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Rename case' })); + const input = screen.getByRole('textbox', { name: 'Case name' }); + fireEvent.change(input, { target: { value: 'Renamed case key' } }); + fireEvent.keyDown(input, { key: 'Enter' }); + expect(mockDispatch).toHaveBeenCalledWith({ + type: 'workflow/replaceId', + payload: { originalId: 'testNode', newId: 'Renamed case key' }, + }); + }); + + it('shows validation feedback for invalid switch-case rename attempts and keeps the dialog open', () => { + mockUseSharedNodeUi.mockReturnValue(true); + mockUseNodeMetadata.mockReturnValue({ graphId: 'graph1', subgraphType: SUBGRAPH_TYPES.SWITCH_CASE, actionCount: 2 }); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Rename case' })); + const input = screen.getByRole('textbox', { name: 'Case name' }); + fireEvent.change(input, { target: { value: '' } }); + fireEvent.keyDown(input, { key: 'Enter' }); + expect(input).toHaveAttribute('aria-invalid', 'true'); + expect(screen.getByRole('dialog')).toBeInTheDocument(); + expect(mockDispatch).not.toHaveBeenCalledWith( + expect.objectContaining({ + type: 'workflow/replaceId', + }) + ); + }); + + it('closes the switch-case rename dialog when escape is pressed', () => { + mockUseSharedNodeUi.mockReturnValue(true); + mockUseNodeMetadata.mockReturnValue({ graphId: 'graph1', subgraphType: SUBGRAPH_TYPES.SWITCH_CASE, actionCount: 2 }); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Rename case' })); + const input = screen.getByRole('textbox', { name: 'Case name' }); + fireEvent.keyDown(input, { key: 'Escape' }); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + }); + + it('opens the host lane context menu from the switch-case more button', () => { + mockUseSharedNodeUi.mockReturnValue(true); + mockUseNodeMetadata.mockReturnValue({ graphId: 'graph1', subgraphType: SUBGRAPH_TYPES.SWITCH_CASE, actionCount: 2 }); + render(); + const more = screen.getByRole('button', { name: 'More case actions' }); + vi.spyOn(more, 'getBoundingClientRect').mockReturnValue({ + left: 100, + top: 40, + right: 132, + bottom: 64, + width: 32, + height: 24, + x: 100, + y: 40, + toJSON: () => ({}), + } as DOMRect); + fireEvent.click(more); + expect(mockDispatch).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'designerView/setNodeContextMenuData', + payload: { + nodeId: 'testNode', + entryPoint: 'shared-lane-more', + location: { x: 116, y: 64 }, + }, + }) + ); + }); + + it('does not render shared lane actions when shared mode is disabled', () => { + mockUseSharedNodeUi.mockReturnValue(false); + mockUseNodeMetadata.mockReturnValue({ graphId: 'graph1', subgraphType: SUBGRAPH_TYPES.SWITCH_CASE, actionCount: 2 }); + render(); + expect(screen.queryByRole('button', { name: 'Rename case' })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'More case actions' })).not.toBeInTheDocument(); + }); + it('should show collapsed text when graph is collapsed', () => { mockUseIsGraphCollapsed.mockReturnValue(true); render(); @@ -496,6 +607,49 @@ describe('SubgraphCardNode (v2)', () => { expect(screen.queryByTestId('loops-pager-testNode')).toBeNull(); }); + it('hides the shared tool pager while metadata belongs to a previous selected iteration', () => { + mockUseSharedNodeUi.mockReturnValue(true); + mockUseMonitoringView.mockReturnValue(true); + mockUseRunInstance.mockReturnValue({ id: 'run-1' }); + mockUseRunIndex.mockReturnValue(2); + mockUseParentNodeId.mockImplementation((id: string) => { + if (id === 'testNode') { + return 'parentAgent'; + } + if (id === 'parentAgent') { + return 'agent-parent'; + } + return undefined; + }); + mockUseRunData.mockImplementation((id: string) => { + if (id === 'agent-parent') { + return { status: 'Succeeded' }; + } + return undefined; + }); + mockUseActionMetadata.mockImplementation((id: string) => + id === 'parentAgent' ? { type: 'Agent', runAfter: {} } : { type: 'Scope', runAfter: {} } + ); + const staleMetadata = { + graphId: 'parentAgent', + subgraphType: SUBGRAPH_TYPES.AGENT_CONDITION, + actionCount: 1, + runData: { repetitionCount: 3 }, + agentRepetitionIdentity: 'run-1|parentAgent|000001|1|Succeeded', + }; + mockUseNodeMetadata.mockReturnValue(staleMetadata); + + const { rerender } = render(); + expect(screen.queryByTestId('shared-loops-pager-testNode')).toBeNull(); + + mockUseNodeMetadata.mockReturnValue({ + ...staleMetadata, + agentRepetitionIdentity: 'run-1|parentAgent|000002|2|Succeeded', + }); + rerender(); + expect(screen.getByTestId('shared-loops-pager-testNode')).toBeInTheDocument(); + }); + it('should not render SubgraphCard when no subgraphType in metadata', () => { mockUseNodeMetadata.mockReturnValue({ graphId: 'graph1', actionCount: 0 }); diff --git a/libs/designer-v2/src/lib/ui/CustomNodes/components/card/SharedActionCard.tsx b/libs/designer-v2/src/lib/ui/CustomNodes/components/card/SharedActionCard.tsx index 7128309d189..9c995a86ad6 100644 --- a/libs/designer-v2/src/lib/ui/CustomNodes/components/card/SharedActionCard.tsx +++ b/libs/designer-v2/src/lib/ui/CustomNodes/components/card/SharedActionCard.tsx @@ -51,6 +51,7 @@ export interface SharedActionCardProps extends ActionCardProps { operationKind?: string; metadataUnavailable?: boolean; description?: string; + onEditTestData?: () => void; isMonitoringView?: boolean; toolKind?: NodeToolKind; handleAxis?: 'vertical' | 'horizontal'; @@ -70,6 +71,7 @@ export const SharedActionCard = forwardRef {card} diff --git a/libs/designer-v2/src/lib/ui/CustomNodes/components/card/SharedFamilyCards.tsx b/libs/designer-v2/src/lib/ui/CustomNodes/components/card/SharedFamilyCards.tsx index 25a160456e1..919d598f899 100644 --- a/libs/designer-v2/src/lib/ui/CustomNodes/components/card/SharedFamilyCards.tsx +++ b/libs/designer-v2/src/lib/ui/CustomNodes/components/card/SharedFamilyCards.tsx @@ -6,9 +6,14 @@ import { LoopNodeCard, NodeInactiveContext, NodeBranchLabel, + NodeBranchActions, + NodeBranchShell, + NODE_BRANCH_ACTIONS_MAX_RESERVE_PX, NodeText, ToolItemCard, getCompactTitleLines, + useLoopBodyHoverClass, + type NodeBranchActionItem, type NodeIconTone, type NodeFrameCountLabel, } from '@microsoft/designer-ui-v2'; @@ -19,7 +24,9 @@ import { ChevronDownRegular, ChevronRightRegular, DismissRegular, + EditRegular, FlowRegular, + MoreHorizontalRegular, PlugConnectedRegular, } from '@fluentui/react-icons'; import { replaceWhiteSpaceWithUnderscore, SUBGRAPH_TYPES, type SubgraphType } from '@microsoft/logic-apps-shared'; @@ -39,7 +46,6 @@ import { mapSharedRunVisuals, mapToolNodeStrings, } from './nodeUiStrings'; -import { nodeMetrics } from '@microsoft/designer-ui-v2/metrics'; import { agentNodeTone, scopeNodeIcon } from './operationNodeGlyphs'; import { getNodePresentation, SHARED_SCOPE_TITLE_RESERVE, type NodePresentation } from '../../../../core/utils/graph'; import { SharedNodeHoverCard } from './SharedNodeHoverCard'; @@ -47,29 +53,11 @@ import { useOperationParameterByName } from '../../../../core/state/operation/op import { WORKFLOW_NODE_TYPES } from '@microsoft/logic-apps-shared'; const useStyles = makeStyles({ - // Plain branch labels are not shared NodeCards, so mirror the card's inactive dimming from shared metrics. - inactive: { opacity: nodeMetrics.inactiveOpacity }, pinned: { outline: `2px solid ${tokens.colorPalettePumpkinBorderActive}`, outlineOffset: '2px' }, collapse: { position: 'absolute', top: '4px', right: '4px', minWidth: 0 }, - branch: { - position: 'relative', - boxSizing: 'border-box', - display: 'grid', - gridTemplateColumns: 'minmax(0, 1fr)', - alignItems: 'center', - textAlign: 'center', - height: '100%', - paddingInline: tokens.spacingHorizontalXXL, - borderRadius: tokens.borderRadius2XLarge, - color: tokens.colorNeutralForeground1, - }, - trueBranch: { backgroundColor: tokens.colorStatusSuccessBackground1 }, - falseBranch: { backgroundColor: tokens.colorStatusDangerBackground1 }, - caseBranch: { backgroundColor: tokens.colorNeutralBackground3 }, - loopBranch: { backgroundColor: tokens.colorPaletteBlueBackground2 }, - branchSelected: { outline: `${tokens.strokeWidthThick} solid ${tokens.colorCompoundBrandStroke}`, outlineOffset: '-2px' }, branchLabel: { justifyContent: 'center', minWidth: 0 }, branchError: { top: '50%', right: 'auto', insetInlineStart: tokens.spacingHorizontalS, transform: 'translateY(-50%)' }, + collapseWithActions: { insetInlineEnd: `${NODE_BRANCH_ACTIONS_MAX_RESERVE_PX + 4}px` }, acceptedFrame: { width: '100%' }, pagerSlot: { display: 'inline-flex', height: '20px', alignItems: 'center' }, }); @@ -79,11 +67,13 @@ export const FamilyCollapseButton = ({ onCollapse, id, tabIndex, + className, }: { collapsed?: boolean; onCollapse?: (includeNested?: boolean) => void; id?: string; tabIndex?: number; + className?: string; }) => { const intl = useIntl(); const styles = useStyles(); @@ -97,7 +87,7 @@ export const FamilyCollapseButton = ({ return ( + ) : undefined + } /> ), - [category, icon, title, cardSubtitle, configured, description, strings] + [category, icon, title, cardSubtitle, configured, description, strings, testDataEnabled, onEditTestData, intl] ); return ( diff --git a/libs/designer-v2/src/lib/ui/CustomNodes/components/card/__test__/SharedFamilyCards.spec.tsx b/libs/designer-v2/src/lib/ui/CustomNodes/components/card/__test__/SharedFamilyCards.spec.tsx index 4e676a942d6..5ed07bbfcd9 100644 --- a/libs/designer-v2/src/lib/ui/CustomNodes/components/card/__test__/SharedFamilyCards.spec.tsx +++ b/libs/designer-v2/src/lib/ui/CustomNodes/components/card/__test__/SharedFamilyCards.spec.tsx @@ -7,6 +7,7 @@ import { compactNodeMetrics, nodeMetrics } from '@microsoft/designer-ui-v2/metri import { NodeInactiveContext } from '@microsoft/designer-ui-v2'; import type { ActionCardProps } from '../actionCard'; import { PreviewOperationCard } from '../../../../panel/multiSelectPanel/SharedExtractionPreviewNode'; +import * as Intl from 'react-intl'; const modelParameter = vi.hoisted(() => ({ current: undefined as { value: { value: string }[] } | undefined })); vi.mock('../../../../../core/state/operation/operationSelector', () => ({ useOperationParameterByName: () => modelParameter.current, @@ -69,6 +70,47 @@ describe('shared family interaction adapters', () => { rerender(); expect(within(header).queryByAltText('Errors')).not.toBeInTheDocument(); }); + + it('uses the neutral false branch glyph only when explicitly opted in', () => { + const defaultView = render( + + ); + expect(defaultView.container.querySelector('[data-branch="false"] [data-icon-name="DismissRegular"]')).not.toBeNull(); + defaultView.unmount(); + + const neutralView = render( + + ); + expect(neutralView.container.querySelector('[data-branch="false"] [data-icon-name="DismissRegular"]')).toBeNull(); + }); + + it('localizes shared If branch captions and the spoken taken outcome from host strings', () => { + const intl = Intl.createIntl({ + locale: 'fr', + defaultLocale: 'fr', + messages: { + Zwdunb: 'Vrai', + '/oWzBF': 'Faux', + '7smF3w': '{label}, branche prise', + }, + }); + const useIntlSpy = vi.spyOn(Intl, 'useIntl').mockReturnValue(intl); + try { + render(); + expect(screen.getByText('Vrai', { exact: true })).toBeVisible(); + expect(screen.getByText('Faux', { exact: true })).toBeVisible(); + expect(screen.getByText('Faux, branche prise')).toBeInTheDocument(); + } finally { + useIntlSpy.mockRestore(); + } + }); + it.each(['if', 'switch', 'loop', 'agent', 'scope'] as const)('keeps %s host status quiet and in the card name', (family) => { const { container } = render(); expect(screen.getByTestId('card-Renamed operation')).toHaveAccessibleName(/Succeeded/); @@ -344,6 +386,50 @@ describe('shared family interaction adapters', () => { expect(open).not.toHaveBeenCalled(); }); + it('renders switch-case rename and more actions without triggering the primary branch selection', () => { + const open = vi.fn(); + const rename = vi.fn(); + const more = vi.fn(); + const collapse = vi.fn(); + render( + + ); + fireEvent.click(screen.getByRole('button', { name: 'Rename case' })); + expect(rename).toHaveBeenCalledTimes(1); + expect(open).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button', { name: 'More case actions' })); + expect(more).toHaveBeenCalledTimes(1); + expect(more.mock.calls[0][0]).toBeInstanceOf(HTMLElement); + expect(open).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button', { name: 'Collapse' })); + expect(collapse).toHaveBeenCalledWith(false); + expect(more).toHaveBeenCalledTimes(1); + expect(open).not.toHaveBeenCalled(); + }); + + it('keeps default lanes protected from lane-header rename and overflow controls', () => { + render( + + ); + expect(screen.queryByRole('button', { name: 'Rename case' })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'More case actions' })).not.toBeInTheDocument(); + }); + it('keeps collapsed Agent tool counts without claiming ownership of absent cards and preserves real expand', () => { const input = props(); render( diff --git a/libs/designer-v2/src/lib/ui/CustomNodes/components/card/nodeUiStrings.ts b/libs/designer-v2/src/lib/ui/CustomNodes/components/card/nodeUiStrings.ts index 7c856d49a28..9c26ca640c5 100644 --- a/libs/designer-v2/src/lib/ui/CustomNodes/components/card/nodeUiStrings.ts +++ b/libs/designer-v2/src/lib/ui/CustomNodes/components/card/nodeUiStrings.ts @@ -137,6 +137,19 @@ export const mapConditionNodeStrings = (intl: IntlShape) => ({ if: intl.formatMessage({ defaultMessage: 'Condition', id: 'Zo2BOK', description: 'Conditional action title' }), switch: intl.formatMessage({ defaultMessage: 'Switch', id: 'JZQ6CL', description: 'Switch action title' }), }, + branch: { + true: intl.formatMessage({ defaultMessage: 'True', id: 'Zwdunb', description: 'True branch label' }), + false: intl.formatMessage({ defaultMessage: 'False', id: '/oWzBF', description: 'False branch label' }), + taken: (label: string) => + intl.formatMessage( + { + defaultMessage: '{label}, branch taken', + id: '7smF3w', + description: 'Announced phrase for the branch that ran in monitoring', + }, + { label } + ), + }, }); export const mapLoopNodeStrings = (intl: IntlShape, type?: string) => ({ diff --git a/libs/designer-v2/src/lib/ui/CustomNodes/components/handles/DefaultHandle.tsx b/libs/designer-v2/src/lib/ui/CustomNodes/components/handles/DefaultHandle.tsx index da9441bee15..91cfe758fe7 100644 --- a/libs/designer-v2/src/lib/ui/CustomNodes/components/handles/DefaultHandle.tsx +++ b/libs/designer-v2/src/lib/ui/CustomNodes/components/handles/DefaultHandle.tsx @@ -15,6 +15,7 @@ export const DefaultHandle = (props: { axis?: 'vertical' | 'horizontal'; /** Only read by the shared merge presentation; structural handles have no visible surface to dim. */ inactive?: boolean; + mergeAddSource?: string; }) => { const styles = useHandleStyles(); const shared = useHandlePresentation(); @@ -55,6 +56,7 @@ export const DefaultHandle = (props: { className={mergeClasses(styles.merge, horizontal && styles.mergeHorizontal)} label={props.label ?? ''} inactive={props.inactive} + data-merge-add-source={props.mergeAddSource} strings={{ label: (label) => intl.formatMessage( diff --git a/libs/designer-v2/src/lib/ui/CustomNodes/components/handles/handles.styles.ts b/libs/designer-v2/src/lib/ui/CustomNodes/components/handles/handles.styles.ts index 6a772faf498..fbcd3e9d1af 100644 --- a/libs/designer-v2/src/lib/ui/CustomNodes/components/handles/handles.styles.ts +++ b/libs/designer-v2/src/lib/ui/CustomNodes/components/handles/handles.styles.ts @@ -130,6 +130,7 @@ export const useHandleStyles = makeStyles({ bottom: `${-nodeMetrics.mergePoint.size / 2}px`, transform: 'translateX(-50%)', zIndex: 3, + '&[data-merge-add-source]': { pointerEvents: 'auto' }, }, mergeHorizontal: { left: 'auto', diff --git a/libs/designer-v2/src/lib/ui/CustomNodes/useLoopGroupHover.ts b/libs/designer-v2/src/lib/ui/CustomNodes/useLoopGroupHover.ts new file mode 100644 index 00000000000..3f259b7afe9 --- /dev/null +++ b/libs/designer-v2/src/lib/ui/CustomNodes/useLoopGroupHover.ts @@ -0,0 +1,61 @@ +import { useCallback, useEffect, useRef } from 'react'; +import type { PointerEvent } from 'react'; + +const groupBody = '[data-loop-group-body]'; +const groupHeader = '[data-loop-group-header]'; + +function findLoopGroup(root: HTMLElement, target: Element, x: number, y: number) { + const headerId = target.closest(groupHeader)?.getAttribute('data-loop-group-header'); + const groups = root.querySelectorAll(groupBody); + if (headerId !== undefined) { + return Array.from(groups).find((group) => group.dataset.loopGroupBody === headerId); + } + // React Flow renders children as siblings of the frame. Test the mounted frames in reverse graph + // order so a nested loop owns its own body; never add a hit target over the pane or its controls. + return Array.from(groups) + .reverse() + .find((group) => { + const { left, right, top, bottom } = group.getBoundingClientRect(); + return x >= left && x <= right && y >= top && y <= bottom; + }); +} + +export function useLoopGroupHover(enabled: boolean) { + const active = useRef([]); + const clear = useCallback(() => { + active.current.forEach((element) => element.removeAttribute('data-loop-active')); + active.current = []; + }, []); + useEffect(() => clear, [enabled, clear]); + const move = useCallback( + (event: PointerEvent) => { + const { currentTarget, target, clientX, clientY, buttons, pointerType } = event; + const ownerWindow = currentTarget.ownerDocument.defaultView; + if ( + buttons || + pointerType === 'touch' || + !ownerWindow || + !(target instanceof ownerWindow.Element) || + !currentTarget.contains(target) || + !target.closest('.react-flow__pane') + ) { + clear(); + return; + } + const body = findLoopGroup(currentTarget, target, clientX, clientY); + if (body && active.current[0] === body && active.current[1]?.isConnected) { + return; + } + clear(); + if (body) { + const header = Array.from(currentTarget.querySelectorAll(groupHeader)).find( + (element) => element.dataset.loopGroupHeader === body.dataset.loopGroupBody + ); + active.current = header ? [body, header] : [body]; + active.current.forEach((element) => element.setAttribute('data-loop-active', '')); + } + }, + [clear] + ); + return enabled ? { onPointerMoveCapture: move, onPointerLeave: clear, onPointerCancel: clear } : undefined; +} diff --git a/libs/designer-v2/src/lib/ui/Designer.tsx b/libs/designer-v2/src/lib/ui/Designer.tsx index cfe1896ab0b..2a2425e0edf 100644 --- a/libs/designer-v2/src/lib/ui/Designer.tsx +++ b/libs/designer-v2/src/lib/ui/Designer.tsx @@ -66,8 +66,10 @@ export const Designer = (props: DesignerProps) => { const isVSCode = useIsVSCode(); const readOnly = useReadOnly(); + const isMonitoringView = useMonitoringView(); const extractionOpen = useSelector((state: RootState) => !!state.designerView.workflowExtractionDialogOpen); const isReadOnly = readOnly || extractionOpen; + const canEdit = !isReadOnly && !isMonitoringView; const dispatch = useDispatch(); const isDarkMode = useIsDarkMode(); @@ -115,7 +117,7 @@ export const Designer = (props: DesignerProps) => { event.preventDefault(); dispatch(onUndoClick()); }, - { enabled: !isReadOnly && canUndo } + { enabled: canEdit && canUndo } ); useHotkeys( @@ -124,7 +126,7 @@ export const Designer = (props: DesignerProps) => { event.preventDefault(); dispatch(onRedoClick()); }, - { enabled: !isReadOnly && canRedo } + { enabled: canEdit && canRedo } ); const selectedNodeId = useOperationPanelSelectedNodeId(); @@ -143,7 +145,7 @@ export const Designer = (props: DesignerProps) => { dispatch(setShowDeleteModalNodeId(selectedNodeId)); } }, - { enabled: !isReadOnly } + { enabled: canEdit } ); // Ctrl/Cmd+D: duplicate the selected node(s) directly below themselves. @@ -156,7 +158,7 @@ export const Designer = (props: DesignerProps) => { dispatch(duplicateOperations({ nodeIds: idsToDuplicate })); } }, - { enabled: !isReadOnly } + { enabled: canEdit } ); // Ctrl/Cmd+C: copy selected node(s) to clipboard. @@ -184,7 +186,7 @@ export const Designer = (props: DesignerProps) => { dispatch(cutOperations({ nodeIds: [selectedNodeId] })); } }, - { enabled: !isReadOnly } + { enabled: canEdit } ); // Ctrl/Cmd+A: select all actions on the canvas. @@ -199,8 +201,6 @@ export const Designer = (props: DesignerProps) => { { enabled: !isReadOnly } ); - const isMonitoringView = useMonitoringView(); - const DND_OPTIONS: any = { backends: [ { diff --git a/libs/designer-v2/src/lib/ui/DesignerReactFlow.tsx b/libs/designer-v2/src/lib/ui/DesignerReactFlow.tsx index 567c4e61623..ca00a99176f 100644 --- a/libs/designer-v2/src/lib/ui/DesignerReactFlow.tsx +++ b/libs/designer-v2/src/lib/ui/DesignerReactFlow.tsx @@ -37,6 +37,8 @@ import { addOperationRunAfter, removeOperationRunAfter } from '../core/actions/b import { useClampPan, useIsA2AWorkflow } from '../core/state/designerView/designerViewSelectors'; import { DEFAULT_NODE_SIZE, getNodePresentation } from '../core/utils/graph'; import { DraftEdge } from './connections/draftEdge'; +import { useLoopGroupHover } from './CustomNodes/useLoopGroupHover'; +import { MergeHoverContext } from './connections/mergeHover'; import { useIsDarkMode, useReadOnly, useSharedNodeUi } from '../core/state/designerOptions/designerOptionsSelectors'; import { useLayout } from '../core/graphlayout'; import { DesignerFlowViewPadding } from '../core/utils/designerLayoutHelpers'; @@ -58,7 +60,7 @@ import HandoffEdge from './connections/handoffEdge'; import HiddenEdge from './connections/hiddenEdge'; import { OnlyEdge } from './connections/onlyEdge'; import { NodeNavigation } from './NodeNavigation'; -import { designerUiTokens } from '@microsoft/designer-ui-v2'; +import { designerUiTokens, useNodeOverviewStyles } from '@microsoft/designer-ui-v2'; import { DESIGNER_MIN_ZOOM, fitSharedDesignerViewport } from './designerViewport'; const DesignerReactFlow = (props: any) => { @@ -69,6 +71,8 @@ const DesignerReactFlow = (props: any) => { const isReadOnly = useReadOnly(); const sharedOption = useSharedNodeUi(); + const loopGroupHover = useLoopGroupHover(sharedOption); + const [hoveredMerge, setHoveredMerge] = useState(); const isEmpty = useIsGraphEmpty(); type NodeTypesObj = Record>; @@ -674,66 +678,97 @@ const DesignerReactFlow = (props: any) => { ); const isDarkMode = useIsDarkMode(); + const overviewStyles = useNodeOverviewStyles(); + // Switch only paint at overview zoom. Keeping node dimensions fixed preserves the fitted viewport and port positions. + const overview = sharedOption && zoom < 0.5; return ( - share one canvas role so the pane never shows two tones; - // outside DesignerUiScope the role falls back to Background1. - style={sharedOption ? { backgroundColor: designerUiTokens.canvasBackground } : undefined} - ref={canvasRef} - onInit={onInit} - nodeTypes={nodeTypes} - nodes={allNodes} - edges={edges} - onNodesChange={onNodesChange} - nodesConnectable={true} - nodesDraggable={false} - nodesFocusable={false} - edgesFocusable={false} - edgeTypes={edgeTypes} - elementsSelectable={true} - selectionOnDrag={isSelectionKeyHeld} - selectionMode={SelectionMode.Full} - selectionKeyCode={null} - multiSelectionKeyCode={['Meta', 'Control', 'Shift']} - panOnDrag={!isSelectionKeyHeld} - onSelectionChange={onSelectionChange} - onSelectionStart={onSelectionStart} - onSelectionEnd={onSelectionEnd} - panOnScroll={true} - deleteKeyCode={null} - zoomActivationKeyCode={['Ctrl', 'Meta', 'Alt', 'Control']} - translateExtent={clampPan ? translateExtent : undefined} - onMove={(_e, viewport) => setZoom(viewport.zoom)} - connectionLineComponent={DraftEdge} - onConnectStart={onConnectStart} - onConnectEnd={onConnectEnd} - isValidConnection={isValidConnection} - connectionRadius={0} - minZoom={DESIGNER_MIN_ZOOM} - snapGrid={[20, 20]} - snapToGrid={true} - onPaneClick={onPaneClick} - onPaneContextMenu={onPaneContextMenu} - disableKeyboardA11y={true} - onlyRenderVisibleElements={!userInferredTabNavigation} - proOptions={{ - account: 'paid-sponsor', - hideAttribution: true, - }} - > - { - if (!userInferredTabNavigation) { - // Mount off-screen cards before dispatching the one-shot canvas focus request. - flushSync(() => setUserInferredTabNavigation(true)); - } + + share one canvas role so the pane never shows two tones; + // outside DesignerUiScope the role falls back to Background1. + style={sharedOption ? { backgroundColor: designerUiTokens.canvasBackground } : undefined} + ref={canvasRef} + {...loopGroupHover} + onPointerMoveCapture={ + sharedOption + ? (event) => { + loopGroupHover?.onPointerMoveCapture(event); + const ownerWindow = event.currentTarget.ownerDocument.defaultView; + const merge = + event.buttons === 0 && event.pointerType !== 'touch' && ownerWindow && event.target instanceof ownerWindow.Element + ? event.target.closest('[data-merge-add-source]') + : null; + setHoveredMerge( + merge && event.currentTarget.contains(merge) ? (merge.getAttribute('data-merge-add-source') ?? undefined) : undefined + ); + } + : undefined + } + onPointerLeave={() => { + loopGroupHover?.onPointerLeave(); + setHoveredMerge(undefined); + }} + onPointerCancel={() => { + loopGroupHover?.onPointerCancel(); + setHoveredMerge(undefined); + }} + onInit={onInit} + nodeTypes={nodeTypes} + nodes={allNodes} + edges={edges} + onNodesChange={onNodesChange} + nodesConnectable={true} + nodesDraggable={false} + nodesFocusable={false} + edgesFocusable={false} + edgeTypes={edgeTypes} + elementsSelectable={true} + selectionOnDrag={isSelectionKeyHeld} + selectionMode={SelectionMode.Full} + selectionKeyCode={null} + multiSelectionKeyCode={['Meta', 'Control', 'Shift']} + panOnDrag={!isSelectionKeyHeld} + onSelectionChange={onSelectionChange} + onSelectionStart={onSelectionStart} + onSelectionEnd={onSelectionEnd} + panOnScroll={true} + deleteKeyCode={null} + zoomActivationKeyCode={['Ctrl', 'Meta', 'Alt', 'Control']} + translateExtent={clampPan ? translateExtent : undefined} + onMove={(_e, viewport) => setZoom(viewport.zoom)} + connectionLineComponent={DraftEdge} + onConnectStart={onConnectStart} + onConnectEnd={onConnectEnd} + isValidConnection={isValidConnection} + connectionRadius={0} + minZoom={DESIGNER_MIN_ZOOM} + snapGrid={[20, 20]} + snapToGrid={true} + onPaneClick={onPaneClick} + onPaneContextMenu={onPaneContextMenu} + disableKeyboardA11y={true} + onlyRenderVisibleElements={!userInferredTabNavigation} + proOptions={{ + account: 'paid-sponsor', + hideAttribution: true, }} - /> - {props.children} - + > + { + if (!userInferredTabNavigation) { + // Mount off-screen cards before dispatching the one-shot canvas focus request. + flushSync(() => setUserInferredTabNavigation(true)); + } + }} + /> + {props.children} + + ); }; diff --git a/libs/designer-v2/src/lib/ui/__test__/Designer.spec.tsx b/libs/designer-v2/src/lib/ui/__test__/Designer.spec.tsx index f1b93bde6ee..50c028f1381 100644 --- a/libs/designer-v2/src/lib/ui/__test__/Designer.spec.tsx +++ b/libs/designer-v2/src/lib/ui/__test__/Designer.spec.tsx @@ -248,6 +248,16 @@ describe('Designer', () => { expect(redoRegistration).toBeDefined(); }); + it.each(['ctrl+d', 'ctrl+x', 'ctrl+z', 'ctrl+y'])('disables %s in monitoring even when the host omits readOnly', (key) => { + mockIsMonitoringView = true; + mockIsReadOnly = false; + mockCanUndo = true; + mockCanRedo = true; + render(); + + expect(hotkeysRegistrations.find((registration) => registration.keys.includes(key))?.options.enabled).toBe(false); + }); + it('should enable undo hotkey when canUndo is true and not readOnly', () => { mockCanUndo = true; mockIsReadOnly = false; diff --git a/libs/designer-v2/src/lib/ui/common/DeleteModal/DeleteModal.tsx b/libs/designer-v2/src/lib/ui/common/DeleteModal/DeleteModal.tsx index 4006aa7bb63..a1660053a64 100644 --- a/libs/designer-v2/src/lib/ui/common/DeleteModal/DeleteModal.tsx +++ b/libs/designer-v2/src/lib/ui/common/DeleteModal/DeleteModal.tsx @@ -3,15 +3,19 @@ import { useNodeMetadata, useNodeDisplayName, storeStateToUndoRedoHistory } from import { deleteOperation, deleteGraphNode } from '../../../core/actions/bjsworkflow/delete'; import { useShowDeleteModalNodeId } from '../../../core/state/designerView/designerViewSelectors'; import { setShowDeleteModalNodeId } from '../../../core/state/designerView/designerViewSlice'; +import { useMonitoringView, useReadOnly } from '../../../core/state/designerOptions/designerOptionsSelectors'; import { useActionMetadata, useWorkflowNode } from '../../../core/state/workflow/workflowSelectors'; import { deleteAgentTool, deleteSwitchCase } from '../../../core/state/workflow/workflowSlice'; import { DeleteNodeModal } from '@microsoft/designer-ui'; import { WORKFLOW_NODE_TYPES } from '@microsoft/logic-apps-shared'; -import { useCallback, useMemo } from 'react'; +import { useCallback, useEffect, useMemo } from 'react'; import { useDispatch } from 'react-redux'; const DeleteModal = () => { const dispatch = useDispatch(); + const readOnly = useReadOnly(); + const monitoring = useMonitoringView(); + const canDelete = !readOnly && !monitoring; const nodeId = useShowDeleteModalNodeId(); const nodeName = useNodeDisplayName(nodeId); @@ -24,8 +28,15 @@ const DeleteModal = () => { const onDismiss = useCallback(() => dispatch(setShowDeleteModalNodeId(undefined)), [dispatch]); + // Don't restore a pending authoring confirmation after a trip through a run view. + useEffect(() => { + if (!canDelete && nodeId) { + onDismiss(); + } + }, [canDelete, nodeId, onDismiss]); + const handleDelete = useCallback(() => { - if (!nodeId || !nodeData) { + if (!canDelete || !nodeId || !nodeData) { return; } const { type, subGraphLocation } = nodeData; @@ -68,7 +79,7 @@ const DeleteModal = () => { } onDismiss(); - }, [nodeData, dispatch, nodeId, isTrigger, graphId, onDismiss]); + }, [canDelete, nodeData, dispatch, nodeId, isTrigger, graphId, onDismiss]); return ( { nodeType={nodeData?.type} subgraphType={metadata?.subgraphType} operationType={operationMetadata?.type} - isOpen={!!nodeId} + isOpen={!!nodeId && canDelete} onDismiss={onDismiss} onConfirm={handleDelete} /> diff --git a/libs/designer-v2/src/lib/ui/common/DeleteModal/MultiSelectDeleteModal.tsx b/libs/designer-v2/src/lib/ui/common/DeleteModal/MultiSelectDeleteModal.tsx index a5548d03045..bc3a685f1ac 100644 --- a/libs/designer-v2/src/lib/ui/common/DeleteModal/MultiSelectDeleteModal.tsx +++ b/libs/designer-v2/src/lib/ui/common/DeleteModal/MultiSelectDeleteModal.tsx @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useEffect, useMemo } from 'react'; import { useDispatch } from 'react-redux'; import { useIntl } from 'react-intl'; import { @@ -21,6 +21,7 @@ import { useOperationPanelSelectedNodeIds } from '../../../core/state/panel/pane import { setNodeSelection } from '../../../core/state/panel/panelSlice'; import { useShowMultiSelectDeleteModal } from '../../../core/state/designerView/designerViewSelectors'; import { setShowMultiSelectDeleteModal } from '../../../core/state/designerView/designerViewSlice'; +import { useMonitoringView, useReadOnly } from '../../../core/state/designerOptions/designerOptionsSelectors'; import { deleteOperations } from '../../../core/actions/bjsworkflow/delete'; import { useMultiSelectDeleteModalStyles } from './MultiSelectDeleteModal.styles'; @@ -47,6 +48,9 @@ export const MultiSelectDeleteModal = (): JSX.Element | null => { const styles = useMultiSelectDeleteModalStyles(); const isOpen = useShowMultiSelectDeleteModal(); + const readOnly = useReadOnly(); + const monitoring = useMonitoringView(); + const canDelete = !readOnly && !monitoring; const selectedNodeIds = useOperationPanelSelectedNodeIds(); const intlText = useMemo( @@ -85,17 +89,26 @@ export const MultiSelectDeleteModal = (): JSX.Element | null => { const onClose = useMemo(() => () => dispatch(setShowMultiSelectDeleteModal(false)), [dispatch]); + useEffect(() => { + if (isOpen && !canDelete) { + onClose(); + } + }, [canDelete, isOpen, onClose]); + const onConfirm = useMemo( () => () => { + if (!canDelete) { + return; + } dispatch(setShowMultiSelectDeleteModal(false)); dispatch(storeStateToUndoRedoHistory({ type: deleteOperations.pending })); dispatch(deleteOperations({ nodeIds: selectedNodeIds })); dispatch(setNodeSelection([])); }, - [dispatch, selectedNodeIds] + [canDelete, dispatch, selectedNodeIds] ); - if (!isOpen) { + if (!isOpen || !canDelete) { return null; } diff --git a/libs/designer-v2/src/lib/ui/common/DeleteModal/__test__/monitoringDeletion.spec.tsx b/libs/designer-v2/src/lib/ui/common/DeleteModal/__test__/monitoringDeletion.spec.tsx new file mode 100644 index 00000000000..16304b5eef7 --- /dev/null +++ b/libs/designer-v2/src/lib/ui/common/DeleteModal/__test__/monitoringDeletion.spec.tsx @@ -0,0 +1,85 @@ +import { cleanup, render, screen } from '@testing-library/react'; +import { IntlProvider } from 'react-intl'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { DeleteMenuItem } from '../../../menuItems/deleteMenuItem'; +import DeleteModal from '../DeleteModal'; +import MultiSelectDeleteModal from '../MultiSelectDeleteModal'; + +const state = vi.hoisted(() => ({ monitoring: false, pendingNode: 'Compose' as string | undefined, bulkOpen: true, dispatch: vi.fn() })); + +vi.mock('react-redux', () => ({ useDispatch: () => state.dispatch })); +vi.mock('../../../../core', () => ({ + useNodeDisplayName: (id?: string) => id ?? '', + useNodeMetadata: () => ({ graphId: 'root' }), + storeStateToUndoRedoHistory: vi.fn(), +})); +vi.mock('../../../../core/actions/bjsworkflow/delete', () => ({ + deleteOperation: vi.fn(), + deleteGraphNode: vi.fn(), + deleteOperations: vi.fn(), +})); +vi.mock('../../../../core/state/designerOptions/designerOptionsSelectors', () => ({ + useReadOnly: () => false, + useMonitoringView: () => state.monitoring, +})); +vi.mock('../../../../core/state/designerView/designerViewSelectors', () => ({ + useShowDeleteModalNodeId: () => state.pendingNode, + useShowMultiSelectDeleteModal: () => state.bulkOpen, +})); +vi.mock('../../../../core/state/designerView/designerViewSlice', () => ({ + setShowDeleteModalNodeId: (nodeId?: string) => ({ type: 'view/deleteNode', payload: nodeId }), + setShowMultiSelectDeleteModal: (open: boolean) => ({ type: 'view/bulkDelete', payload: open }), +})); +vi.mock('../../../../core/state/workflow/workflowSelectors', () => ({ + useWorkflowNode: () => ({ type: 'operation' }), + useActionMetadata: () => ({ type: 'Compose' }), + useNodeDisplayName: (id: string) => id, +})); +vi.mock('../../../../core/state/operation/operationSelector', () => ({ useOperationVisuals: () => ({}) })); +vi.mock('../../../../core/state/panel/panelSelectors', () => ({ useOperationPanelSelectedNodeIds: () => ['Compose', 'Response'] })); +vi.mock('@microsoft/designer-ui', async (importOriginal) => ({ + ...(await importOriginal()), + DeleteNodeModal: ({ isOpen }: { isOpen: boolean }) => (isOpen ?
: null), +})); + +describe('monitoring deletion', () => { + beforeEach(() => { + state.monitoring = false; + state.pendingNode = 'Compose'; + state.bulkOpen = true; + state.dispatch.mockClear(); + }); + afterEach(cleanup); + + it.each([ + { Dialog: DeleteModal, name: 'Delete Compose', close: { type: 'view/deleteNode', payload: undefined } }, + { Dialog: MultiSelectDeleteModal, name: 'Delete workflow actions', close: { type: 'view/bulkDelete', payload: false } }, + ])('dismisses the pending "$name" confirmation when monitoring begins', ({ Dialog, name, close }) => { + const confirmation = ( + + + + ); + const { rerender } = render(confirmation); + expect(screen.getByRole('dialog', { name })).toBeVisible(); + + state.monitoring = true; + rerender( + + + + ); + expect(screen.queryByRole('dialog', { name })).toBeNull(); + expect(state.dispatch.mock.calls).toEqual([[close]]); + }); + + it('disables the node Delete menu item even when the host sets only monitoring', () => { + state.monitoring = true; + render( + + + + ); + expect(screen.getByRole('menuitem', { name: 'Delete' })).toHaveAttribute('aria-disabled', 'true'); + }); +}); diff --git a/libs/designer-v2/src/lib/ui/common/DesignerContextualMenu/DesignerContextualMenu.tsx b/libs/designer-v2/src/lib/ui/common/DesignerContextualMenu/DesignerContextualMenu.tsx index 78344e61de4..f008b77cd9c 100644 --- a/libs/designer-v2/src/lib/ui/common/DesignerContextualMenu/DesignerContextualMenu.tsx +++ b/libs/designer-v2/src/lib/ui/common/DesignerContextualMenu/DesignerContextualMenu.tsx @@ -12,7 +12,7 @@ import { Delete24Filled, Delete24Regular, } from '@fluentui/react-icons'; -import type { LogicAppsV2, TopLevelDropdownMenuItem } from '@microsoft/logic-apps-shared'; +import type { LogicAppsV2 } from '@microsoft/logic-apps-shared'; import { SUBGRAPH_TYPES, UiInteractionsService, @@ -65,6 +65,7 @@ import { useReactFlow } from '@xyflow/react'; import { getChildRunNameFromOutputs, getChildWorkflowIdFromInputs } from '../../panel/nodeDetailsPanel/childWorkflowHelpers'; import { useRawInputsOutputs } from '../../panel/nodeDetailsPanel/useRawInputsOutputs'; import { WorkflowExtractionAction } from '../../panel/multiSelectPanel/workflowExtraction'; +import { isWorkflowEditLocked } from '../../../core/state/designerOptions/workflowEditLock'; const BulkDeleteIcon = bundleIcon(Delete24Filled, Delete24Regular); const BulkCopyIcon = bundleIcon(Clipboard24Filled, Clipboard24Regular); @@ -73,6 +74,7 @@ const BulkCutIcon = bundleIcon(Cut24Filled, Cut24Regular); export const DesignerContextualMenu = () => { const menuData = useNodeContextMenuData(); const nodeId = useMemo(() => menuData?.nodeId ?? '', [menuData?.nodeId]); + const isSharedLaneMoreEntryPoint = menuData?.entryPoint === 'shared-lane-more'; const isNodeCollapsed = useIsActionCollapsed(nodeId); const title = useNodeDisplayName(nodeId); @@ -84,6 +86,7 @@ export const DesignerContextualMenu = () => { const intl = useIntl(); const rootState = useSelector((state: RootState) => state); + const editLocked = isWorkflowEditLocked(rootState.designerOptions); const alternateSelectedNodeId = useOperationAlternateSelectedNodeId(); const selectedNodeIds = useOperationPanelSelectedNodeIds(); @@ -183,12 +186,16 @@ export const DesignerContextualMenu = () => { } }, [dispatch, menuData?.location, screenToFlowPosition]); - const transformMenuItems = (items: TopLevelDropdownMenuItem[]): DropdownMenuCustomNode[] => { - return items.map((item) => ({ - priority: item?.priority, - renderCustomComponent: () => , - })); - }; + const hostNodeContextMenuOptions: DropdownMenuCustomNode[] = useMemo( + () => + isUiInteractionsServiceEnabled() + ? (UiInteractionsService().getNodeContextMenuItems?.({ graphId: metadata?.graphId, nodeId: nodeId }) ?? []).map((item) => ({ + priority: item?.priority, + renderCustomComponent: () => , + })) + : [], + [metadata?.graphId, nodeId] + ); const actionContextMenuOptions: DropdownMenuCustomNode[] = useMemo(() => { isNodeCollapsed; @@ -203,9 +210,7 @@ export const DesignerContextualMenu = () => { } return [ - ...(isUiInteractionsServiceEnabled() - ? transformMenuItems(UiInteractionsService().getNodeContextMenuItems?.({ graphId: metadata?.graphId, nodeId: nodeId }) ?? []) - : []), + ...hostNodeContextMenuOptions, { priority: NodeMenuPriorities.Delete, renderCustomComponent: () => ( @@ -262,6 +267,7 @@ export const DesignerContextualMenu = () => { showLogicAppRunClick, runAfterClick, runMode, + hostNodeContextMenuOptions, ]); const actionContextMenuItems: JSX.Element[] = actionContextMenuOptions @@ -270,13 +276,17 @@ export const DesignerContextualMenu = () => { const subgraphMenuItems: JSX.Element[] = useMemo( () => [ + ...(isSharedLaneMoreEntryPoint ? hostNodeContextMenuOptions : []) + .slice() + .sort((a, b) => (a?.priority ?? NodeMenuPriorities.Default) - (b?.priority ?? NodeMenuPriorities.Default)) + .map((option) => option.renderCustomComponent() as JSX.Element), ...(metadata?.subgraphType === SUBGRAPH_TYPES.SWITCH_CASE || metadata?.subgraphType === SUBGRAPH_TYPES.AGENT_CONDITION || metadata?.subgraphType === SUBGRAPH_TYPES.MCP_CLIENT ? [] : []), ], - [deleteClick, metadata?.subgraphType] + [deleteClick, metadata?.subgraphType, hostNodeContextMenuOptions, isSharedLaneMoreEntryPoint] ); const graphMenuItems: JSX.Element[] = useMemo( @@ -333,18 +343,30 @@ export const DesignerContextualMenu = () => { { count: selectedNodeIds.length } ); return [ - } onClick={bulkCutClick} data-automation-id={'msla-bulk-cut-menu-option'}> + } + disabled={editLocked} + onClick={bulkCutClick} + data-automation-id={'msla-bulk-cut-menu-option'} + > {cutText} , } onClick={bulkCopyClick} data-automation-id={'msla-bulk-copy-menu-option'}> {copyText} , setOpen(false)} />, - } onClick={bulkDeleteClick} data-automation-id={'msla-bulk-delete-menu-option'}> + } + disabled={editLocked} + onClick={bulkDeleteClick} + data-automation-id={'msla-bulk-delete-menu-option'} + > {deleteText} , ]; - }, [intl, selectedNodeIds.length, bulkDeleteClick, bulkCopyClick, bulkCutClick]); + }, [intl, selectedNodeIds.length, bulkDeleteClick, bulkCopyClick, bulkCutClick, editLocked]); const menuItems = useMemo(() => { // If no node id, show canvas menu items @@ -353,7 +375,7 @@ export const DesignerContextualMenu = () => { } // If the right-clicked node is part of a multi-selection, show bulk actions - if (isMultiSelect) { + if (isMultiSelect && !isSharedLaneMoreEntryPoint) { return bulkMenuItems; } @@ -377,6 +399,7 @@ export const DesignerContextualMenu = () => { nodeId, canvasMenuItems, isMultiSelect, + isSharedLaneMoreEntryPoint, bulkMenuItems, metadata?.subgraphType, isScopeNode, diff --git a/libs/designer-v2/src/lib/ui/common/DesignerContextualMenu/__test__/DesignerContextualMenu.spec.tsx b/libs/designer-v2/src/lib/ui/common/DesignerContextualMenu/__test__/DesignerContextualMenu.spec.tsx index 70042cdc93c..e47ea905f22 100644 --- a/libs/designer-v2/src/lib/ui/common/DesignerContextualMenu/__test__/DesignerContextualMenu.spec.tsx +++ b/libs/designer-v2/src/lib/ui/common/DesignerContextualMenu/__test__/DesignerContextualMenu.spec.tsx @@ -11,6 +11,7 @@ import * as operationInfoHook from '../../../../core/state/selectors/actionMetad import { RUN_AFTER_PANEL_TAB } from '../../../../ui/CustomNodes/constants'; const mocks = vi.hoisted(() => ({ + isMonitoringView: false, dispatch: vi.fn(), screenToFlowPosition: vi.fn(({ x, y }: { x: number; y: number }) => ({ x: x / 2, y: y / 2 })), getRecordEntry: vi.fn(() => ({})), @@ -31,7 +32,7 @@ const mocks = vi.hoisted(() => ({ vi.mock('react-redux', () => ({ useDispatch: () => mocks.dispatch, - useSelector: (selector: any) => selector({ workflow: { operations: {} } }), + useSelector: (selector: any) => selector({ workflow: { operations: {} }, designerOptions: { isMonitoringView: mocks.isMonitoringView } }), })); vi.mock('@xyflow/react', () => ({ @@ -231,6 +232,7 @@ describe('DesignerContextualMenu', () => { beforeEach(() => { vi.useFakeTimers(); vi.clearAllMocks(); + mocks.isMonitoringView = false; mocks.rawInputsOutputs = { data: { inputs: {}, outputs: {} } }; vi.spyOn(designerViewSelectors, 'useNodeContextMenuData').mockReturnValue({ @@ -400,6 +402,16 @@ describe('DesignerContextualMenu', () => { expect(tree.root.findByProps({ 'data-testid': 'card-context-menu' }).props['data-open']).toBe(false); }); + it('does not offer active bulk edit commands while inspecting a run', () => { + mocks.isMonitoringView = true; + vi.spyOn(panelSelectors, 'useOperationPanelSelectedNodeIds').mockReturnValue(['test-node', 'second-node']); + const tree = renderMenu(); + + expect(tree.root.findByProps({ 'data-automation-id': 'msla-bulk-cut-menu-option' }).props.disabled).toBe(true); + expect(tree.root.findByProps({ 'data-automation-id': 'msla-bulk-delete-menu-option' }).props.disabled).toBe(true); + expect(tree.root.findByProps({ 'data-automation-id': 'msla-bulk-copy-menu-option' }).props.disabled).toBeFalsy(); + }); + it('does not show bulk extraction when the clicked node is outside the multi-selection', () => { vi.spyOn(panelSelectors, 'useOperationPanelSelectedNodeIds').mockReturnValue(['first-node', 'second-node']); @@ -409,6 +421,42 @@ describe('DesignerContextualMenu', () => { expect(tree.root.findAllByProps({ 'data-testid': 'copy-menu-item' })).toHaveLength(1); }); + it('keeps legacy switch-case right-click menus free of host lane commands', () => { + mocks.isUiInteractionsServiceEnabled.mockReturnValue(true); + mocks.getNodeContextMenuItems.mockReturnValue([{ priority: 50, text: 'Host command' }]); + vi.spyOn(workflowSelectors, 'useNodeMetadata').mockReturnValue({ + graphId: 'graph-a', + subgraphType: SUBGRAPH_TYPES.SWITCH_CASE, + } as any); + + const tree = renderMenu(); + + expect(tree.root.findAllByProps({ 'data-testid': 'custom-menu-item' })).toHaveLength(0); + expect(tree.root.findAllByProps({ 'data-testid': 'delete-menu-item' })).toHaveLength(1); + }); + + it('shows host lane commands from shared lane-more entrypoint and bypasses multi-select bulk menus', () => { + mocks.isUiInteractionsServiceEnabled.mockReturnValue(true); + mocks.getNodeContextMenuItems.mockReturnValue([{ priority: 50, text: 'Host command' }]); + vi.spyOn(designerViewSelectors, 'useNodeContextMenuData').mockReturnValue({ + nodeId: 'test-node', + entryPoint: 'shared-lane-more', + location: { x: 100, y: 80 }, + }); + vi.spyOn(workflowSelectors, 'useNodeMetadata').mockReturnValue({ + graphId: 'graph-a', + subgraphType: SUBGRAPH_TYPES.SWITCH_CASE, + } as any); + vi.spyOn(panelSelectors, 'useOperationPanelSelectedNodeIds').mockReturnValue(['test-node', 'second-node']); + + const tree = renderMenu(); + + expect(tree.root.findByProps({ 'data-testid': 'custom-menu-item' }).children).toEqual(['Host command']); + expect(tree.root.findAllByProps({ 'data-automation-id': 'msla-bulk-copy-menu-option' })).toHaveLength(0); + expect(tree.root.findAllByProps({ 'data-testid': 'workflow-extraction-action' })).toHaveLength(0); + expect(tree.root.findAllByProps({ 'data-testid': 'delete-menu-item' })).toHaveLength(1); + }); + it('shows delete and graph commands for a switch-case subgraph', () => { vi.spyOn(workflowSelectors, 'useNodeMetadata').mockReturnValue({ subgraphType: SUBGRAPH_TYPES.SWITCH_CASE, diff --git a/libs/designer-v2/src/lib/ui/common/EdgeContextualMenu/EdgeContextualMenu.tsx b/libs/designer-v2/src/lib/ui/common/EdgeContextualMenu/EdgeContextualMenu.tsx index d842ace82b7..b01f262c3a6 100644 --- a/libs/designer-v2/src/lib/ui/common/EdgeContextualMenu/EdgeContextualMenu.tsx +++ b/libs/designer-v2/src/lib/ui/common/EdgeContextualMenu/EdgeContextualMenu.tsx @@ -569,7 +569,14 @@ export const EdgeContextualMenu = () => { <>
setOpen(data.open)} + onOpenChange={(event, data) => { + setOpen(data.open); + const returnId = menuData?.focusReturnElementId; + if (!data.open && returnId && 'key' in event && event.key === 'Escape') { + // Wait until Fluent releases the focus trap; the edge may have unmounted by then. + requestAnimationFrame(() => document.getElementById(returnId)?.focus({ preventScroll: true })); + } + }} trapFocus open={open} withArrow={true} diff --git a/libs/designer-v2/src/lib/ui/common/LoopsPager/helper.ts b/libs/designer-v2/src/lib/ui/common/LoopsPager/helper.ts index 50d73fd1ab2..5100f869227 100644 --- a/libs/designer-v2/src/lib/ui/common/LoopsPager/helper.ts +++ b/libs/designer-v2/src/lib/ui/common/LoopsPager/helper.ts @@ -3,39 +3,10 @@ import type { NodeOperation } from '../../../core/state/operation/operationMetad import type { NodesMetadata } from '../../../core/state/workflow/workflowInterfaces'; import type { RootState } from '../../../core/store'; import { getAllParentsForNode } from '../../../core/utils/graph'; -import { getRecordEntry, type LogicAppsV2 } from '@microsoft/logic-apps-shared'; +import { getRecordEntry } from '@microsoft/logic-apps-shared'; import { useSelector } from 'react-redux'; -/** - * Gets number of loops for loop nodes. - * @param {LogicAppsV2.WorkflowRunAction} action - Node run metadata. - * @returns {number | undefined} Number of loops if metadata has the property otherwise undefined. - */ -export const getLoopsCount = (action: LogicAppsV2.WorkflowRunAction): number | undefined => { - const { inputsLink, iterationCount, repetitionCount } = action || {}; - - // Until actions have an iterationCount property when using the 2016-10-01 or later API. - if (typeof iterationCount === 'number') { - return iterationCount; - } - - // Foreach actions have a foreachItemsCount property in its inputsLink's metadata object when using the 2016-06-01 or later API. - if (inputsLink) { - const { metadata } = inputsLink; - if (metadata) { - const { foreachItemsCount } = metadata; - if (typeof foreachItemsCount === 'number') { - return foreachItemsCount; - } - } - } - - if (typeof repetitionCount === 'number') { - return repetitionCount; - } - - return undefined; -}; +export { getLoopsCount } from '../../../core/utils/loopRepetitions'; /** * Gets repetition name for API call. @@ -73,6 +44,32 @@ export const getScopeRepetitionName = (index: number | undefined): string => { return String(index).padStart(6, '0'); }; +interface AgentRepetitionIdentityParams { + runId: string | undefined; + ownerNodeId: string | undefined; + repetitionName: string | undefined; + repetitionIndex: number | undefined; + parentStatus: string | undefined; +} + +/** + * Builds the authoritative identity used to scope agent monitoring data to a specific selected iteration. + * If the run identity is unavailable (legacy/synthetic paths), we intentionally skip scoping and keep + * existing behavior unchanged. + */ +export const getAgentRepetitionIdentity = ({ + runId, + ownerNodeId, + repetitionName, + repetitionIndex, + parentStatus, +}: AgentRepetitionIdentityParams): string | undefined => { + if (!runId || !ownerNodeId || repetitionName === undefined || repetitionIndex === undefined) { + return undefined; + } + return [runId, ownerNodeId, repetitionName, String(repetitionIndex), parentStatus ?? ''].join('|'); +}; + /** * Hook that computes the repetition name inside a selector. * Returns a string primitive, so useSelector's default === comparison diff --git a/libs/designer-v2/src/lib/ui/connections/__tests__/dropzone.spec.tsx b/libs/designer-v2/src/lib/ui/connections/__tests__/dropzone.spec.tsx index 4d0f2aa4b17..48936d982be 100644 --- a/libs/designer-v2/src/lib/ui/connections/__tests__/dropzone.spec.tsx +++ b/libs/designer-v2/src/lib/ui/connections/__tests__/dropzone.spec.tsx @@ -265,12 +265,8 @@ describe('shared insertion uses the real host menu and DnD boundary', () => { expect(container.querySelector('[data-edge-control]')).toBeNull(); }); - it.each([ - { boundary: 'read-only', readOnly: true, monitoring: false }, - { boundary: 'monitoring', readOnly: false, monitoring: true }, - ])('disables the real accepted horizontal terminal control on a $boundary canvas', ({ readOnly, monitoring }) => { - state.readOnly = readOnly; - state.monitoring = monitoring; + it('disables the real accepted horizontal terminal control on a read-only authoring canvas', () => { + state.readOnly = true; const { container } = render(); expect(container.querySelector('[data-line="dashedNeutral"] path')).toHaveAttribute('d', 'M0 10 H8'); expect(screen.getByRole('button')).toBeDisabled(); @@ -278,18 +274,42 @@ describe('shared insertion uses the real host menu and DnD boundary', () => { expect(state.dispatch).not.toHaveBeenCalled(); }); - it.each([ - { boundary: 'read-only', readOnly: true, monitoring: false }, - { boundary: 'monitoring', readOnly: false, monitoring: true }, - ])('disables the flagged mutation surface on a $boundary canvas and never dispatches', ({ readOnly, monitoring }) => { - state.readOnly = readOnly; - state.monitoring = monitoring; + it('omits the terminal control in Shared monitoring without changing Legacy', () => { + state.monitoring = true; + const { rerender } = render(); + expect(screen.queryByRole('button')).not.toBeInTheDocument(); + + rerender(); + expect(screen.getByRole('button')).toBeInTheDocument(); + }); + + it('disables the flagged mutation surface on a read-only canvas and never dispatches', () => { + state.readOnly = true; render(); expect(screen.getByRole('button')).toBeDisabled(); fireEvent.click(screen.getByRole('button')); expect(state.dispatch).not.toHaveBeenCalled(); }); + it('does not render a Shared terminal Add on a monitoring canvas', () => { + state.monitoring = true; + render(); + expect(screen.queryByRole('button')).not.toBeInTheDocument(); + expect(state.dispatch).not.toHaveBeenCalled(); + }); + + it.each([false, true])('keeps a Shared monitoring insertion hidden when edge hover is %s', (isRevealed) => { + state.monitoring = true; + const { container } = render(); + const control = container.querySelector('[data-edge-control="insertion"]')!; + fireEvent.mouseEnter(control); + expect(control).toHaveAttribute('data-revealed', 'false'); + const button = screen.getByRole('button'); + expect(button).toBeDisabled(); + fireEvent.click(button); + expect(state.dispatch).not.toHaveBeenCalled(); + }); + it('retains real A2A drop restrictions instead of replacing DnD with the shared button', () => { state.dragging = true; state.a2a = true; diff --git a/libs/designer-v2/src/lib/ui/connections/dropzone.tsx b/libs/designer-v2/src/lib/ui/connections/dropzone.tsx index 79b86bfc616..c846f87c545 100644 --- a/libs/designer-v2/src/lib/ui/connections/dropzone.tsx +++ b/libs/designer-v2/src/lib/ui/connections/dropzone.tsx @@ -1,5 +1,5 @@ /* eslint-disable react/display-name */ -import { memo, useCallback, useMemo, useRef, useState } from 'react'; +import { memo, useCallback, useContext, useMemo, useRef, useState } from 'react'; import { useDispatch } from 'react-redux'; import { useHotkeys } from 'react-hotkeys-hook'; import { useIntl } from 'react-intl'; @@ -35,6 +35,7 @@ import { AddFilled } from '@fluentui/react-icons'; import { terminalConnectionLength, useConnectionStyles } from './connections.styles'; import { mergeClasses, Tooltip } from '@fluentui/react-components'; import type { PositioningShorthand } from '@fluentui/react-components'; +import { MergeHoverContext } from './mergeHover'; // Side placement keeps the label off the vertical flow axis so it does not cover the upstream card. const sideTooltipPositioning: PositioningShorthand = { position: 'after', fallbackPositions: ['before', 'below', 'above'] }; @@ -48,10 +49,22 @@ export interface DropZoneProps { isRevealed?: boolean; sharedPresentation?: boolean; axis?: 'vertical' | 'horizontal'; + /** The canonical source-side Add; sibling controls on a fan-out must not also reveal. */ + followsMerge?: boolean; } export const DropZone: React.FC = memo( - ({ graphId, parentId, childId, isLeaf = false, tabIndex = 0, isRevealed, sharedPresentation, axis = 'vertical' }) => { + ({ + graphId, + parentId, + childId, + isLeaf = false, + tabIndex = 0, + isRevealed, + sharedPresentation, + axis = 'vertical', + followsMerge = false, + }) => { const intl = useIntl(); const dispatch = useDispatch(); const isA2AWorkflow = useIsA2AWorkflow(); @@ -70,7 +83,9 @@ export const DropZone: React.FC = memo( const [hovered, setHovered] = useState(false); const [focused, setFocused] = useState(false); const terminal = isRevealed === undefined; - const revealed = terminal || isRevealed || hovered || focused; + const hoveredMerge = useContext(MergeHoverContext); + const activeFromMerge = shared && !locked && followsMerge && hoveredMerge !== undefined && hoveredMerge === parentId; + const revealed = terminal || (!locked && (isRevealed || hovered || focused || activeFromMerge)); const terminalControlSize = Math.max(nodeMetrics.actionAdd.buttonWidth, nodeMetrics.actionAdd.buttonHeight); const controlSize = terminal ? terminalControlSize : nodeMetrics.edgeControl.hitTargetSize; @@ -212,6 +227,9 @@ export const DropZone: React.FC = memo( } ); + const buttonId = normalizeAutomationId( + `msla-edge-button-${replaceWhiteSpaceWithUnderscore(parentName)}-${replaceWhiteSpaceWithUnderscore(childName) || 'undefined'}` + ); const openMenu = useCallback(() => { if (locked) { return; @@ -223,13 +241,14 @@ export const DropZone: React.FC = memo( parentId, childId, isLeaf, + ...(shared && { focusReturnElementId: buttonId }), location: { x: (rect?.left ?? 0) + (rect?.width ?? 0), y: (rect?.top ?? 0) + (rect?.height ?? 0) / 2, }, }) ); - }, [dispatch, graphId, parentId, childId, isLeaf, locked]); + }, [dispatch, graphId, parentId, childId, isLeaf, locked, shared, buttonId]); const actionButtonClick = useCallback( (e: React.MouseEvent) => { e.preventDefault(); @@ -239,10 +258,6 @@ export const DropZone: React.FC = memo( [openMenu] ); - const buttonId = normalizeAutomationId( - `msla-edge-button-${replaceWhiteSpaceWithUnderscore(parentName)}-${replaceWhiteSpaceWithUnderscore(childName) || 'undefined'}` - ); - const automationId = useCallback( (buttonName: string) => normalizeAutomationId( @@ -255,6 +270,10 @@ export const DropZone: React.FC = memo( const buttonRef = useRef(null); + if (shared && monitoring && terminal) { + return null; + } + return (
(hotkeyRef.current = node)}> {isDragging && !locked ? ( @@ -273,6 +292,7 @@ export const DropZone: React.FC = memo( className={styles.control} data-edge-control={terminal ? 'terminal' : 'insertion'} data-revealed={revealed} + data-active-from-merge={activeFromMerge || undefined} style={{ width: controlSize, height: controlSize }} onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)} @@ -300,6 +320,7 @@ export const DropZone: React.FC = memo( onClick={actionButtonClick} onContextMenu={actionButtonClick} disabled={locked} + active={activeFromMerge} onMouseDown={(event) => event.stopPropagation()} onKeyDown={(event) => { if (event.key === 'Enter' || event.key === ' ') { diff --git a/libs/designer-v2/src/lib/ui/connections/edge.tsx b/libs/designer-v2/src/lib/ui/connections/edge.tsx index c717d4f761e..c42d8eeb663 100644 --- a/libs/designer-v2/src/lib/ui/connections/edge.tsx +++ b/libs/designer-v2/src/lib/ui/connections/edge.tsx @@ -36,6 +36,7 @@ interface EdgeContentProps { tabIndex?: number; isRevealed?: boolean; sharedPresentation: boolean; + followsMerge?: boolean; controlProps?: HTMLAttributes; } @@ -61,6 +62,7 @@ const EdgeContent = (props: EdgeContentProps) => ( tabIndex={props.tabIndex} isRevealed={props.isRevealed} sharedPresentation={props.sharedPresentation} + followsMerge={props.followsMerge} />
@@ -249,6 +251,7 @@ const ButtonEdge: React.FC> = ({ : css('react-flow__edge-path', highlighted ? 'highlighted' : '') } data-line={shared ? variant : undefined} + data-line-highlighted={shared && highlighted ? '' : undefined} d={d} strokeDasharray={shared ? undefined : showRunAfter ? '4 6' : '0'} strokeWidth={shared ? undefined : 2} @@ -266,6 +269,7 @@ const ButtonEdge: React.FC> = ({ y={endpoint.y} direction={getSharedEdgeArrowDirection(targetPosition)} variant={variant} + highlighted={highlighted} style={{ ...style, stroke: stroke.stroke, @@ -298,6 +302,7 @@ const ButtonEdge: React.FC> = ({ tabIndex={tabIndex} isRevealed={hovered} sharedPresentation={shared} + followsMerge={!multipleTargets || showSourceButton} controlProps={shared ? activeState.wrapperProps : undefined} /> )} @@ -313,6 +318,7 @@ const ButtonEdge: React.FC> = ({ tabIndex={tabIndex} isRevealed={hovered} sharedPresentation={shared} + followsMerge={onlyEdge} controlProps={shared ? activeState.wrapperProps : undefined} /> )} diff --git a/libs/designer-v2/src/lib/ui/connections/mergeHover.ts b/libs/designer-v2/src/lib/ui/connections/mergeHover.ts new file mode 100644 index 00000000000..dc8dfbc9b3a --- /dev/null +++ b/libs/designer-v2/src/lib/ui/connections/mergeHover.ts @@ -0,0 +1,4 @@ +import { createContext } from 'react'; + +/** React Flow mounts the junction and its edge label in different DOM branches. Match by source node ID. */ +export const MergeHoverContext = createContext(undefined); diff --git a/libs/designer-v2/src/lib/ui/connections/sharedEdgeArrowCap.tsx b/libs/designer-v2/src/lib/ui/connections/sharedEdgeArrowCap.tsx index d5665187c33..375bb6741e2 100644 --- a/libs/designer-v2/src/lib/ui/connections/sharedEdgeArrowCap.tsx +++ b/libs/designer-v2/src/lib/ui/connections/sharedEdgeArrowCap.tsx @@ -67,6 +67,7 @@ export interface SharedEdgeArrowCapProps { direction: NodeLineArrowDirection; /** Line variant echoed as `data-line-cap` for probes; omitted for transient draft lines. */ variant?: string; + highlighted?: boolean; /** Chevron half-extent; defaults to the designer edge size, not the Otto library size. */ size?: number; className?: string; @@ -94,6 +95,7 @@ export const SharedEdgeArrowCap = ({ y, direction, variant, + highlighted, size = SHARED_EDGE_ARROW_SIZE, className, style, @@ -113,6 +115,7 @@ export const SharedEdgeArrowCap = ({ strokeLinecap="round" strokeLinejoin="round" data-line-cap={variant} + data-line-highlighted={highlighted ? '' : undefined} /> diff --git a/libs/designer-v2/src/lib/ui/menuItems/deleteMenuItem.tsx b/libs/designer-v2/src/lib/ui/menuItems/deleteMenuItem.tsx index c5233a6f6b2..5644632eb5a 100644 --- a/libs/designer-v2/src/lib/ui/menuItems/deleteMenuItem.tsx +++ b/libs/designer-v2/src/lib/ui/menuItems/deleteMenuItem.tsx @@ -1,4 +1,4 @@ -import { useReadOnly } from '../../core/state/designerOptions/designerOptionsSelectors'; +import { useMonitoringView, useReadOnly } from '../../core/state/designerOptions/designerOptionsSelectors'; import { MenuItem } from '@fluentui/react-components'; import { bundleIcon, Delete24Filled, Delete24Regular } from '@fluentui/react-icons'; import { useIntl } from 'react-intl'; @@ -17,6 +17,7 @@ export const DeleteMenuItem = (props: DeleteMenuItemProps) => { const intl = useIntl(); const readOnly = useReadOnly(); + const monitoring = useMonitoringView(); const deleteText = intl.formatMessage({ defaultMessage: 'Delete', @@ -30,7 +31,7 @@ export const DeleteMenuItem = (props: DeleteMenuItemProps) => { description: '"Delete" keyboard command text', }); - const isDisabled = readOnly; + const isDisabled = readOnly || monitoring; const menuItem = ( ; + return ( + + ); } if (family === 'agent') { return ; } + // Unknown scope families are ordinary actions in the editor; use its title sizing policy here too. return ( ); }; diff --git a/libs/designer-v2/src/lib/ui/panel/multiSelectPanel/__test__/SharedWorkflowExtractionPreview.spec.tsx b/libs/designer-v2/src/lib/ui/panel/multiSelectPanel/__test__/SharedWorkflowExtractionPreview.spec.tsx index dfd31616289..07d5872b1a4 100644 --- a/libs/designer-v2/src/lib/ui/panel/multiSelectPanel/__test__/SharedWorkflowExtractionPreview.spec.tsx +++ b/libs/designer-v2/src/lib/ui/panel/multiSelectPanel/__test__/SharedWorkflowExtractionPreview.spec.tsx @@ -1,4 +1,5 @@ import { fireEvent, render, screen } from '@testing-library/react'; +import { ActionNodeCard, LoopNodeCard, TriggerNodeCard } from '@microsoft/designer-ui-v2'; import { IntlProvider } from 'react-intl'; import { describe, expect, it, vi } from 'vitest'; import type { Workflow } from '../../../../common/models/workflow'; @@ -118,6 +119,44 @@ const renderCard = (data: SharedExtractionPreviewNode) => ); describe('preview presentation reuses the main metadata policy', () => { + it.each([ + { title: 'Build message', titleLines: 1 as const }, + { title: 'Build the localized notification message before publishing the latest design changes', titleLines: 2 as const }, + ])('matches Standard compact action geometry for $title', ({ title, titleLines }) => { + const { container } = render( + + + + + ); + const preview = container.querySelector('#preview-card'); + const editor = container.querySelector('#editor-card'); + expect(preview).toBeInTheDocument(); + expect(editor).toBeInTheDocument(); + expect(preview?.className).toBe(editor?.className); + expect(preview?.firstElementChild?.className).toBe(editor?.firstElementChild?.className); + const [previewTitle, editorTitle] = screen.getAllByText(title); + expect(previewTitle.className).toBe(editorTitle.className); + }); + + it.each([ + { type: 'Request', isTrigger: true, Card: TriggerNodeCard }, + { type: 'Foreach', isTrigger: false, Card: LoopNodeCard }, + ])('uses the compact editor title treatment for a wrapped $type preview', ({ type, isTrigger, Card }) => { + const title = 'Build the localized notification message before publishing the latest design changes'; + const { container } = render( + + + + + ); + const [previewTitle, editorTitle] = screen.getAllByText(title); + expect(previewTitle.className).toBe(editorTitle.className); + expect(container.querySelector('#preview-card')?.firstElementChild?.className).toBe( + container.querySelector('#editor-card')?.firstElementChild?.className + ); + }); + const renderConnectedCard = (data: SharedExtractionPreviewNode) => { const props: NodeProps = { id: data.id, diff --git a/libs/designer-v2/src/lib/ui/panel/multiSelectPanel/__test__/multiSelectPanel.spec.tsx b/libs/designer-v2/src/lib/ui/panel/multiSelectPanel/__test__/multiSelectPanel.spec.tsx index 290ec8ec171..5befc7aa4ab 100644 --- a/libs/designer-v2/src/lib/ui/panel/multiSelectPanel/__test__/multiSelectPanel.spec.tsx +++ b/libs/designer-v2/src/lib/ui/panel/multiSelectPanel/__test__/multiSelectPanel.spec.tsx @@ -7,9 +7,11 @@ const mockDispatch = vi.fn(); const mockToggleCollapse = vi.fn(); let mockSelectedNodeIds = ['first', 'second']; let mockCanWrap = true; +let mockMonitoring = false; vi.mock('react-redux', () => ({ useDispatch: () => mockDispatch, + useSelector: (selector: (state: unknown) => unknown) => selector({ designerOptions: { isMonitoringView: mockMonitoring } }), })); vi.mock('react-intl', () => ({ @@ -180,10 +182,21 @@ describe('MultiSelectPanel', () => { vi.clearAllMocks(); mockSelectedNodeIds = ['first', 'second']; mockCanWrap = true; + mockMonitoring = false; }); afterEach(cleanup); + it('keeps Copy but prevents cutting, grouping, and deleting a selection in monitoring', () => { + mockMonitoring = true; + renderPanel(); + + expect(screen.getByRole('button', { name: 'Cut' })).toBeDisabled(); + expect(screen.getByRole('button', { name: 'Delete' })).toBeDisabled(); + expect(screen.queryByRole('button', { name: 'Group' })).toBeNull(); + expect(screen.getByRole('button', { name: 'Copy' })).toBeEnabled(); + }); + it('renders selected actions, count, visuals, extraction action, and the requested panel side', () => { const { container } = renderPanel('Left'); diff --git a/libs/designer-v2/src/lib/ui/panel/multiSelectPanel/multiSelectPanel.tsx b/libs/designer-v2/src/lib/ui/panel/multiSelectPanel/multiSelectPanel.tsx index 3f103a442ef..4aef74a1ee5 100644 --- a/libs/designer-v2/src/lib/ui/panel/multiSelectPanel/multiSelectPanel.tsx +++ b/libs/designer-v2/src/lib/ui/panel/multiSelectPanel/multiSelectPanel.tsx @@ -1,12 +1,13 @@ import { useCallback, useMemo, useRef, useState } from 'react'; -import { useDispatch } from 'react-redux'; +import { useDispatch, useSelector } from 'react-redux'; import { useIntl } from 'react-intl'; import { Button, Menu, MenuButton, MenuItem, MenuList, MenuPopover, MenuTrigger, Tag, TagGroup, Tooltip } from '@fluentui/react-components'; import type { TagDismissData } from '@fluentui/react-components'; import { Copy24Regular, Cut24Regular, Delete24Regular, Group24Regular } from '@fluentui/react-icons'; import type { CommonPanelProps, PanelNodeData } from '@microsoft/designer-ui'; import { PanelContainer, PanelHeader, PanelLocation, PanelScope, PanelSize } from '@microsoft/designer-ui'; -import type { AppDispatch } from '../../../core'; +import type { AppDispatch, RootState } from '../../../core'; +import { isWorkflowEditLocked } from '../../../core/state/designerOptions/workflowEditLock'; import { useNodeDisplayName } from '../../../core/state/workflow/workflowSelectors'; import { useOperationVisuals } from '../../../core/state/operation/operationSelector'; import { useCanWrapSelectedNodes, useOperationPanelSelectedNodeIds } from '../../../core/state/panel/panelSelectors'; @@ -49,6 +50,7 @@ const MultiSelectPanelBody = ({ panelLocation, onClose }: MultiSelectPanelBodyPr const selectedNodeIds = useOperationPanelSelectedNodeIds(); const canWrap = useCanWrapSelectedNodes(); + const editLocked = useSelector((state: RootState) => isWorkflowEditLocked(state.designerOptions)); const copyButtonRef = useRef(null); const [showCopyCallout, setShowCopyCallout] = useState(false); @@ -217,13 +219,13 @@ const MultiSelectPanelBody = ({ panelLocation, onClose }: MultiSelectPanelBodyPr ))}
- - {canWrap ? ( + {editLocked ? null : canWrap ? ( }>{intlText.groupLabel} @@ -306,7 +308,7 @@ const MultiSelectPanelBody = ({ panelLocation, onClose }: MultiSelectPanelBodyPr )} -
diff --git a/libs/designer-v2/src/lib/ui/panel/runTreeView/TreeActionItem.tsx b/libs/designer-v2/src/lib/ui/panel/runTreeView/TreeActionItem.tsx index 5a2259ca0f0..da25df8838e 100644 --- a/libs/designer-v2/src/lib/ui/panel/runTreeView/TreeActionItem.tsx +++ b/libs/designer-v2/src/lib/ui/panel/runTreeView/TreeActionItem.tsx @@ -19,12 +19,15 @@ import { useNodeMetadata, useParentRunIndexes, useRunInstance, + useParentNodeId, + useToolRunIndex, } from '../../../core/state/workflow/workflowSelectors'; import { collapseGraphsToShowNode, clearAllRepetitionRunData, updateAgenticMetadata, setRunIndex, + setToolRunIndex, updateAgenticGraph, } from '../../../core/state/workflow/workflowSlice'; import { fetchBuiltInToolRunData } from '../../../core/actions/bjsworkflow/monitoring'; @@ -36,6 +39,9 @@ import StatusIndicator from './StatusIndicator'; import { ChatFilled, WrenchFilled, CodeFilled } from '@fluentui/react-icons'; import HandoffIcon from '../../../common/images/handoff_icon.svg'; import Markdown from 'react-markdown'; +import { useSharedNodeUi } from '../../../core/state/designerOptions/designerOptionsSelectors'; +import { useIsA2AWorkflow } from '../../../core/state/designerView/designerViewSelectors'; +import { getAgentRepetitionIdentity, getScopeRepetitionName } from '../../common/LoopsPager/helper'; export interface TreeActionItemProps { id: string; @@ -55,16 +61,35 @@ export const TreeActionItem = ({ id, content, icon, repetitionName, treeItemProp const selectedRun = useRunInstance() as LogicAppsV2.RunInstanceDefinition | undefined; const rawRunData = useRunData(id); + const shared = useSharedNodeUi(); + const isA2AWorkflow = useIsA2AWorkflow(); + const useScopedAgentData = shared && !isA2AWorkflow; const ref = useRef(null); const parentRunIndex = useParentRunIndex(id); const itemRunIndex = useMemo(() => data.repIndex ?? 0, [data.repIndex]); - const selectedRunIndexForItem = useRunIndex(id); - const subgraphType = useNodeMetadata(id)?.subgraphType; + const useToolPage = useScopedAgentData && subgraphType === SUBGRAPH_TYPES.MCP_CLIENT; + const runPage = useRunIndex(id); + const toolPage = useToolRunIndex(id); + const selectedRunIndexForItem = useToolPage ? toolPage : runPage; const isAgentRepetition = useMemo(() => data?.repetition?.type === 'workflows/runs/actions/agentRepetitions', [data?.repetition?.type]); + const agentOwnerId = isAgentRepetition ? id : data?.repetition?.properties?.repetitionIndexes?.[0]?.scopeName; + const agentParentId = useParentNodeId(agentOwnerId); + const agentParentStatus = useRunData(agentParentId ?? '')?.status; + const getSelectionIdentity = useCallback( + (index: number | undefined) => + getAgentRepetitionIdentity({ + runId: useScopedAgentData ? selectedRun?.id : undefined, + ownerNodeId: agentOwnerId, + repetitionName: getScopeRepetitionName(index), + repetitionIndex: index, + parentStatus: agentParentStatus, + }), + [agentOwnerId, agentParentStatus, selectedRun?.id, useScopedAgentData] + ); const selectedNodeId = useOperationPanelSelectedNodeId(); const selectedParentRunIndexes = useParentRunIndexes(selectedNodeId); @@ -74,7 +99,7 @@ export const TreeActionItem = ({ id, content, icon, repetitionName, treeItemProp return false; } if (itemRunIndex !== selectedRunIndexForItem) { - if (subgraphType === SUBGRAPH_TYPES.AGENT_CONDITION) { + if (subgraphType === SUBGRAPH_TYPES.AGENT_CONDITION || useToolPage) { return false; } if (isAgentRepetition) { @@ -97,6 +122,7 @@ export const TreeActionItem = ({ id, content, icon, repetitionName, treeItemProp selectedRunIndexForItem, subgraphType, isAgentRepetition, + useToolPage, ]); useEffect(() => { @@ -145,6 +171,7 @@ export const TreeActionItem = ({ id, content, icon, repetitionName, treeItemProp dispatch(clearAllRepetitionRunData()); const updatePayload = { nodeId: id, + agentRepetitionIdentity: getSelectionIdentity(itemRunIndex), scopeRepetitionRunData: { ...data?.repetition?.properties, agentRepetitionName: _repetitionName, @@ -167,10 +194,12 @@ export const TreeActionItem = ({ id, content, icon, repetitionName, treeItemProp // Only update parent if the parent repetition index has changed const repetitionIndex = data?.repetition?.properties?.repetitionIndexes?.[0]; const parentRepetition = data?.parentRepetition; - if (parentRunIndex !== Number(parentRepetition?.name)) { + const parentChanged = parentRunIndex !== Number(parentRepetition?.name); + if (parentChanged) { dispatch(clearAllRepetitionRunData()); const updatePayload = { nodeId: repetitionIndex?.scopeName ?? '', + agentRepetitionIdentity: getSelectionIdentity(repetitionIndex?.itemIndex), scopeRepetitionRunData: { ...parentRepetition?.properties, agentRepetitionName: String(repetitionIndex?.itemIndex).padStart(6, '0'), @@ -182,9 +211,9 @@ export const TreeActionItem = ({ id, content, icon, repetitionName, treeItemProp if (data?.repetition?.type === 'workflows/runs/actions/agentRepetitions/tools') { // Only update tool if the tool repetition index has changed - if (itemRunIndex !== selectedRunIndexForItem) { + if (itemRunIndex !== selectedRunIndexForItem || (useScopedAgentData && parentChanged)) { dispatch( - setRunIndex({ + (useToolPage ? setToolRunIndex : setRunIndex)({ nodeId: id, page: itemRunIndex ?? 0, }) @@ -217,7 +246,19 @@ export const TreeActionItem = ({ id, content, icon, repetitionName, treeItemProp dispatch(setRunIndex({ nodeId: element.scopeName, page: element.itemIndex })); }); }, - [itemRunIndex, parentRunIndex, selected, dispatch, data, selectedRunIndexForItem, isAgentRepetition, selectedRun] + [ + itemRunIndex, + parentRunIndex, + selected, + dispatch, + data, + selectedRunIndexForItem, + isAgentRepetition, + selectedRun, + getSelectionIdentity, + useScopedAgentData, + useToolPage, + ] ); const shortTime = useMemo(() => { diff --git a/libs/designer-v2/src/lib/ui/panel/runTreeView/__tests__/TreeActionItem.spec.tsx b/libs/designer-v2/src/lib/ui/panel/runTreeView/__tests__/TreeActionItem.spec.tsx index 23d8e8a3245..87315cd3729 100644 --- a/libs/designer-v2/src/lib/ui/panel/runTreeView/__tests__/TreeActionItem.spec.tsx +++ b/libs/designer-v2/src/lib/ui/panel/runTreeView/__tests__/TreeActionItem.spec.tsx @@ -8,6 +8,7 @@ import { TreeActionItem, type TreeActionItemProps } from '../TreeActionItem'; import { FlatTree } from '@fluentui/react-components'; import * as Core from '../../../../core'; import * as WorkflowSelectors from '../../../../core/state/workflow/workflowSelectors'; +import { setRunIndex, setToolRunIndex, updateAgenticMetadata } from '../../../../core/state/workflow/workflowSlice'; // Mock scrollIntoView which doesn't exist in JSDOM beforeAll(() => { @@ -34,30 +35,20 @@ vi.mock('../../../../core/state/workflow/workflowSelectors', async (importOrigin useRunIndex: vi.fn(), useNodeMetadata: vi.fn(), useParentRunIndexes: vi.fn(), - }; -}); - -vi.mock('../../../../core/state/workflow/workflowSlice', async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - collapseGraphsToShowNode: vi.fn(() => ({ type: 'COLLAPSE_GRAPHS', payload: undefined })), - clearAllRepetitionRunData: vi.fn(() => ({ type: 'CLEAR_REPETITION_DATA', payload: undefined })), - updateAgenticMetadata: vi.fn(() => ({ type: 'UPDATE_AGENTIC_METADATA', payload: undefined })), - setRunIndex: vi.fn(() => ({ type: 'SET_RUN_INDEX', payload: undefined })), - updateAgenticGraph: vi.fn(() => ({ type: 'UPDATE_AGENTIC_GRAPH', payload: undefined })), + useRunInstance: vi.fn(), }; }); describe('TreeActionItem', () => { let mockStore: EnhancedStore; - const createMockStore = () => { + const createMockStore = (useSharedNodeUi = false) => { return configureStore({ reducer: { operations: (state = {}) => state, workflow: (state = { nodesMetadata: {} }) => state, designerView: (state = {}) => state, + designerOptions: (state = { useSharedNodeUi }) => state, panel: (state = {}) => state, }, }); @@ -94,7 +85,10 @@ describe('TreeActionItem', () => { mockStore = createMockStore(); // Default mock implementations + (Core.changePanelNode as Mock).mockReturnValue({ type: 'CHANGE_PANEL_NODE' }); + (Core.setFocusNode as Mock).mockReturnValue({ type: 'SET_FOCUS_NODE' }); (Core.useOperationPanelSelectedNodeId as Mock).mockReturnValue(null); + vi.mocked(WorkflowSelectors.useRunInstance).mockReturnValue(undefined); (WorkflowSelectors.useRunData as Mock).mockReturnValue(null); (WorkflowSelectors.useParentRunIndex as Mock).mockReturnValue(0); (WorkflowSelectors.useRunIndex as Mock).mockReturnValue(0); @@ -338,6 +332,37 @@ describe('TreeActionItem', () => { }); describe('Agent Repetitions', () => { + it.each([true, false])('selects the MCP tool iteration under its owning Agent with Shared=%s', (shared) => { + mockStore = createMockStore(shared); + const dispatch = vi.spyOn(mockStore, 'dispatch'); + vi.mocked(WorkflowSelectors.useParentRunIndex).mockReturnValue(0); + vi.mocked(WorkflowSelectors.useRunInstance).mockReturnValue({ id: 'run-1' } as ReturnType); + (WorkflowSelectors.useNodeMetadata as Mock).mockReturnValue({ subgraphType: 'MCP_CLIENT' }); + renderWithProviders({ + ...defaultProps, + repetitionName: '000001-000002', + data: { + repIndex: 2, + repetition: { + type: 'workflows/runs/actions/agentRepetitions/tools', + properties: { repetitionIndexes: [{ scopeName: 'Agent', itemIndex: 1 }] }, + }, + parentRepetition: { name: '000001', properties: { status: 'Succeeded' } }, + }, + }); + + fireEvent.click(screen.getByText('Test Action')); + + expect(dispatch).toHaveBeenCalledWith( + expect.objectContaining({ + type: updateAgenticMetadata.type, + payload: expect.objectContaining({ nodeId: 'Agent', agentRepetitionIdentity: shared ? 'run-1|Agent|000001|1|' : undefined }), + }) + ); + expect(dispatch).toHaveBeenCalledWith((shared ? setToolRunIndex : setRunIndex)({ nodeId: 'test-action', page: 2 })); + expect(dispatch).toHaveBeenCalledWith(setRunIndex({ nodeId: 'Agent', page: 1 })); + }); + it('should handle agent repetition data', () => { const agentRepetitionProps = { ...defaultProps, From 223e73b780f76cc278f59afbc9a218e9f1461ae6 Mon Sep 17 00:00:00 2001 From: Krrish Mittal <11722204+takyyon@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:34:24 -0800 Subject: [PATCH 2/3] test(designer): verify node parity in both v2 renderers Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- Localize/lang/strings.json | 8 +- e2e/designer/nodeSearchPanel.spec.ts | 7 +- .../sharedNodeUiBranchCommands.spec.ts | 86 ++++++++ e2e/designer/sharedNodeUiCanvas.spec.ts | 12 +- e2e/designer/sharedNodeUiCommands.spec.ts | 81 +++++++ e2e/designer/sharedNodeUiConnections.spec.ts | 34 +++ e2e/designer/sharedNodeUiOverview.spec.ts | 114 ++++++++++ e2e/designer/sharedNodeUiRedesign.spec.ts | 56 ++++- .../sharedNodeUiRedesignMonitoring.spec.ts | 14 ++ .../sharedNodeUiSimulatedRuns.spec.ts | 204 +++++++++++++++++- 10 files changed, 593 insertions(+), 23 deletions(-) create mode 100644 e2e/designer/sharedNodeUiBranchCommands.spec.ts create mode 100644 e2e/designer/sharedNodeUiOverview.spec.ts diff --git a/Localize/lang/strings.json b/Localize/lang/strings.json index 1a6ade9f8a0..5096f73b099 100644 --- a/Localize/lang/strings.json +++ b/Localize/lang/strings.json @@ -850,6 +850,7 @@ "DYXoEM": "(UTC+02:00) Chisinau", "DYbiZw": "Fail operation when limits are reached", "DZZ3fj": "Duration", + "DZs1Ne": "More case actions", "DabKOm": "API keys", "DbxZhS": "Remove list of options", "DcJBUx": "Trigger type", @@ -1226,7 +1227,6 @@ "Ld62T8": "Delete", "LdITnG": "(UTC-03:00) Cayenne, Fortaleza", "LeR+TX": "Zoom in", - "Leu34C": "Rename case", "Lft/is": "Add new", "LgCmeY": "The specified path does not exist or is not accessible.", "LiRX1e": "Replacement", @@ -1525,7 +1525,6 @@ "QwAEWd": "Select a project", "QxEQwD": "Status", "QzjaQG": "Connection updated", - "R+8B9G": "More case actions", "R/aiRy": "(UTC+12:00) Coordinated Universal Time+12", "R0Skk9": "Confirm that you want to delete this artifact? You can't undo this action.", "R7UxBX": "Learn more", @@ -2878,6 +2877,7 @@ "_DYXoEM.comment": "Time zone value ", "_DYbiZw.comment": "Fail operation when limits are reached", "_DZZ3fj.comment": "Column header text for duration", + "_DZs1Ne.comment": "Accessible label for the switch-case overflow actions menu", "_DabKOm.comment": "Label for the API keys", "_DbxZhS.comment": "Remove the drop-down list of options for the text input dynamic parameter", "_DcJBUx.comment": "Type of the trigger in the template", @@ -3254,7 +3254,6 @@ "_Ld62T8.comment": "Button text for deleting selected workflows", "_LdITnG.comment": "Time zone value ", "_LeR+TX.comment": "Aria label for a button that zooms in on the workflow", - "_Leu34C.comment": "Accessible label for the switch-case rename action", "_Lft/is.comment": "Button to add a new connection", "_LgCmeY.comment": "Specified path does not exist or is not accessible message text", "_LiRX1e.comment": "Extraction replacement expression column", @@ -3553,7 +3552,6 @@ "_QwAEWd.comment": "Select the project to use for this connection", "_QxEQwD.comment": "Status filter label", "_QzjaQG.comment": "Notification title for successful connection update", - "_R+8B9G.comment": "Accessible label for the switch-case overflow actions menu", "_R/aiRy.comment": "Time zone value ", "_R0Skk9.comment": "Content for the delete artifact", "_R7UxBX.comment": "Link text for learning more about knowledge base group", @@ -4552,6 +4550,7 @@ "_izUiSp.comment": "Parameters button", "_j/Pssm.comment": "Label for description of custom formatTimeSpan Function", "_j1FtOw.comment": "Aria label for add new tag", + "_j2TDoU.comment": "Accessible label for the switch-case rename action", "_j2v8BE.comment": "Text to show no connections present in the template.", "_j4OKkU.comment": "label to set text color", "_j5z8Vd.comment": "Label for array connection", @@ -5991,6 +5990,7 @@ "izUiSp": "Parameters", "j/Pssm": "Formats a timespan value according to the specified format string and optional culture.", "j1FtOw": "Add new tag", + "j2TDoU": "Rename case", "j2v8BE": "No connections are needed in this template", "j4OKkU": "Text color", "j5z8Vd": "Repeating", diff --git a/e2e/designer/nodeSearchPanel.spec.ts b/e2e/designer/nodeSearchPanel.spec.ts index 17957e33a5e..e8b122c43e5 100644 --- a/e2e/designer/nodeSearchPanel.spec.ts +++ b/e2e/designer/nodeSearchPanel.spec.ts @@ -16,8 +16,11 @@ test.describe( expect(await page.getByText('Terminate', { exact: true }).isVisible()).toBeTruthy(); // Open node search panel and select action - await page.getByLabel('Search workflow actions').click(); - await page.getByTestId('msla-op-search-result-verify_property_changes').click(); + await page.getByRole('button', { name: 'Search workflow actions', exact: true }).click(); + const search = page.getByRole('dialog', { name: 'Go to operation', exact: true }); + await search.getByPlaceholder('Search for operation', { exact: true }).fill('Verify property changes'); + await search.getByText('Verify property changes', { exact: true }).click(); + await expect(search).toBeHidden(); // node panel tab is open with terminate action expect(await page.getByText('Terminate', { exact: true }).isVisible()).toBeTruthy(); diff --git a/e2e/designer/sharedNodeUiBranchCommands.spec.ts b/e2e/designer/sharedNodeUiBranchCommands.spec.ts new file mode 100644 index 00000000000..ac4bf450aa6 --- /dev/null +++ b/e2e/designer/sharedNodeUiBranchCommands.spec.ts @@ -0,0 +1,86 @@ +import { expect, test, type Page } from '@playwright/test'; +import { getSerializedWorkflowFromStateV2 } from './utils/designerFunctions'; +import { openSharedWorkflow } from './utils/sharedNodeUi'; + +async function readMenuItems(page: Page) { + return await page + .locator('[role="menuitem"]') + .allInnerTexts() + .then((items) => items.map((item) => item.trim()).filter(Boolean)); +} + +test.describe('Shared node UI branch lane commands', { tag: ['@mock', '@shared-node-ui'] }, () => { + test('renames the switch-case key from the edit glyph without mutating case value or branch actions', async ({ page }) => { + await openSharedWorkflow(page, 'Switch', 'true'); + const before = await getSerializedWorkflowFromStateV2(page); + const beforeCases = before.definition.actions.Switch.cases; + const caseIds = Object.keys(beforeCases); + const firstCaseId = caseIds[0]; + expect(firstCaseId).toBeTruthy(); + + const caseCard = page.locator(`[id="msla-node-${firstCaseId}"]`); + await expect(caseCard).toBeVisible(); + await caseCard.getByRole('button', { name: 'Rename case', exact: true }).click(); + const renameDialog = page.getByRole('dialog', { name: 'Rename case', exact: true }); + await expect(renameDialog).toBeVisible(); + await renameDialog.getByRole('textbox', { name: 'Case name', exact: true }).fill('Renamed case lane'); + await renameDialog.getByRole('button', { name: 'Save', exact: true }).click(); + await expect(renameDialog).not.toBeVisible(); + + await expect + .poll(async () => Object.keys((await getSerializedWorkflowFromStateV2(page)).definition.actions.Switch.cases)) + .not.toContain(firstCaseId); + + const after = await getSerializedWorkflowFromStateV2(page); + const afterCases = after.definition.actions.Switch.cases; + const renamedCaseId = Object.keys(afterCases).find((id) => !beforeCases[id]); + if (!renamedCaseId) { + throw new Error('Switch-case rename did not produce a new case key.'); + } + expect(Object.keys(afterCases)).toHaveLength(caseIds.length); + expect(afterCases[renamedCaseId].case).toEqual(beforeCases[firstCaseId].case); + expect(afterCases[renamedCaseId].actions).toEqual(beforeCases[firstCaseId].actions); + expect(after.definition.actions.Switch.default).toEqual(before.definition.actions.Switch.default); + }); + + test('opens lane-header More actions for switch cases and keeps Default lane protected', async ({ page }, testInfo) => { + await openSharedWorkflow(page, 'Switch', 'true'); + const ids = { caseId: 'First_Case', defaultId: 'Switch-defaultCase' }; + const before = await getSerializedWorkflowFromStateV2(page); + const beforeCount = Object.keys(before.definition.actions.Switch.cases).length; + + const caseCard = page.locator(`[id="msla-node-${ids.caseId}"]`); + await caseCard.getByRole('button', { name: 'More case actions', exact: true }).click(); + await expect(page.getByRole('menuitem', { name: /^Delete\b/ })).toBeVisible(); + await testInfo.attach('switch-case-more-actions', { + body: JSON.stringify({ items: await readMenuItems(page) }), + contentType: 'application/json', + }); + await page.getByRole('menuitem', { name: /^Delete\b/ }).click(); + const deleteDialog = page.getByRole('dialog'); + await expect(deleteDialog).toBeVisible(); + await deleteDialog.getByRole('button', { name: 'Cancel', exact: true }).click(); + await expect(deleteDialog).not.toBeVisible(); + + await caseCard.getByRole('button', { name: 'More case actions', exact: true }).click(); + await page.getByRole('menuitem', { name: /^Delete\b/ }).click(); + await expect(deleteDialog).toBeVisible(); + await deleteDialog.getByRole('button', { name: /^Delete\b/ }).click(); + await expect(deleteDialog).not.toBeVisible(); + await expect + .poll(async () => Object.keys((await getSerializedWorkflowFromStateV2(page)).definition.actions.Switch.cases).length) + .toBe(beforeCount - 1); + + const defaultCard = page.locator(`[id="msla-node-${ids.defaultId}"]`); + await expect(defaultCard.getByRole('button', { name: 'Rename case', exact: true })).toHaveCount(0); + await expect(defaultCard.getByRole('button', { name: 'More case actions', exact: true })).toHaveCount(0); + }); + + test('hides shared lane-header branch commands when the shared flag is off', async ({ page }) => { + await openSharedWorkflow(page, 'Switch', 'false'); + const caseCard = page.locator('[id="msla-node-First_Case"]'); + await expect(caseCard).toBeVisible(); + await expect(caseCard.getByRole('button', { name: 'Rename case', exact: true })).toHaveCount(0); + await expect(caseCard.getByRole('button', { name: 'More case actions', exact: true })).toHaveCount(0); + }); +}); diff --git a/e2e/designer/sharedNodeUiCanvas.spec.ts b/e2e/designer/sharedNodeUiCanvas.spec.ts index d34d91d6c1a..41d444a94e6 100644 --- a/e2e/designer/sharedNodeUiCanvas.spec.ts +++ b/e2e/designer/sharedNodeUiCanvas.spec.ts @@ -50,6 +50,10 @@ for (const dark of [false, true]) { if (dark) { await setContextSetting(page, 'Dark Mode', true); } + // Changing layout can move Compose under a stationary mouse; don't compare its rest paint to its hover paint. + await page.mouse.move(0, 0); + const compose = page.locator('#msla-node-Compose'); + await expect(compose.and(page.locator(':hover'))).toHaveCount(0); const before = await getSerializedWorkflowFromStateV2(page); let previous = ''; await expect @@ -80,12 +84,12 @@ for (const dark of [false, true]) { expect(paint.backgroundOverFlow).toBe(paint.background1); } else { await setSharedNodeUi(page, true); - await expect(page.locator('#msla-node-Compose')).toHaveAttribute('data-node-card', 'action'); + await expect(compose).toHaveAttribute('data-node-card', 'action'); await setSharedNodeUi(page, false); - await expect(page.locator('#msla-node-Compose')).not.toHaveAttribute('data-node-card', 'action'); + await expect(compose).not.toHaveAttribute('data-node-card', 'action'); await waitForViewport(page); - const restored = await readPaint(page); - expect({ ...restored, pattern: undefined }).toEqual({ ...paint, pattern: undefined }); + await expect(compose.and(page.locator(':hover'))).toHaveCount(0); + await expect.poll(async () => ({ ...(await readPaint(page)), pattern: undefined })).toEqual({ ...paint, pattern: undefined }); } expect((await getSerializedWorkflowFromStateV2(page)).definition.actions).toEqual(before.definition.actions); } diff --git a/e2e/designer/sharedNodeUiCommands.spec.ts b/e2e/designer/sharedNodeUiCommands.spec.ts index 4e6eab085e5..129d4dd1578 100644 --- a/e2e/designer/sharedNodeUiCommands.spec.ts +++ b/e2e/designer/sharedNodeUiCommands.spec.ts @@ -15,6 +15,29 @@ async function readNodePosition(node: Locator) { for (const flag of ['true', 'false'] as const) { test.describe(`Shared node UI structural and canvas commands, flag ${flag}`, { tag: ['@mock', '@shared-node-ui'] }, () => { + test('opens the existing Testing tab from a supported Shared action hover card only', async ({ page }) => { + await openSharedWorkflow(page, 'Panel', flag); + await page.evaluate(() => { + const store = window.DesignerStoreV2; + const { connectorId, operationId } = store.getState().operations.operationInfo.HTTP; + store.dispatch({ + type: 'staticResults/addResultSchema', + payload: { id: `${connectorId}-${operationId}`, schema: { type: 'object', properties: {} } }, + }); + }); + const node = page.locator('#msla-node-HTTP'); + await node.hover(); + const edit = page.getByRole('button', { name: 'Edit test data', exact: true }); + if (flag === 'true') { + await edit.click(); + await expect(page.getByRole('tab', { name: 'Testing', exact: true })).toHaveAttribute('aria-selected', 'true'); + } else { + await node.click(); + await expect(page.getByRole('tab', { name: 'Testing', exact: true })).toBeVisible(); + await expect(edit).toHaveCount(0); + } + }); + test('keeps trigger and scope context commands on their actual graph identities', async ({ page }) => { await openSharedWorkflow(page, 'Scope', flag); const before = await getSerializedWorkflowFromStateV2(page); @@ -36,6 +59,19 @@ for (const flag of ['true', 'false'] as const) { await expect(page.locator('.react-flow__edgeupdater')).toHaveCount(0); }); + test('offers parallel insertion only on an existing edge', async ({ page }) => { + await openSharedWorkflow(page, 'Scope', flag); + const insertion = page.getByRole('button', { name: 'Insert a new step between manual and Initialize variable', exact: true }); + await insertion.click(); + await expect(page.getByRole('menuitem', { name: 'Add an action', exact: true })).toBeVisible(); + await expect(page.getByRole('menuitem', { name: 'Add a parallel branch', exact: true })).toBeVisible(); + await page.keyboard.press('Escape'); + + await page.getByRole('button', { name: 'Insert a new step after Response', exact: true }).click(); + await expect(page.getByRole('menuitem', { name: 'Add an action', exact: true })).toBeVisible(); + await expect(page.getByRole('menuitem', { name: 'Add a parallel branch', exact: true })).toHaveCount(0); + }); + test('preserves actual operation drag and drop with the original metadata and new run-after order', async ({ page }) => { await openSharedWorkflow(page, 'Panel', flag); const before = await getSerializedWorkflowFromStateV2(page); @@ -159,5 +195,50 @@ for (const flag of ['true', 'false'] as const) { await expect(page.getByRole('button', { name: 'Search workflow actions', exact: true })).toBeFocused(); expect((await getSerializedWorkflowFromStateV2(page)).definition).toEqual(definitionBefore.definition); }); + + test('selects the matching operation from node search and opens its details', async ({ page }) => { + await openSharedWorkflow(page, 'Conditionals (Complex)', flag); + await page.getByRole('button', { name: 'Search workflow actions', exact: true }).click(); + const search = page.getByRole('dialog', { name: 'Go to operation', exact: true }); + await search.getByPlaceholder('Search for operation', { exact: true }).fill('Verify property changes'); + await search.getByText('Verify property changes', { exact: true }).click(); + await expect(search).toBeHidden(); + await expect + .poll(() => page.evaluate(() => window.DesignerStoreV2.getState().panel.operationContent.selectedNodeIds)) + .toContain('Verify_property_changes'); + const settings = page.getByRole('tab', { name: /^Settings/ }); + await settings.click(); + await expect(settings).toHaveAttribute('aria-selected', 'true'); + }); + + test('keeps selected and pinned node tabs independent', async ({ page }) => { + await openSharedWorkflow(page, 'Panel', flag); + await page.locator('#msla-node-Initialize_ArrayVariable').click({ button: 'right' }); + await page.getByTestId('msla-pin-menu-option').click(); + await page.locator('#msla-node-Parse_JSON').click(); + + const pinned = page.locator('#msla-node-details-panel-Initialize_ArrayVariable'); + const selected = page.locator('#msla-node-details-panel-Parse_JSON'); + const about = pinned.getByRole('tab', { name: 'About', exact: true }); + const settings = selected.getByRole('tab', { name: /^Settings/ }); + if (await about.isVisible()) { + await about.click(); + } else { + await pinned.getByRole('tab', { name: /more tabs$/ }).click(); + await page.getByRole('menuitem', { name: 'About', exact: true }).click(); + } + if (await settings.isVisible()) { + await settings.click(); + } else { + await selected.getByRole('tab', { name: /more tabs$/ }).click(); + await page.getByRole('menuitem', { name: 'Settings', exact: true }).click(); + } + await expect(about).toHaveAttribute('aria-selected', 'true'); + await expect(settings).toHaveAttribute('aria-selected', 'true'); + const parameters = selected.getByRole('tab', { name: 'Parameters', exact: true }); + await parameters.click(); + await expect(about).toHaveAttribute('aria-selected', 'true'); + await expect(parameters).toHaveAttribute('aria-selected', 'true'); + }); }); } diff --git a/e2e/designer/sharedNodeUiConnections.spec.ts b/e2e/designer/sharedNodeUiConnections.spec.ts index ee9546fcef9..42aa5dbaf3e 100644 --- a/e2e/designer/sharedNodeUiConnections.spec.ts +++ b/e2e/designer/sharedNodeUiConnections.spec.ts @@ -60,6 +60,40 @@ for (const flag of ['true', 'false'] as const) { expect((await getSerializedWorkflowFromStateV2(page)).definition.actions).toEqual(before.definition.actions); }); + test('blocks node mutations in monitoring even when the host omits readOnly', async ({ page }) => { + await openSharedWorkflow(page, 'General Run After', flag); + const compose = page.locator('#msla-node-Compose'); + await compose.press('Enter'); + await compose.focus(); + const undo = page.getByRole('button', { name: 'Undo', exact: true }); + await page.keyboard.press('ControlOrMeta+d'); + await expect(undo).toBeEnabled(); + await page.evaluate(() => { + const store = window.DesignerStoreV2; + store.dispatch({ + type: 'designerOptions/initDesignerOptions', + payload: { ...store.getState().designerOptions, isMonitoringView: true, readOnly: false }, + }); + }); + const history = page.getByRole('heading', { name: 'Run history', exact: true }); + await expect(history).toBeVisible(); + await page.locator('.fui-DrawerHeaderNavigation button').click(); + await expect(history).toBeHidden(); + await expect(undo).toBeDisabled(); + await compose.press('Enter'); + await compose.focus(); + // Entering monitoring reloads the workflow from the host, discarding unsaved edits. + const before = (await getSerializedWorkflowFromStateV2(page)).definition.actions; + await page.keyboard.press('ControlOrMeta+c'); + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toContain('"nodeId":"Compose-copy"'); + await page.keyboard.press('ControlOrMeta+d'); + await page.keyboard.press('ControlOrMeta+z'); + await page.keyboard.press('ControlOrMeta+x'); + await page.keyboard.press('Delete'); + await expect(page.getByRole('dialog')).toHaveCount(0); + expect((await getSerializedWorkflowFromStateV2(page)).definition.actions).toEqual(before); + }); + test('cuts an actual multi-selection through its context menu without losing clipboard operations', async ({ page }) => { await openSharedWorkflow(page, 'General Run After', flag); const before = await getSerializedWorkflowFromStateV2(page); diff --git a/e2e/designer/sharedNodeUiOverview.spec.ts b/e2e/designer/sharedNodeUiOverview.spec.ts new file mode 100644 index 00000000000..c2dc5d64382 --- /dev/null +++ b/e2e/designer/sharedNodeUiOverview.spec.ts @@ -0,0 +1,114 @@ +import { expect, type Locator, type Page, test } from '@playwright/test'; +import { LoadRunFile } from './utils/GoToWorkflow'; +import { openSharedWorkflow, setContextSetting, waitForViewport } from './utils/sharedNodeUi'; + +const card = (page: Page, id: string) => page.locator(`[id="msla-node-${id}"]`); +const zoom = (page: Page) => + page.locator('.react-flow__viewport').evaluate((element) => new DOMMatrixReadOnly(getComputedStyle(element).transform).m11); + +async function contrast(foreground: Locator, background: Locator, property = 'color') { + const color = await foreground.evaluate((element, prop) => getComputedStyle(element).getPropertyValue(prop), property); + const surface = await background.evaluate((element) => getComputedStyle(element).backgroundColor); + function luminance(rgb: string) { + expect(rgb).toMatch(/^rgb\(\d+, \d+, \d+\)$/); + const [r, g, b] = rgb.match(/\d+/g)!.map((component) => { + const value = Number(component) / 255; + return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4; + }); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; + } + const values = [luminance(color), luminance(surface)].sort((a, b) => b - a); + return (values[0] + 0.05) / (values[1] + 0.05); +} + +for (const flag of ['false', 'true'] as const) { + test.describe(`Node overview and convergence, flag ${flag}`, { tag: ['@mock', '@shared-node-ui'] }, () => { + const shared = flag === 'true'; + + test('keeps run status visible at native fit and returns to detail without resizing the card', async ({ page }) => { + await page.setViewportSize({ width: 1600, height: 1000 }); + await openSharedWorkflow(page, 'Monitoring view conditional', flag); + await LoadRunFile(page, 'mixedStatus'); + const delay = card(page, 'Delay'); + const status = shared ? delay.getByText('Failed', { exact: true }) : delay.getByAltText('Failed', { exact: true }); + await expect(status).toBeVisible(); + await page.getByRole('button', { name: 'Zoom view to fit' }).click(); + await waitForViewport(page); + expect(await zoom(page)).toBeGreaterThanOrEqual(0.36); + expect(await zoom(page)).toBeLessThan(0.5); + const size = () => delay.evaluate((element) => [element.offsetWidth, element.offsetHeight]); + const fittedSize = await size(); + const title = delay.locator('[data-node-title]'); + if (shared) { + await expect(page.locator('[data-node-overview]')).toHaveCount(1); + await expect(title).toHaveCSS('font-size', '16px'); + await expect(delay.locator('[data-node-glyph]')).toHaveCSS('transform', 'matrix(1.2, 0, 0, 1.2, 0, 0)'); + } else { + await expect(page.locator('[data-node-overview]')).toHaveCount(0); + } + const zoomIn = page.getByRole('button', { name: 'Zoom in', exact: true }); + await zoomIn.click(); + await zoomIn.click(); + await expect.poll(() => zoom(page)).toBeGreaterThan(0.5); + await expect(page.locator('[data-node-overview]')).toHaveCount(0); + if (shared) { + await expect(page.locator('[data-node-card] [data-node-title]').first()).toHaveCSS('font-size', '14px'); + } + await page.getByRole('button', { name: 'Zoom view to fit' }).click(); + await waitForViewport(page); + expect(await size()).toEqual(fittedSize); + }); + + test('hovering the Switch join targets only its downstream insert without opening it', async ({ page }) => { + await openSharedWorkflow(page, 'Switch', flag); + const insert = page.getByRole('button', { name: /insert a new step between Switch and Initialize owner/i }); + if (!shared) { + await expect(page.locator('[data-merge-add-source]')).toHaveCount(0); + await expect(insert).toBeVisible(); + return; + } + const control = page.locator('[data-edge-control]').filter({ has: insert }); + await expect(control).toHaveAttribute('data-revealed', 'false'); + await page.getByRole('img', { name: 'Merge point for Switch', exact: true }).hover(); + await expect(control).toHaveAttribute('data-active-from-merge', 'true'); + await expect(page.locator('[data-active-from-merge]')).toHaveCount(1); + await expect(page.getByRole('menu')).toHaveCount(0); + await page.mouse.move(1, 1); + await expect(control).toHaveAttribute('data-revealed', 'false'); + }); + + for (const theme of ['light', 'dark'] as const) { + test(`${theme} failure keeps text and status legible, with distinct forced-color selection`, async ({ page }) => { + await openSharedWorkflow(page, 'Monitoring view conditional', flag); + if (theme === 'dark') { + await setContextSetting(page, 'Dark Mode', true); + } + await LoadRunFile(page, 'mixedStatus'); + const delay = card(page, 'Delay'); + const status = shared ? delay.getByText('Failed', { exact: true }) : delay.getByAltText('Failed', { exact: true }); + await expect(status).toBeVisible(); + const perimeter = delay.locator('[data-node-status-perimeter]'); + const surface = delay.locator('[data-node-surface]'); + if (shared) { + expect(await contrast(status, surface)).toBeGreaterThanOrEqual(4.5); + expect(await contrast(perimeter, surface, 'border-top-color')).toBeGreaterThanOrEqual(3); + } + await page.emulateMedia({ forcedColors: 'active', reducedMotion: 'reduce' }); + await expect(status).toBeVisible(); + await delay.click(); + if (shared) { + await expect(delay).toHaveAttribute('data-selected', 'true'); + await expect(perimeter).toHaveCSS('border-top-style', 'dashed'); + await expect(surface).toHaveCSS('border-top-style', 'solid'); + expect(await contrast(status, surface)).toBeGreaterThanOrEqual(4.5); + expect(await contrast(perimeter, surface, 'border-top-color')).toBeGreaterThanOrEqual(3); + await page.keyboard.press('Tab'); + await delay.focus(); + await expect(delay).toHaveCSS('outline-offset', '2px'); + } else { + await expect(perimeter).toHaveCount(0); + } + }); + } + }); +} diff --git a/e2e/designer/sharedNodeUiRedesign.spec.ts b/e2e/designer/sharedNodeUiRedesign.spec.ts index dd268430b6a..922e448bf99 100644 --- a/e2e/designer/sharedNodeUiRedesign.spec.ts +++ b/e2e/designer/sharedNodeUiRedesign.spec.ts @@ -70,15 +70,18 @@ for (const flag of ['false', 'true'] as const) { await expect(page.getByRole('menuitem', { name: 'Add a parallel branch', exact: true })).toBeVisible(); await page.keyboard.press('Escape'); await expect(addAction).not.toBeVisible(); - // Legacy parity: the edge menu is anchored to a detached point, so Escape lands focus on the - // upstream card and a single Tab returns to the same insert button. - await expect(page.locator('#msla-node-Init_all')).toBeFocused(); - await page.keyboard.press('Tab'); + if (!shared) { + await expect(page.locator('#msla-node-Init_all')).toBeFocused(); + await page.keyboard.press('Tab'); + } await expect(insert).toBeFocused(); await page.keyboard.press('Space'); await expect(addAction).toBeVisible(); await page.keyboard.press('Escape'); await expect(addAction).not.toBeVisible(); + if (shared) { + await expect(insert).toBeFocused(); + } }); test('pastes a copied action through the edge insert with unchanged workflow semantics', async ({ page }) => { @@ -171,6 +174,33 @@ for (const flag of ['false', 'true'] as const) { expect(overlaps(await boxOf(tooltip), await boxOf(page.locator('#msla-node-Init_all')))).toBe(false); expect(overlaps(await boxOf(tooltip), await boxOf(insert))).toBe(false); }); + + test('keeps the full authored title accessible after renaming an action', async ({ page }, testInfo) => { + await openSharedWorkflow(page, 'General Run After', flag); + const card = page.locator('#msla-node-Compose'); + const longTitle = 'Validate every line item before authorizing payment to the vendor'; + await card.press('Enter'); + const titleEditor = page.getByRole('textbox', { name: 'Card title', exact: true }); + await titleEditor.fill(longTitle); + await titleEditor.press('Tab'); + await expect(card).toHaveAccessibleName(new RegExp(longTitle)); + if (shared) { + const title = card.getByText(longTitle, { exact: true }); + await expect(title).toHaveCSS('-webkit-line-clamp', '3'); + expect(await card.evaluate((element) => element.offsetHeight)).toBe(68); + await page.locator('#msla-panel-header-close-nav').click(); + await tabTo(page, card); + const heading = page.getByRole('heading', { name: longTitle, exact: true }); + await expect(heading).toBeVisible(); + await expect(heading).toHaveCSS('white-space', 'normal'); + expect(await heading.evaluate(({ scrollHeight, clientHeight }) => scrollHeight - clientHeight)).toBe(0); + await testInfo.attach('keyboard-full-title', { body: await page.screenshot(), contentType: 'image/png' }); + await page.keyboard.press('Escape'); + await expect(heading).not.toBeVisible(); + } else { + await expect(card).not.toHaveAttribute('data-node-card'); + } + }); }); } @@ -188,6 +218,24 @@ test.describe('Shared redesign direction and hover affordances', { tag: ['@mock' expect(overlaps(card, await boxOf(compose))).toBe(false); }); + test('keeps a parallel card uncovered and lets the pointer enter the hover card', async ({ page }, testInfo) => { + await openSharedWorkflow(page, 'General Run After'); + const compose = page.locator('#msla-node-Compose'); + const navigation = page.locator('#msla-node-Execute_a_navigation_plan'); + const [composeBox, navigationBox] = await Promise.all([boxOf(compose), boxOf(navigation)]); + const [anchor, sibling] = composeBox.x < navigationBox.x ? [compose, navigation] : [navigation, compose]; + await anchor.hover(); + const info = page.locator('[data-node-info-card="action"]'); + await expect(info).toBeVisible(); + const [anchorBox, siblingBox] = await Promise.all([boxOf(anchor), boxOf(sibling)]); + await expect.poll(async () => overlaps(await boxOf(info), siblingBox) || overlaps(await boxOf(info), anchorBox)).toBe(false); + await testInfo.attach('parallel-hover-placement', { body: await page.screenshot(), contentType: 'image/png' }); + await info.getByRole('button', { name: 'Close', exact: true }).click(); + await expect(info).not.toBeVisible(); + await sibling.hover(); + await expect(info).toBeVisible(); + }); + test('gives editable source ports visible hover feedback without moving them', async ({ page }) => { await openSharedWorkflow(page, 'General Run After'); const port = page.locator('.react-flow__node[data-id="Init_all"] .react-flow__handle.source[data-port-interactive="true"]'); diff --git a/e2e/designer/sharedNodeUiRedesignMonitoring.spec.ts b/e2e/designer/sharedNodeUiRedesignMonitoring.spec.ts index 451d0093833..fa5e79b1921 100644 --- a/e2e/designer/sharedNodeUiRedesignMonitoring.spec.ts +++ b/e2e/designer/sharedNodeUiRedesignMonitoring.spec.ts @@ -48,6 +48,20 @@ async function toggleGraph(page: Page, cardId: string, flag: Flag) { for (const flag of ['true', 'false'] as const) { test.describe(`Standard node redesign, flag ${flag}`, { tag: ['@mock', '@shared-node-ui'] }, () => { + test('keeps the monitored definition read-only when Delete is pressed on a card', async ({ page }) => { + await openSharedWorkflow(page, 'Monitoring view conditional', flag); + await LoadRunFile(page, 'normalState'); + const delay = card(page, 'Delay'); + const action = delay.locator('[id="msla-node-Delay"]'); + const before = (await getSerializedWorkflowFromStateV2(page)).definition; + await action.focus(); + await expect(action).toBeFocused(); + await page.keyboard.press('Delete'); + await expect(page.getByRole('dialog').filter({ hasText: /Are you sure you want to delete/ })).toHaveCount(0); + await expect(action).toBeVisible(); + expect((await getSerializedWorkflowFromStateV2(page)).definition).toEqual(before); + }); + test('captures the conditional monitoring run at fit and measures its canvas zoom', async ({ page }, testInfo) => { await page.setViewportSize({ width: 1600, height: 1000 }); await openSharedWorkflow(page, 'Monitoring view conditional', flag); diff --git a/e2e/designer/sharedNodeUiSimulatedRuns.spec.ts b/e2e/designer/sharedNodeUiSimulatedRuns.spec.ts index 587c468b943..21bdc3abd3c 100644 --- a/e2e/designer/sharedNodeUiSimulatedRuns.spec.ts +++ b/e2e/designer/sharedNodeUiSimulatedRuns.spec.ts @@ -1,7 +1,7 @@ import { expect, test, type Locator, type Page } from '@playwright/test'; import type { AppStore } from '../../libs/designer-v2/src/lib/core/store'; import { getSerializedWorkflowFromStateV2 } from './utils/designerFunctions'; -import { openSharedWorkflow } from './utils/sharedNodeUi'; +import { openSharedWorkflow, setContextSetting } from './utils/sharedNodeUi'; type DesignerWindow = Window & { DesignerStoreV2: Pick }; const times = { startTime: '2026-01-01T00:00:00Z', endTime: '2026-01-01T00:00:01Z' }; @@ -30,6 +30,26 @@ const runIndex = (page: Page, id: string, tool = false) => { id, tool } ); +const measureForeach = (page: Page) => + page.evaluate(() => { + const graph = document.querySelector('.react-flow__node[data-id="Foreach"]')!; + const header = document.querySelector('.react-flow__node[data-id="Foreach-#scope"]')!; + const card = header.querySelector('#msla-node-Foreach')!; + const frame = graph.querySelector('.msla-graph-container-wrapper > [data-node-card="loop-frame"]'); + const edge = document.querySelector( + '.react-flow__edge[data-id^="Foreach-"] :is(.react-flow__edge-path, .msla-shared-edge-path)' + )!; + const zoom = new DOMMatrixReadOnly(getComputedStyle(graph.closest('.react-flow__viewport')!).transform).m11; + const top = graph.getBoundingClientRect().top; + return { + header: header.offsetHeight, + card: card.offsetHeight, + graph: graph.offsetHeight, + frameTop: frame ? Math.round((frame.getBoundingClientRect().top - top) / zoom) : undefined, + edgeStart: Math.round((edge.getPointAtLength(0).matrixTransform(edge.getScreenCTM()!).y - top) / zoom), + }; + }); + async function exerciseFourIterations(page: Page, pager: Locator, id: string, shared: boolean, tool = false) { const previous = pager.getByLabel(shared ? 'Previous iteration' : 'Previous', { exact: true }); const next = pager.getByLabel(shared ? 'Next iteration' : 'Next', { exact: true }); @@ -59,6 +79,19 @@ async function exerciseFourIterations(page: Page, pager: Locator, id: string, sh for (const flag of ['true', 'false'] as const) { test.describe(`Deterministic simulated run metadata, flag ${flag}`, { tag: ['@mock', '@shared-node-ui'] }, () => { + test('keeps the empty Foreach caption clear in dark monitoring', async ({ page }, testInfo) => { + await openSharedWorkflow(page, 'All Scope Nodes', flag); + await setContextSetting(page, 'Dark Mode', true); + const emptyLoop = page.locator('.react-flow__node[data-id="ForEach_empty"]'); + await expect(emptyLoop).toBeVisible(); + expect(await emptyLoop.locator('[data-loop-body-join]').count()).toBe(flag === 'true' ? 1 : 0); + await enterSimulatedMonitoring(page); + const header = page.locator('.react-flow__node[data-id="ForEach_empty-#scope"]'); + await expect(header.getByText('No actions', { exact: true })).toBeVisible(); + await expect(emptyLoop.locator('[data-loop-body-join]')).toHaveCount(0); + await testInfo.attach('dark-empty-foreach', { body: await page.screenshot(), contentType: 'image/png' }); + }); + test('pages actual outer and nested Foreach renderers without an observed backend run', async ({ page }, testInfo) => { await openSharedWorkflow(page, 'ForEach', flag); const before = await getSerializedWorkflowFromStateV2(page); @@ -88,18 +121,69 @@ for (const flag of ['true', 'false'] as const) { await exerciseFourIterations(page, pager, id, flag === 'true'); if (flag === 'true') { await expect(pager.locator('[data-node-pager]')).toHaveCount(1); + const outputPort = pager.locator('xpath=ancestor::div[@data-node-card="foreach"]').locator('.react-flow__handle.source'); + // Edge IDs encode the dash inside the source node ID before adding the endpoint separator. + const outgoing = page.locator(`.react-flow__edge[data-id^="${id}%2D#scope-"] .msla-shared-edge-path`).first(); + await expect + .poll(async () => { + const { y, height } = (await pager.boundingBox())!; + const port = (await outputPort.boundingBox())!; + const edgeStartY = await outgoing.evaluate( + (path: SVGPathElement) => path.getPointAtLength(0).matrixTransform(path.getScreenCTM()!).y + ); + return Math.min(port.y + port.height, edgeStartY) - (y + height); + }) + .toBeGreaterThanOrEqual(0); } } + const pager = page.getByTestId('msla-pager-v2-foreach'); + await pager.getByLabel(flag === 'true' ? 'Next iteration' : 'Next', { exact: true }).click(); + const body = page.locator('[data-loop-group-body="Foreach"]'); + const join = body.locator('[data-loop-body-join]'); if (flag === 'true') { - const pager = page.getByTestId('msla-pager-v2-foreach'); - await pager.getByLabel('Next iteration', { exact: true }).click(); - const collapse = page.locator('button[id="Foreach-collapse-toggle"]'); - await collapse.press('Enter'); - await expect(pager).toHaveCount(0); - await collapse.press('Enter'); - await expect(pager).toBeVisible(); - await expect.poll(() => runIndex(page, 'Foreach')).toBe(1); + await expect(join).toHaveAttribute('data-arrow', 'false'); + await expect(join).toHaveCSS('pointer-events', 'none'); + const header = page.locator('[data-loop-group-header="Foreach"]'); + const frame = body.locator('[data-node-card="loop-frame"]'); + await header.hover(); + await expect(header).toHaveAttribute('data-loop-active', ''); + await expect(body).toHaveAttribute('data-loop-active', ''); + await expect(frame).toHaveCSS('outline-style', 'solid'); + const bridge = (await join.boundingBox())!; + await page.mouse.move(bridge.x + bridge.width / 2, bridge.y + bridge.height / 2); + await expect(header).toHaveAttribute('data-loop-active', ''); + const frameBounds = (await frame.boundingBox())!; + await page.mouse.move(frameBounds.x + 5, frameBounds.y + frameBounds.height / 2); + await expect(header).toHaveAttribute('data-loop-active', ''); + const nestedHeader = page.locator('[data-loop-group-header="Foreach_nested"]'); + await nestedHeader.hover(); + await expect(nestedHeader).toHaveAttribute('data-loop-active', ''); + await expect(header).not.toHaveAttribute('data-loop-active', ''); + await expect(frame).toHaveCSS('outline-style', 'none'); + } else { + await expect(body).toHaveCount(0); + } + const expanded = await measureForeach(page); + const collapse = page.locator('button[id="Foreach-collapse-toggle"]'); + await collapse.click(); + await expect(pager).toHaveCount(0); + await expect(join).toHaveCount(0); + await expect.poll(async () => (await measureForeach(page)).graph).toBeLessThan(expanded.graph); + const collapsed = await measureForeach(page); + if (flag === 'true') { + // The collapsed React Flow wrapper includes the count badge; the pager + // must disappear from the card and the accepted body-frame position. + expect(expanded.card - collapsed.card).toBe(24); + expect(expanded.frameTop! - collapsed.frameTop!).toBe(24); } + expect(collapsed.edgeStart).toBeLessThan(expanded.edgeStart); + await collapse.click(); + await expect(pager).toBeVisible(); + if (flag === 'true') { + await expect(join).toHaveCount(1); + } + await expect.poll(() => measureForeach(page)).toEqual(expanded); + await expect.poll(() => runIndex(page, 'Foreach')).toBe(1); expect((await getSerializedWorkflowFromStateV2(page)).definition).toEqual(before.definition); expect(await page.evaluate(() => (window as DesignerWindow).DesignerStoreV2.getState().workflow.runInstance)).toBeNull(); await expect(page.getByRole('button', { name: /Insert a new step/ })).toHaveCount(0); @@ -109,6 +193,108 @@ for (const flag of ['true', 'false'] as const) { }); }); + test('does not apply a late Agent response to the selected tool cards', async ({ page }) => { + // The Local Designer's mock client doesn't send HTTP. Back just the simulated Agent route with + // fetch so Playwright can release its responses out of order without changing the product service. + await page.route(/\/LocalDesigner\/httpClient\.ts(?:\?|$)/, async (route) => { + const response = await route.fetch(); + await route.fulfill({ + response, + body: `${await response.text()} + const originalGet = HttpClient.prototype.get; + HttpClient.prototype.get = function (options) { + if (/^\\/url\\/agent-parity-run\\/actions\\/WorkflowAgent\\/agentRepetitions\\/\\d+\\?/.test(options.uri)) { + return fetch(options.uri).then(response => response.json()); + } + return originalGet.apply(this, arguments); + };`, + }); + }); + await openSharedWorkflow(page, 'Agent with MCP Tools', flag); + await enterSimulatedMonitoring(page); + const select = (index: number) => + page.evaluate((page) => { + (window as DesignerWindow).DesignerStoreV2.dispatch({ type: 'workflow/setRunIndex', payload: { nodeId: 'WorkflowAgent', page } }); + }, index); + const release = { older: () => {} }; + const older = new Promise((resolve) => { + release.older = resolve; + }); + const responses = /\/url\/agent-parity-run\/actions\/WorkflowAgent\/agentRepetitions\/00000[012]\?/; + await page.route(responses, async (route) => { + const repetition = new URL(route.request().url()).pathname.split('/').pop()!; + if (repetition === '000001') { + await older; + } + const status = repetition === '000002' ? 'Failed' : 'Succeeded'; + await route.fulfill({ + json: { + name: repetition, + properties: { + ...times, + status, + iterationCount: 3, + // Only Legacy uses a link as the distinct-iteration signal. + ...(flag === 'false' ? { inputsLink: { uri: `/simulated-agent/${repetition}` } } : {}), + tools: { + Regular_Tool: { status, iterations: 3 }, + BuiltIn_MCP_Server: { status, iterations: 3 }, + ...(repetition !== '000001' && { Managed_MCP_Server: { status, iterations: 3 } }), + }, + }, + }, + }); + }); + await page.evaluate(() => { + const store = (window as DesignerWindow).DesignerStoreV2; + store.dispatch({ type: 'workflow/setRunIndex', payload: { nodeId: 'WorkflowAgent', page: 0 } }); + store.dispatch({ + type: 'workflow/setRunInstance', + payload: { id: '/agent-parity-run', name: 'agent-parity-run', properties: { status: 'Succeeded' } }, + }); + }); + const tools = ['Regular_Tool', 'BuiltIn_MCP_Server', 'Managed_MCP_Server']; + const card = (id: string) => page.locator(`[id="msla-node-${id}"]`); + const next = page.getByTestId('msla-pager-v2-workflowagent').getByLabel(flag === 'true' ? 'Next iteration' : 'Next', { exact: true }); + const activeStatus = () => + page.evaluate((toolIds) => { + const { nodesMetadata } = (window as DesignerWindow).DesignerStoreV2.getState().workflow; + return toolIds.map((id) => (nodesMetadata[id]?.toolRunData ?? nodesMetadata[id]?.runData)?.status); + }, tools); + await expect.poll(activeStatus).toEqual(['Succeeded', 'Succeeded', 'Succeeded']); + if (flag === 'true') { + for (const id of tools) { + await expect(card(id)).toHaveAttribute('data-status', 'succeeded'); + } + await expect(page.getByTestId('msla-pager-v2-builtin_mcp_server')).toBeVisible(); + } + const previousRequest = page.waitForRequest(/\/agentRepetitions\/000001\?/); + await next.click(); + await previousRequest; + if (flag === 'true') { + for (const id of tools) { + await expect(card(id)).not.toHaveAttribute('data-status', /.+/); + await expect(page.getByTestId(`msla-pager-v2-${id.toLowerCase()}`)).toHaveCount(0); + } + } + await next.click(); + await expect.poll(activeStatus).toEqual(['Failed', 'Failed', 'Failed']); + const olderResponse = page.waitForResponse(/\/agentRepetitions\/000001\?/); + release.older(); + await olderResponse; + if (flag === 'true') { + for (const id of tools) { + await expect(card(id)).toHaveAttribute('data-status', 'failed'); + } + await expect(page.getByTestId('msla-pager-v2-builtin_mcp_server')).toBeVisible(); + } + await expect.poll(activeStatus).toEqual(['Failed', 'Failed', 'Failed']); + await select(1); + // Selecting the now-cached response filters the uninvoked tool in both modes. + await expect(page.getByTestId('rf__node-Managed_MCP_Server')).toHaveCount(0); + await expect.poll(activeStatus).toEqual(['Succeeded', 'Succeeded', flag === 'true' ? undefined : 'Failed']); + }); + test('pages the actual regular and MCP tool renderers using deterministic repetition metadata', async ({ page }, testInfo) => { await openSharedWorkflow(page, 'Agent with MCP Tools', flag); const before = await getSerializedWorkflowFromStateV2(page); From 378f6835ad7db9b81eae6f84ccf1472bf8e1033c Mon Sep 17 00:00:00 2001 From: Krrish Mittal Date: Mon, 23 Nov 2026 12:57:03 -0800 Subject: [PATCH 3/3] fix(designer-v2): preserve selected tool results and compact card bounds Keep invocation status and duration scoped during refreshes and paging. Preserve the compact title line height at overview zoom and restore the forced-colors loop hover cue. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- e2e/designer/sharedNodeUiOverview.spec.ts | 41 ++++ .../sharedNodeUiSimulatedRuns.spec.ts | 95 ++++++++- .../src/nodes/overviewStyles.ts | 2 +- .../src/nodes/primitives/LoopBodyJoin.tsx | 12 +- .../bjsworkflow/__test__/monitoring.spec.ts | 30 +++ .../core/actions/bjsworkflow/monitoring.ts | 21 +- .../workflowSlice.graphBehavior.spec.ts | 106 ++++++++++ .../workflowSlice.monitoringBehavior.spec.ts | 124 +++++++++++ .../core/state/workflow/workflowInterfaces.ts | 13 ++ .../core/state/workflow/workflowSelectors.ts | 55 +++-- .../lib/core/state/workflow/workflowSlice.ts | 194 ++++++++++++++---- .../src/lib/core/utils/loopRepetitions.ts | 24 +++ .../lib/ui/CustomNodes/OperationCardNode.tsx | 39 +++- .../src/lib/ui/CustomNodes/ScopeCardNode.tsx | 9 +- .../lib/ui/CustomNodes/SubgraphCardNode.tsx | 28 ++- .../__test__/OperationCardNode.spec.tsx | 37 ++++ .../__test__/SubgraphCardNode.spec.tsx | 40 ++++ .../src/lib/ui/common/LoopsPager/helper.ts | 37 +--- .../__test__/agentChatContent.spec.tsx | 60 ++++-- .../runHistoryPanel/agentChatContent.tsx | 24 ++- .../ui/panel/runTreeView/TreeActionItem.tsx | 6 + 21 files changed, 851 insertions(+), 146 deletions(-) diff --git a/e2e/designer/sharedNodeUiOverview.spec.ts b/e2e/designer/sharedNodeUiOverview.spec.ts index c2dc5d64382..ff733fa3d33 100644 --- a/e2e/designer/sharedNodeUiOverview.spec.ts +++ b/e2e/designer/sharedNodeUiOverview.spec.ts @@ -25,6 +25,47 @@ for (const flag of ['false', 'true'] as const) { test.describe(`Node overview and convergence, flag ${flag}`, { tag: ['@mock', '@shared-node-ui'] }, () => { const shared = flag === 'true'; + test('keeps a three-line authoring title inside its layout bounds at overview zoom', async ({ page }) => { + await page.setViewportSize({ width: 1600, height: 1000 }); + await openSharedWorkflow(page, 'General Run After', flag); + const action = card(page, 'Init_all'); + const label = 'Send an email notification to the on-call engineer after the nightly import'; + await action.press('Enter'); + const titleInput = page.getByRole('textbox', { name: 'Card title', exact: true }); + await titleInput.fill(label); + await titleInput.press('Tab'); + await expect(action).toHaveAccessibleName(new RegExp(label)); + await page.getByTestId('msla-panel-header-close-nav').click(); + + const zoomIn = page.getByRole('button', { name: 'Zoom in', exact: true }); + const zoomOut = page.getByRole('button', { name: 'Zoom out', exact: true }); + for (let step = 0; step < 10 && (await zoom(page)) <= 0.5; step++) { + await zoomIn.click(); + await waitForViewport(page); + } + expect(await zoom(page)).toBeGreaterThan(0.5); + const bounds = () => + action.evaluate((element) => ({ + card: element.offsetHeight, + reserved: element.closest('.react-flow__node')!.style.height, + title: element.querySelector('[data-node-title]')?.offsetHeight, + })); + const detailBounds = await bounds(); + if (shared) { + expect(detailBounds).toEqual({ card: 68, reserved: '68px', title: 54 }); + } + for (let step = 0; step < 10 && (await zoom(page)) >= 0.5; step++) { + await zoomOut.click(); + await waitForViewport(page); + } + expect(await zoom(page)).toBeLessThan(0.5); + await expect(page.locator('[data-node-overview]')).toHaveCount(shared ? 1 : 0); + if (shared) { + await expect(action.locator('[data-node-title]')).toHaveCSS('font-size', '16px'); + } + expect(await bounds()).toEqual(detailBounds); + }); + test('keeps run status visible at native fit and returns to detail without resizing the card', async ({ page }) => { await page.setViewportSize({ width: 1600, height: 1000 }); await openSharedWorkflow(page, 'Monitoring view conditional', flag); diff --git a/e2e/designer/sharedNodeUiSimulatedRuns.spec.ts b/e2e/designer/sharedNodeUiSimulatedRuns.spec.ts index 21bdc3abd3c..14235572d18 100644 --- a/e2e/designer/sharedNodeUiSimulatedRuns.spec.ts +++ b/e2e/designer/sharedNodeUiSimulatedRuns.spec.ts @@ -160,6 +160,26 @@ for (const flag of ['true', 'false'] as const) { await expect(nestedHeader).toHaveAttribute('data-loop-active', ''); await expect(header).not.toHaveAttribute('data-loop-active', ''); await expect(frame).toHaveCSS('outline-style', 'none'); + await page.emulateMedia({ forcedColors: 'active' }); + const stroke = join.locator('path'); + const systemColors = await stroke.evaluate(() => { + const probe = document.createElement('span'); + probe.style.forcedColorAdjust = 'none'; + document.body.append(probe); + const resolve = (color: string) => { + probe.style.color = color; + return getComputedStyle(probe).color; + }; + const colors = { resting: resolve('CanvasText'), hovered: resolve('Highlight') }; + probe.remove(); + return colors; + }); + await expect(stroke).toHaveCSS('stroke', systemColors.resting); + await header.hover(); + await expect(stroke).toHaveCSS('stroke', systemColors.hovered); + await page.mouse.move(1, 1); + await expect(stroke).toHaveCSS('stroke', systemColors.resting); + await page.emulateMedia({ forcedColors: 'none' }); } else { await expect(body).toHaveCount(0); } @@ -203,7 +223,7 @@ for (const flag of ['true', 'false'] as const) { body: `${await response.text()} const originalGet = HttpClient.prototype.get; HttpClient.prototype.get = function (options) { - if (/^\\/url\\/agent-parity-run\\/actions\\/WorkflowAgent\\/agentRepetitions\\/\\d+\\?/.test(options.uri)) { + if (/^\\/url\\/agent-parity-run\\/actions\\/WorkflowAgent\\/agentRepetitions\\/\\d+(?:\\/actions)?\\?/.test(options.uri)) { return fetch(options.uri).then(response => response.json()); } return originalGet.apply(this, arguments); @@ -221,6 +241,37 @@ for (const flag of ['true', 'false'] as const) { release.older = resolve; }); const responses = /\/url\/agent-parity-run\/actions\/WorkflowAgent\/agentRepetitions\/00000[012]\?/; + if (flag === 'true') { + await page.route(/\/url\/agent-parity-run\/actions\/WorkflowAgent\/agentRepetitions\/00000[012]\/actions\?/, async (route) => { + const first = new URL(route.request().url()).pathname.includes('/000000/'); + await route.fulfill({ + json: { + value: first + ? [ + { + name: 'BuiltIn_MCP_Server', + properties: { + actionResults: [ + { ...times, status: 'Failed' }, + { ...times, endTime: '2026-01-01T00:00:02Z', status: 'Succeeded' }, + ], + }, + }, + { + name: 'code_interpreter', + properties: { + actionResults: [ + { ...times, name: 'code_interpreter', status: 'Failed' }, + { ...times, name: 'code_interpreter', endTime: '2026-01-01T00:00:03Z', status: 'Succeeded' }, + ], + }, + }, + ] + : [], + }, + }); + }); + } await page.route(responses, async (route) => { const repetition = new URL(route.request().url()).pathname.split('/').pop()!; if (repetition === '000001') { @@ -240,6 +291,7 @@ for (const flag of ['true', 'false'] as const) { Regular_Tool: { status, iterations: 3 }, BuiltIn_MCP_Server: { status, iterations: 3 }, ...(repetition !== '000001' && { Managed_MCP_Server: { status, iterations: 3 } }), + ...(flag === 'true' && repetition === '000000' && { code_interpreter: { status: 'Failed', iterations: 2 } }), }, }, }, @@ -263,10 +315,47 @@ for (const flag of ['true', 'false'] as const) { }, tools); await expect.poll(activeStatus).toEqual(['Succeeded', 'Succeeded', 'Succeeded']); if (flag === 'true') { - for (const id of tools) { + for (const id of ['Regular_Tool', 'Managed_MCP_Server']) { await expect(card(id)).toHaveAttribute('data-status', 'succeeded'); } - await expect(page.getByTestId('msla-pager-v2-builtin_mcp_server')).toBeVisible(); + const mcp = card('BuiltIn_MCP_Server'); + const mcpPager = page.getByTestId('msla-pager-v2-builtin_mcp_server'); + await expect(mcpPager).toBeVisible(); + await expect(mcp).toHaveAccessibleName(/Failed.*1s/i); + await mcpPager.getByLabel('Next iteration', { exact: true }).click(); + await expect(mcp).toHaveAccessibleName(/Succeeded.*2s/i); + await mcpPager.getByLabel('Next iteration', { exact: true }).click(); + await expect(mcp).toHaveAccessibleName(/Succeeded/i); + await expect(mcp).not.toHaveAccessibleName(/2s/i); + + await page.evaluate(() => { + const store = (window as DesignerWindow).DesignerStoreV2; + const { WorkflowAgent } = store.getState().workflow.nodesMetadata; + store.dispatch({ + type: 'workflow/updateAgenticMetadata', + payload: { + nodeId: 'WorkflowAgent', + agentRepetitionIdentity: WorkflowAgent.agentRepetitionIdentity, + scopeRepetitionRunData: { + ...WorkflowAgent.runData, + tools: { + Regular_Tool: { status: 'Succeeded', iterations: 3 }, + BuiltIn_MCP_Server: { status: 'Succeeded', iterations: 2 }, + Managed_MCP_Server: { status: 'Succeeded', iterations: 3 }, + code_interpreter: { status: 'Failed', iterations: 2 }, + }, + }, + }, + }); + }); + await expect.poll(() => runIndex(page, 'BuiltIn_MCP_Server', true)).toBe(1); + await expect(mcp).toHaveAccessibleName(/Succeeded.*2s/i); + + const builtIn = card('code_interpreter'); + const builtInPager = page.getByTestId('msla-pager-v2-code_interpreter'); + await builtInPager.getByLabel('Next iteration', { exact: true }).click(); + await builtIn.click(); + await expect(builtIn).toHaveAccessibleName(/Succeeded.*3s/i); } const previousRequest = page.waitForRequest(/\/agentRepetitions\/000001\?/); await next.click(); diff --git a/libs/designer-ui-v2/src/nodes/overviewStyles.ts b/libs/designer-ui-v2/src/nodes/overviewStyles.ts index 9fbad1a757c..ad54ff64bb6 100644 --- a/libs/designer-ui-v2/src/nodes/overviewStyles.ts +++ b/libs/designer-ui-v2/src/nodes/overviewStyles.ts @@ -4,8 +4,8 @@ import { makeStyles, tokens } from '@fluentui/react-components'; export const useNodeOverviewStyles = makeStyles({ canvas: { '& [data-node-card] [data-node-title]': { + // The title owns its line height so a three-line card still fits the reserved bounds. fontSize: tokens.fontSizeBase400, - lineHeight: tokens.lineHeightBase300, }, '& [data-node-card] [data-node-caption]': { display: 'none' }, '& [data-node-card] [data-node-status-icon]': { fontSize: tokens.fontSizeBase400 }, diff --git a/libs/designer-ui-v2/src/nodes/primitives/LoopBodyJoin.tsx b/libs/designer-ui-v2/src/nodes/primitives/LoopBodyJoin.tsx index ef5dcdb108a..40c2211dbd8 100644 --- a/libs/designer-ui-v2/src/nodes/primitives/LoopBodyJoin.tsx +++ b/libs/designer-ui-v2/src/nodes/primitives/LoopBodyJoin.tsx @@ -6,10 +6,6 @@ const useStyles = makeStyles({ position: 'absolute', transform: 'translateX(-50%)', pointerEvents: 'none', - '[data-loop-active] > & > path': { - stroke: tokens.colorBrandStroke1, - '@media (forced-colors: active)': { stroke: 'Highlight' }, - }, }, header: { '&[data-loop-group-header][data-loop-active]:not([data-selected])': { @@ -19,6 +15,14 @@ const useStyles = makeStyles({ }, }, body: { + '&[data-loop-active] > [data-loop-body-join] > path': { + stroke: tokens.colorBrandStroke1, + '@media (forced-colors: active)': { + // Use the system's own highlight without letting the browser replace the SVG stroke. + forcedColorAdjust: 'none', + stroke: 'Highlight !important', + }, + }, '&[data-loop-active] > [data-node-card="loop-frame"]:not([data-selected])': { outlineStyle: 'solid', outlineWidth: tokens.strokeWidthThin, diff --git a/libs/designer-v2/src/lib/core/actions/bjsworkflow/__test__/monitoring.spec.ts b/libs/designer-v2/src/lib/core/actions/bjsworkflow/__test__/monitoring.spec.ts index e781a06d2ff..42853e3b885 100644 --- a/libs/designer-v2/src/lib/core/actions/bjsworkflow/__test__/monitoring.spec.ts +++ b/libs/designer-v2/src/lib/core/actions/bjsworkflow/__test__/monitoring.spec.ts @@ -54,6 +54,36 @@ describe('fetchBuiltInToolRunData', () => { vi.clearAllMocks(); }); + it('binds content and status from the requested built-in invocation, not the first match or aggregate', async () => { + const requestedLink = { uri: 'https://example.com/invocation-2', contentSize: 1 }; + mockGetAgentActionsRepetition.mockResolvedValue([ + { + name: 'code_interpreter', + properties: { + actionResults: [ + { name: 'code_interpreter', status: 'Failed', outputsLink: { uri: 'https://example.com/invocation-1' } }, + { name: 'code_interpreter', status: 'Succeeded', outputsLink: requestedLink }, + ], + }, + }, + ]); + mockGetContent.mockResolvedValue({ result: 'second invocation' }); + + const response = await fetchBuiltInToolRunData({ + toolNodeId: 'code_interpreter', + agentNodeId: 'Agent', + runId: 'run', + repetitionName: '000000', + agentToolInvocation: { agentRepetitionIdentity: 'run|Agent|000000|0|', page: 1 }, + })(vi.fn(), vi.fn(), undefined); + + expect(mockGetContent).toHaveBeenCalledExactlyOnceWith(requestedLink); + expect(response.payload).toMatchObject({ + status: 'Succeeded', + outputs: { result: { value: 'second invocation' } }, + }); + }); + it('should fetch action-level data via getAgentActionsRepetition and convert to BoundParameters', async () => { const mockInputs = { message: 'hello', code: 'print("hi")' }; const mockOutputs = { result: 'hi', exitCode: 0 }; diff --git a/libs/designer-v2/src/lib/core/actions/bjsworkflow/monitoring.ts b/libs/designer-v2/src/lib/core/actions/bjsworkflow/monitoring.ts index f60908e7e72..527195b27a6 100644 --- a/libs/designer-v2/src/lib/core/actions/bjsworkflow/monitoring.ts +++ b/libs/designer-v2/src/lib/core/actions/bjsworkflow/monitoring.ts @@ -25,6 +25,7 @@ import type { NodeOperation } from '../../state/operation/operationMetadataSlice import { getConnectorWithSwagger } from '../../queries/connections'; import OutputsBinder from '../../utils/monitoring/binders/outputs'; import { getAgentActionsRepetition, getAgentRepetition } from '../../queries/runs'; +import type { AgentToolInvocation } from '../../state/workflow/workflowInterfaces'; /** * Converts raw JSON data into BoundParameters format for display in ValuesPanel. @@ -155,15 +156,31 @@ export const fetchBuiltInToolRunData = createAsyncThunk( repetitionName: string; inputsLink?: ContentLink; outputsLink?: ContentLink; + agentToolInvocation?: AgentToolInvocation; }) => { - const { toolNodeId, agentNodeId, runId, repetitionName } = payload; + const { toolNodeId, agentNodeId, runId, repetitionName, agentToolInvocation } = payload; // Use action-level links if provided, otherwise fetch them from getAgentActionsRepetition let actionInputsLink = payload.inputsLink; let actionOutputsLink = payload.outputsLink; let repetitionProperties: any = {}; - if (actionInputsLink || actionOutputsLink) { + if (agentToolInvocation) { + // Links alone carry no status or duration. Read the same invocation for both content and card details. + const actionsRepetitions = await getAgentActionsRepetition(agentNodeId, runId, repetitionName, 0); + const results = actionsRepetitions.flatMap((repetition) => { + const actions = (repetition.properties as { actionResults?: (LogicAppsV2.WorkflowRunAction & { name?: string })[] }).actionResults; + return (actions ?? []).filter((action) => (action?.name ?? repetition.name) === toolNodeId); + }); + const selected = results[agentToolInvocation.page]; + if (!selected) { + // An aggregate or a different invocation is not a substitute for a missing page. + return undefined; + } + repetitionProperties = selected; + actionInputsLink = selected.inputsLink as ContentLink | undefined; + actionOutputsLink = selected.outputsLink as ContentLink | undefined; + } else if (actionInputsLink || actionOutputsLink) { // We have action-level links — no need to fetch repetitionProperties = {}; } else { diff --git a/libs/designer-v2/src/lib/core/state/workflow/__test__/workflowSlice.graphBehavior.spec.ts b/libs/designer-v2/src/lib/core/state/workflow/__test__/workflowSlice.graphBehavior.spec.ts index 62ca2ab807f..96d7804fd89 100644 --- a/libs/designer-v2/src/lib/core/state/workflow/__test__/workflowSlice.graphBehavior.spec.ts +++ b/libs/designer-v2/src/lib/core/state/workflow/__test__/workflowSlice.graphBehavior.spec.ts @@ -367,6 +367,112 @@ describe('workflow graph mutations preserve authoring topology', () => { expect(reducer(refreshed, actions.clearAllRepetitionRunData()).nodesMetadata.toolB.toolRunData).toBeUndefined(); }); + it.each([undefined, SUBGRAPH_TYPES.MCP_CLIENT])( + 'refreshes tool aggregates without losing the selected invocation (%s)', + (subgraphType) => { + const identity = 'run-1|Agent|000001|1|Succeeded'; + const state: WorkflowState = { + ...initialWorkflowState, + graph: { id: 'root', type: 'GRAPH_NODE', children: [], edges: [] }, + nodesMetadata: { + Agent: { graphId: 'root' }, + Tool: { graphId: 'Agent', subgraphType }, + }, + }; + const refresh = (current: WorkflowState, iterations: number, agentRepetitionIdentity = identity) => + reducer( + current, + actions.updateAgenticMetadata({ + nodeId: 'Agent', + agentRepetitionIdentity, + scopeRepetitionRunData: { tools: { Tool: { status: 'Failed', iterations } } }, + }) + ); + const changePage = (current: WorkflowState, page: number) => + reducer(current, (subgraphType ? actions.setToolRunIndex : actions.setRunIndex)({ nodeId: 'Tool', page })); + const aggregate = refresh(state, 2); + const invocation = { + nodeId: 'Tool', + runData: { + status: 'Succeeded', + startTime: '2026-01-01T00:00:00Z', + endTime: '2026-01-01T00:00:02Z', + inputsLink: { uri: '/selected-inputs', contentSize: 1 }, + outputsLink: { contentSize: 0 }, + retryHistory: [], + correlation: { actionTrackingId: 'invocation', clientTrackingId: 'run-1' }, + code: 'OK', + }, + agentToolInvocation: { agentRepetitionIdentity: identity, page: 1 }, + }; + const selected = reducer(changePage(aggregate, 1), actions.setRepetitionRunData(invocation)); + const refreshed = refresh(selected, 3); + + expect(refreshed.nodesMetadata.Tool.runData).toMatchObject({ + status: 'Succeeded', + duration: '2s', + inputsLink: { uri: '/selected-inputs' }, + }); + expect(subgraphType ? refreshed.nodesMetadata.Tool.toolRunData : refreshed.nodesMetadata.Tool.runData).toMatchObject({ + repetitionCount: 3, + }); + expect(refresh(changePage(refreshed, 2), 3).nodesMetadata.Tool.runData?.status).not.toBe('Succeeded'); + expect(reducer(changePage(refreshed, 2), actions.setRepetitionRunData(invocation)).nodesMetadata.Tool.runData?.status).not.toBe( + 'Succeeded' + ); + expect(refresh(refreshed, 2, 'run-2|Agent|000001|1|Succeeded').nodesMetadata.Tool.runData?.status).not.toBe('Succeeded'); + } + ); + + it.each([ + { subgraphType: undefined, count: 2, page: 1 }, + { subgraphType: SUBGRAPH_TYPES.MCP_CLIENT, count: 2, page: 1 }, + { subgraphType: undefined, count: 1, page: 0 }, + { subgraphType: SUBGRAPH_TYPES.MCP_CLIENT, count: 0, page: 0 }, + ])('clamps a $subgraphType tool to page $page when the count shrinks to $count', ({ subgraphType, count, page }) => { + const agentRepetitionIdentity = 'run-1|Agent|000001|1|Succeeded'; + const selection = subgraphType ? { toolRunIndex: 2 } : { runIndex: 2 }; + const aggregate = { status: 'Failed', repetitionCount: 3 } as LogicAppsV2.WorkflowRunAction; + const state: WorkflowState = { + ...initialWorkflowState, + graph: { id: 'root', type: 'GRAPH_NODE', children: [], edges: [] }, + nodesMetadata: { + Agent: { graphId: 'root' }, + Tool: { + graphId: 'Agent', + subgraphType, + ...selection, + agentRepetitionIdentity, + agentToolInvocation: { agentRepetitionIdentity, page: 2, aggregate: subgraphType ? undefined : aggregate }, + runData: { + status: 'Succeeded', + repetitionCount: 3, + duration: '2s', + inputsLink: { uri: '/removed-invocation', contentSize: 1 }, + } as LogicAppsV2.WorkflowRunAction, + toolRunData: subgraphType ? aggregate : undefined, + }, + }, + }; + const refreshed = reducer( + state, + actions.updateAgenticMetadata({ + nodeId: 'Agent', + agentRepetitionIdentity, + scopeRepetitionRunData: { tools: { Tool: { status: 'Failed', iterations: count } } }, + }) + ); + const tool = refreshed.nodesMetadata.Tool; + expect(subgraphType ? tool.toolRunIndex : tool.runIndex).toBe(page); + expect(tool.agentToolInvocation).toBeUndefined(); + if (subgraphType) { + expect(tool.runData).toBeUndefined(); + expect(tool.toolRunData).toEqual({ status: 'Failed', repetitionCount: count }); + } else { + expect(tool.runData).toEqual({ status: 'Failed', repetitionCount: count }); + } + }); + it('collapses and expands nested graph descendants independently from collapsed action branches', () => { const state = fixture({ actions: { diff --git a/libs/designer-v2/src/lib/core/state/workflow/__test__/workflowSlice.monitoringBehavior.spec.ts b/libs/designer-v2/src/lib/core/state/workflow/__test__/workflowSlice.monitoringBehavior.spec.ts index 3b10eb74423..c4dab415470 100644 --- a/libs/designer-v2/src/lib/core/state/workflow/__test__/workflowSlice.monitoringBehavior.spec.ts +++ b/libs/designer-v2/src/lib/core/state/workflow/__test__/workflowSlice.monitoringBehavior.spec.ts @@ -6,6 +6,7 @@ import { fetchBuiltInToolRunData, initializeInputsOutputsBinding } from '../../. import { resetWorkflowState } from '../../global'; import { updateNodeParameters, updateNodeSettings } from '../../operation/operationMetadataSlice'; import type { WorkflowState } from '../workflowInterfaces'; +import { getNodeRunData } from '../workflowSelectors'; import reducer, { initialWorkflowState, workflowSlice } from '../workflowSlice'; const actions = workflowSlice.actions; @@ -35,7 +36,130 @@ const run: LogicAppsV2.WorkflowRunAction = { const boundInputs = { input: { displayName: 'Input', value: 'actual request' } }; const boundOutputs = { result: { displayName: 'Result', value: 'actual response' } }; +const toolId = 'code_interpreter'; +const agentToolInvocation = { agentRepetitionIdentity: 'run|Agent|000000|0|', page: 1 }; +const refreshBuiltInTool = (state: WorkflowState, identity = agentToolInvocation.agentRepetitionIdentity) => + reducer( + state, + actions.updateAgenticMetadata({ + nodeId: 'Agent', + agentRepetitionIdentity: identity, + scopeRepetitionRunData: { tools: { [toolId]: { status: 'Failed', iterations: 3 } } }, + }) + ); +const selectBuiltInTool = () => + reducer( + refreshBuiltInTool({ + ...fixture(), + runInstance: { id: 'run' } as LogicAppsV2.RunInstanceDefinition, + nodesMetadata: { Agent: { graphId: 'root', runIndex: 0 }, [toolId]: { graphId: 'Agent' } }, + }), + actions.setRunIndex({ nodeId: toolId, page: 1 }) + ); +const builtInToolResponse = fetchBuiltInToolRunData.fulfilled( + { ...run, toolNodeId: toolId, inputs: boundInputs, outputs: boundOutputs }, + 'built-in-request', + { + toolNodeId: toolId, + agentNodeId: 'Agent', + runId: 'run', + repetitionName: '000000', + agentToolInvocation, + } +); + describe('workflow monitoring and host state transitions', () => { + it('retains the selected built-in response and bound content across an aggregate refresh', () => { + const selected = reducer(selectBuiltInTool(), builtInToolResponse); + const refreshed = refreshBuiltInTool(selected); + expect(refreshed.nodesMetadata[toolId].runData).toMatchObject({ + status: 'Succeeded', + duration: '2s', + repetitionCount: 3, + inputs: boundInputs, + outputs: boundOutputs, + }); + }); + + it('ignores a built-in response after the tool page changes', () => { + const paged = reducer(selectBuiltInTool(), actions.setRunIndex({ nodeId: toolId, page: 2 })); + expect(reducer(paged, builtInToolResponse)).toBe(paged); + }); + + it('ignores a built-in response when the Agent changes repetition before the new aggregate arrives', () => { + const paged = reducer(selectBuiltInTool(), actions.setRunIndex({ nodeId: 'Agent', page: 1 })); + expect(reducer(paged, builtInToolResponse)).toBe(paged); + }); + + it.each([false, true])('applies a chat-selected built-in response (response before aggregate: %s)', (responseFirst) => { + const selected = selectBuiltInTool(); + const nextInvocation = { agentRepetitionIdentity: 'run|Agent|000001|1|', page: 2 }; + const request = { ...builtInToolResponse.meta.arg, repetitionName: '000001', agentToolInvocation: nextInvocation }; + const moved = reducer(selected, actions.setRunIndex({ nodeId: 'Agent', page: 1 })); + const pending = reducer(moved, fetchBuiltInToolRunData.pending('chat-request', request)); + const response = fetchBuiltInToolRunData.fulfilled(builtInToolResponse.payload, 'chat-request', request); + const refreshed = responseFirst + ? refreshBuiltInTool(reducer(pending, response), nextInvocation.agentRepetitionIdentity) + : reducer(refreshBuiltInTool(pending, nextInvocation.agentRepetitionIdentity), response); + expect(refreshed.nodesMetadata[toolId]).toMatchObject({ + runIndex: 2, + runData: { status: 'Succeeded', repetitionCount: 3, inputs: boundInputs, outputs: boundOutputs }, + }); + }); + + it.each([false, true])( + 'keeps admitted built-in details when leaving an unloaded Agent repetition (response arrived: %s)', + (responded) => { + const selected = reducer(selectBuiltInTool(), builtInToolResponse); + const request = { + ...builtInToolResponse.meta.arg, + repetitionName: '000001', + agentToolInvocation: { agentRepetitionIdentity: 'run|Agent|000001|1|', page: 2 }, + }; + let state = reducer(selected, actions.setRunIndex({ nodeId: 'Agent', page: 1 })); + state = reducer(state, fetchBuiltInToolRunData.pending('chat-request', request)); + expect(getNodeRunData(state, toolId)).toBeUndefined(); + const response = fetchBuiltInToolRunData.fulfilled({ ...builtInToolResponse.payload, status: 'Failed' }, 'chat-request', request); + if (responded) { + state = reducer(state, response); + } + state = reducer(state, actions.setRunIndex({ nodeId: 'Agent', page: 0 })); + if (!responded) { + state = reducer(state, response); + } + expect(state.nodesMetadata[toolId]).toEqual(selected.nodesMetadata[toolId]); + expect(getNodeRunData(state, toolId)).toEqual(selected.nodesMetadata[toolId].runData); + } + ); + + it('does not inherit Agent content when a scoped built-in tool page is clamped', () => { + const selected = reducer(selectBuiltInTool(), builtInToolResponse); + const agentInputs = { uri: 'https://example.test/agent/inputs' }; + const agentOutputs = { uri: 'https://example.test/agent/outputs' }; + const scopeRepetitionRunData = { + inputsLink: agentInputs, + outputsLink: agentOutputs, + tools: { [toolId]: { status: 'Failed', iterations: 1 } }, + }; + const refreshed = reducer( + selected, + actions.updateAgenticMetadata({ + nodeId: 'Agent', + agentRepetitionIdentity: agentToolInvocation.agentRepetitionIdentity, + scopeRepetitionRunData, + }) + ); + const tool = refreshed.nodesMetadata[toolId]; + expect(tool.runIndex).toBe(0); + expect(tool.runData?.status).toBe('Failed'); + expect(tool.runData?.inputsLink?.uri).toBeUndefined(); + expect(tool.runData?.outputsLink?.uri).toBeUndefined(); + expect(tool.runData?.inputs).toBeUndefined(); + expect(tool.runData?.outputs).toBeUndefined(); + const legacy = reducer(selected, actions.updateAgenticMetadata({ nodeId: 'Agent', scopeRepetitionRunData })); + expect(legacy.nodesMetadata[toolId].runData).toMatchObject({ inputsLink: agentInputs, outputsLink: agentOutputs }); + }); + it('updates repetition selection and timing, then clears nested run data while retaining root results', () => { let state = fixture(); state = reducer(state, actions.setRunIndex({ nodeId: 'B', page: 2 })); diff --git a/libs/designer-v2/src/lib/core/state/workflow/workflowInterfaces.ts b/libs/designer-v2/src/lib/core/state/workflow/workflowInterfaces.ts index 77544f19ebd..730b3e553d7 100644 --- a/libs/designer-v2/src/lib/core/state/workflow/workflowInterfaces.ts +++ b/libs/designer-v2/src/lib/core/state/workflow/workflowInterfaces.ts @@ -4,6 +4,11 @@ import type { LogicAppsV2, SubgraphType } from '@microsoft/logic-apps-shared'; export type SpecTypes = 'BJS' | 'CNCF'; +export interface AgentToolInvocation { + agentRepetitionIdentity: string; + page: number; +} + export interface NodeMetadata { graphId: string; parentNodeId?: string; @@ -14,11 +19,19 @@ export interface NodeMetadata { runData?: LogicAppsV2.WorkflowRunAction | LogicAppsV2.WorkflowRunTrigger; actionMetadata?: Record; subgraphRunData?: Record; + subgraphRunDataIdentity?: string; runIndex?: number; handoffs?: Record; toolRunIndex?: number; toolRunData?: LogicAppsV2.WorkflowRunAction; agentRepetitionIdentity?: string; + agentToolInvocation?: AgentToolInvocation & { aggregate?: LogicAppsV2.WorkflowRunAction }; + pendingBuiltInTool?: { + toolNodeId: string; + invocation: AgentToolInvocation; + requestId: string; + runData?: Partial; + }; } export interface NodesMetadata { [nodeId: string]: NodeMetadata; diff --git a/libs/designer-v2/src/lib/core/state/workflow/workflowSelectors.ts b/libs/designer-v2/src/lib/core/state/workflow/workflowSelectors.ts index 83cea4dd522..7e5e3140178 100644 --- a/libs/designer-v2/src/lib/core/state/workflow/workflowSelectors.ts +++ b/libs/designer-v2/src/lib/core/state/workflow/workflowSelectors.ts @@ -13,6 +13,7 @@ import { getRecordEntry, SUBGRAPH_TYPES, equals, + isBuiltInAgentTool, } from '@microsoft/logic-apps-shared'; import { createSelector } from '@reduxjs/toolkit'; import { useMemo } from 'react'; @@ -25,6 +26,7 @@ import { useEdges } from '@xyflow/react'; import { ErrorLevel } from '../operation/errorLevel'; import type { OperationMetadataState } from '../operation/operationMetadataSlice'; import { getOperationsState } from '../selectors/actionMetadataSelector'; +import { getAgentRepetitionIdentity, getScopeRepetitionName } from '../../utils/loopRepetitions'; export const getWorkflowState = (state: RootState): WorkflowState => state.workflow; @@ -649,10 +651,21 @@ export const useRetryHistory = (id: string): LogicAppsV2.RetryHistory[] | undefi ) ); -export const useRunData = (id: string): LogicAppsV2.WorkflowRunAction | LogicAppsV2.WorkflowRunTrigger | undefined => - useSelector( - useMemo(() => createSelector(getWorkflowState, (state: WorkflowState) => getRecordEntry(state.nodesMetadata, id)?.runData), [id]) - ); +export const getNodeRunData = (state: WorkflowState, id: string): NodesMetadata[string]['runData'] => { + const node = getRecordEntry(state.nodesMetadata, id); + // Keep the previous tool result in state for a return to its cached repetition, but not in the open details panel. + if ( + node?.agentRepetitionIdentity && + isBuiltInAgentTool(id) && + node.agentRepetitionIdentity !== getSelectedAgentRepetitionIdentity(state, node.graphId) + ) { + return undefined; + } + return node?.runData; +}; + +export const useRunData = (id: string): NodesMetadata[string]['runData'] => + useSelector(useMemo(() => createSelector(getWorkflowState, (state: WorkflowState) => getNodeRunData(state, id)), [id])); export const useToolRunData = (id: string): LogicAppsV2.WorkflowRunAction | LogicAppsV2.WorkflowRunTrigger | undefined => useSelector( @@ -758,22 +771,28 @@ export const useToolRunIndex = (id: string | undefined): number | undefined => { ); }; +const getParentNodeId = (nodesMetadata: NodesMetadata, id: string | undefined): string | undefined => { + const parentId = getRecordEntry(nodesMetadata, id)?.parentNodeId; + return parentId?.includes('elseActions') || parentId?.includes('actions') + ? getRecordEntry(nodesMetadata, parentId)?.parentNodeId + : parentId; +}; + +export const getSelectedAgentRepetitionIdentity = (state: WorkflowState, agentNodeId: string): string | undefined => { + const repetitionIndex = getRecordEntry(state.nodesMetadata, agentNodeId)?.runIndex; + const parentId = getParentNodeId(state.nodesMetadata, agentNodeId); + return getAgentRepetitionIdentity({ + runId: state.runInstance?.id, + ownerNodeId: agentNodeId, + repetitionName: getScopeRepetitionName(repetitionIndex), + repetitionIndex, + parentStatus: getRecordEntry(state.nodesMetadata, parentId)?.runData?.status, + }); +}; + export const useParentNodeId = (id: string | undefined): string | undefined => { return useSelector( - useMemo( - () => - createSelector(getWorkflowState, (state: WorkflowState) => { - if (!id) { - return undefined; - } - const parentId = getRecordEntry(state.nodesMetadata, id)?.parentNodeId; - if (parentId?.includes('elseActions') || parentId?.includes('actions')) { - return getRecordEntry(state.nodesMetadata, parentId)?.parentNodeId; - } - return parentId; - }), - [id] - ) + useMemo(() => createSelector(getWorkflowState, (state: WorkflowState) => getParentNodeId(state.nodesMetadata, id)), [id]) ); }; diff --git a/libs/designer-v2/src/lib/core/state/workflow/workflowSlice.ts b/libs/designer-v2/src/lib/core/state/workflow/workflowSlice.ts index 0e0f61bdf93..496c52529d7 100644 --- a/libs/designer-v2/src/lib/core/state/workflow/workflowSlice.ts +++ b/libs/designer-v2/src/lib/core/state/workflow/workflowSlice.ts @@ -32,9 +32,9 @@ import { updateStaticResults, } from '../operation/operationMetadataSlice'; import type { RelationshipIds } from '../panel/panelTypes'; -import type { ErrorMessage, SpecTypes, WorkflowState, WorkflowKind, NodeMetadata } from './workflowInterfaces'; +import type { AgentToolInvocation, ErrorMessage, SpecTypes, WorkflowState, WorkflowKind, NodeMetadata } from './workflowInterfaces'; import type { BoundParameters } from '@microsoft/logic-apps-shared'; -import { getParentsUncollapseFromGraphState, getWorkflowNodeFromGraphState } from './workflowSelectors'; +import { getParentsUncollapseFromGraphState, getSelectedAgentRepetitionIdentity, getWorkflowNodeFromGraphState } from './workflowSelectors'; import { LogEntryLevel, LoggerService, @@ -60,6 +60,45 @@ import { updateAgenticSubgraph, type UpdateAgenticGraphPayload } from '../../par import { isA2AWorkflow, shouldClearNodeRunData } from './helper'; import { UnsupportedExceptionCode } from '../../../common/exceptions/unsupported'; +const clampToolPage = (page: number, count: number | undefined): number => + Number.isInteger(count) ? Math.min(page, Math.max((count ?? 0) - 1, 0)) : page; + +const selectRunPage = (node: NodeMetadata, page: number) => { + if (node.runIndex !== page) { + delete node.pendingBuiltInTool; + } + if (node.agentToolInvocation && node.agentToolInvocation.page !== page && node.subgraphType !== SUBGRAPH_TYPES.MCP_CLIENT) { + node.runData = node.agentToolInvocation.aggregate; + delete node.agentToolInvocation; + } + node.runIndex = page; +}; + +const setToolInvocationRunData = (node: NodeMetadata, invocation: AgentToolInvocation, runData: Partial) => { + const isMcp = node.subgraphType === SUBGRAPH_TYPES.MCP_CLIENT; + const page = isMcp ? node.toolRunIndex : node.runIndex; + if (node.agentRepetitionIdentity !== invocation.agentRepetitionIdentity || page !== invocation.page) { + return; + } + const aggregate = isMcp ? undefined : node.agentToolInvocation ? node.agentToolInvocation.aggregate : node.runData; + if ((isMcp ? node.toolRunData?.repetitionCount : aggregate?.repetitionCount) === 0) { + return; + } + node.agentToolInvocation = { ...invocation, aggregate }; + node.runData = { + ...formatRepetitionRunData(runData), + ...(!isMcp && { repetitionCount: aggregate?.repetitionCount }), + }; +}; + +const formatRepetitionRunData = (runData: Partial): LogicAppsV2.WorkflowRunAction => + ({ + ...runData, + inputsLink: runData?.inputsLink ?? null, + outputsLink: runData?.outputsLink ?? null, + duration: getDurationStringPanelMode(Date.parse(runData?.endTime ?? '') - Date.parse(runData?.startTime ?? ''), /* abbreviated */ true), + }) as LogicAppsV2.WorkflowRunAction; + export interface AddImplicitForeachPayload { nodeId: string; foreachNodeId: string; @@ -540,6 +579,8 @@ export const workflowSlice = createSlice({ const { scopeRepetitionRunData, nodeId, agentRepetitionIdentity } = action.payload; const { tools = {} } = scopeRepetitionRunData ?? {}; const agentGraph = getWorkflowNodeFromGraphState(state, nodeId); + const agentMetadata = getRecordEntry(state.nodesMetadata, nodeId); + const pendingTool = agentMetadata?.pendingBuiltInTool; // Agent monitoring is scoped to the selected repetition. When a tool is missing in that // repetition (or the run failed before invocation), clear the previous iteration's tool @@ -565,6 +606,7 @@ export const workflowSlice = createSlice({ delete clearedNodeData.toolRunIndex; delete clearedNodeData.runData; delete clearedNodeData.runIndex; + delete clearedNodeData.agentToolInvocation; state.nodesMetadata[toolId] = clearedNodeData as NodeMetadata; }); @@ -576,45 +618,70 @@ export const workflowSlice = createSlice({ // A refresh of the current selection must not reset a tool page chosen in the run tree or canvas. const sameSelection = !!agentRepetitionIdentity && nodeMetadata.agentRepetitionIdentity === agentRepetitionIdentity; - if (nodeMetadata.subgraphType === SUBGRAPH_TYPES.MCP_CLIENT) { + const summary = { status: tools[toolId].status, repetitionCount: tools[toolId].iterations }; + const isMcp = nodeMetadata.subgraphType === SUBGRAPH_TYPES.MCP_CLIENT; + const currentPage = (isMcp ? nodeMetadata.toolRunIndex : nodeMetadata.runIndex) ?? 0; + const pending = + pendingTool && pendingTool.toolNodeId === toolId && pendingTool.invocation.agentRepetitionIdentity === agentRepetitionIdentity + ? pendingTool + : undefined; + const page = clampToolPage(pending?.invocation.page ?? (sameSelection ? currentPage : 0), summary.repetitionCount); + const preservePage = sameSelection && page === currentPage && summary.repetitionCount !== 0; + if (isMcp) { // MCP client action does not have a tool, so save the "tool" runData in a dedicated toolRunData. const nodeData = { ...nodeMetadata, - toolRunData: { - status: tools[toolId].status, - repetitionCount: tools[toolId].iterations, - }, - toolRunIndex: sameSelection ? (nodeMetadata.toolRunIndex ?? 0) : 0, + toolRunData: summary, + toolRunIndex: page, agentRepetitionIdentity, }; - if (agentRepetitionIdentity && !sameSelection) { + if (agentRepetitionIdentity && !preservePage) { delete nodeData.runData; delete nodeData.runIndex; + delete nodeData.agentToolInvocation; } state.nodesMetadata[toolId] = nodeData as NodeMetadata; } else { - const preserveToolDetails = sameSelection && nodeMetadata.runData; + const preserveToolDetails = preservePage && nodeMetadata.runData; + const invocation = nodeMetadata.agentToolInvocation; + const selectedInvocation = + preservePage && invocation && invocation.agentRepetitionIdentity === agentRepetitionIdentity && invocation.page === page + ? invocation + : undefined; const nodeData = { ...nodeMetadata, runData: { - ...(preserveToolDetails || {}), - status: tools[toolId].status, - repetitionCount: tools[toolId].iterations, - ...(isBuiltInAgentTool(toolId) && !preserveToolDetails + ...((invocation && !selectedInvocation && sameSelection ? invocation.aggregate : preserveToolDetails) || {}), + ...summary, + ...(selectedInvocation && { status: nodeMetadata.runData?.status ?? summary.status }), + // The Agent's content describes the whole repetition, not an individual tool invocation. + ...(!agentRepetitionIdentity && isBuiltInAgentTool(toolId) && !preserveToolDetails ? { inputsLink: scopeRepetitionRunData?.inputsLink ?? null, outputsLink: scopeRepetitionRunData?.outputsLink ?? null, } : {}), }, - runIndex: sameSelection ? (nodeMetadata.runIndex ?? 0) : 0, + runIndex: page, agentRepetitionIdentity, }; + // Restore the latest aggregate if a different invocation is selected before its details arrive. + if (selectedInvocation) { + nodeData.agentToolInvocation = { + ...selectedInvocation, + aggregate: { ...selectedInvocation.aggregate, ...summary } as LogicAppsV2.WorkflowRunAction, + }; + } else { + delete nodeData.agentToolInvocation; + } + if (pending?.runData) { + setToolInvocationRunData(nodeData as NodeMetadata, pending.invocation, pending.runData); + } state.nodesMetadata[toolId] = nodeData as NodeMetadata; } }); - const nodeMetadata = getRecordEntry(state.nodesMetadata, nodeId); + const nodeMetadata = agentMetadata; if (!nodeMetadata) { return; } @@ -630,6 +697,7 @@ export const workflowSlice = createSlice({ }; nodeMetadata.runData = nodeRunData as LogicAppsV2.WorkflowRunAction; nodeMetadata.agentRepetitionIdentity = agentRepetitionIdentity; + delete nodeMetadata.pendingBuiltInTool; nodeMetadata.actionCount = (agentGraph?.children ?? []).filter((node) => !containsIdTag(node.id) && !containsCaseTag(node.id))?.length ?? -1; @@ -840,7 +908,7 @@ export const workflowSlice = createSlice({ if (!nodeMetadata) { return; } - nodeMetadata.runIndex = page; + selectRunPage(nodeMetadata, page); }, setToolRunIndex: (state: WorkflowState, action: PayloadAction<{ page: number; nodeId: string }>) => { const { page, nodeId } = action.payload; @@ -848,26 +916,36 @@ export const workflowSlice = createSlice({ if (!nodeMetadata) { return; } + const invocation = nodeMetadata.agentToolInvocation; + if (nodeMetadata.subgraphType === SUBGRAPH_TYPES.MCP_CLIENT && invocation && invocation.page !== page) { + delete nodeMetadata.runData; + delete nodeMetadata.agentToolInvocation; + } nodeMetadata.toolRunIndex = page; }, - setRepetitionRunData: (state: WorkflowState, action: PayloadAction<{ nodeId: string; runData: LogicAppsV2.WorkflowRunAction }>) => { - const { nodeId, runData } = action.payload; + setRepetitionRunData: ( + state: WorkflowState, + action: PayloadAction<{ nodeId: string; runData: LogicAppsV2.WorkflowRunAction; agentToolInvocation?: AgentToolInvocation }> + ) => { + const { nodeId, runData, agentToolInvocation } = action.payload; const nodeMetadata = getRecordEntry(state.nodesMetadata, nodeId); if (!nodeMetadata) { return; } - const nodeRunData = { - ...runData, - inputsLink: runData?.inputsLink ?? null, - outputsLink: runData?.outputsLink ?? null, - duration: getDurationStringPanelMode(Date.parse(runData?.endTime) - Date.parse(runData?.startTime), /* abbreviated */ true), - }; - nodeMetadata.runData = nodeRunData as LogicAppsV2.WorkflowRunAction; + if (agentToolInvocation) { + // A late result must not be promoted to the currently selected page. + setToolInvocationRunData(nodeMetadata, agentToolInvocation, runData); + return; + } + delete nodeMetadata.agentToolInvocation; + nodeMetadata.runData = formatRepetitionRunData(runData); }, clearAllRepetitionRunData: (state: WorkflowState) => { for (const node of Object.values(state.nodesMetadata)) { + delete node.pendingBuiltInTool; if (node.agentRepetitionIdentity) { delete node.agentRepetitionIdentity; + delete node.agentToolInvocation; delete node.toolRunData; delete node.toolRunIndex; } @@ -879,8 +957,11 @@ export const workflowSlice = createSlice({ } } }, - setSubgraphRunData: (state: WorkflowState, action: PayloadAction<{ nodeId: string; runData: LogicAppsV2.RunRepetition[] }>) => { - const { nodeId, runData } = action.payload; + setSubgraphRunData: ( + state: WorkflowState, + action: PayloadAction<{ nodeId: string; runData: LogicAppsV2.RunRepetition[]; agentRepetitionIdentity?: string }> + ) => { + const { nodeId, runData, agentRepetitionIdentity } = action.payload; const nodeMetadata = getRecordEntry(state.nodesMetadata, nodeId); if (!nodeMetadata) { return; @@ -891,6 +972,11 @@ export const workflowSlice = createSlice({ return acc; }, {} as any); nodeMetadata.subgraphRunData = subgraph; + if (agentRepetitionIdentity) { + nodeMetadata.subgraphRunDataIdentity = agentRepetitionIdentity; + } else { + delete nodeMetadata.subgraphRunDataIdentity; + } }, setRunDataInputOutputs: ( state: WorkflowState, @@ -1198,8 +1284,51 @@ export const workflowSlice = createSlice({ }; nodeMetadata.runData = nodeRunData as LogicAppsV2.WorkflowRunAction; }); + builder.addCase(fetchBuiltInToolRunData.pending, (state, action) => { + const { agentNodeId, toolNodeId, runId, agentToolInvocation } = action.meta.arg; + if ( + !agentToolInvocation || + state.runInstance?.id !== runId || + getSelectedAgentRepetitionIdentity(state, agentNodeId) !== agentToolInvocation.agentRepetitionIdentity + ) { + return; + } + const node = getRecordEntry(state.nodesMetadata, toolNodeId); + if (node?.agentRepetitionIdentity === agentToolInvocation.agentRepetitionIdentity) { + selectRunPage(node, clampToolPage(agentToolInvocation.page, node.runData?.repetitionCount)); + return; + } + // Don't replace admitted tool details until the new Agent repetition is admitted. + const agent = getRecordEntry(state.nodesMetadata, agentNodeId); + if (agent) { + agent.pendingBuiltInTool = { toolNodeId, invocation: agentToolInvocation, requestId: action.meta.requestId }; + } + }); builder.addCase(fetchBuiltInToolRunData.fulfilled, (state, action) => { + if (!action.payload) { + return; // No action-level result exists for this scoped page yet. + } const { toolNodeId, inputsLink, outputsLink, inputs, outputs, startTime, endTime, status, correlation } = action.payload; + const runData = { inputsLink, outputsLink, inputs, outputs, startTime, endTime, status, correlation }; + const { agentNodeId, runId, agentToolInvocation } = action.meta?.arg ?? {}; + if (agentToolInvocation) { + if ( + state.runInstance?.id !== runId || + getSelectedAgentRepetitionIdentity(state, agentNodeId) !== agentToolInvocation.agentRepetitionIdentity + ) { + return; + } + const pending = getRecordEntry(state.nodesMetadata, agentNodeId)?.pendingBuiltInTool; + if (pending?.requestId === action.meta.requestId) { + pending.runData = runData; + return; + } + const node = getRecordEntry(state.nodesMetadata, toolNodeId); + if (node) { + setToolInvocationRunData(node, agentToolInvocation, runData); + } + return; + } // Create nodesMetadata entry if it doesn't exist (for built-in tools like code_interpreter) if (!state.nodesMetadata[toolNodeId]) { @@ -1208,14 +1337,7 @@ export const workflowSlice = createSlice({ state.nodesMetadata[toolNodeId].runData = { ...state.nodesMetadata[toolNodeId].runData, - inputsLink, - outputsLink, - inputs, - outputs, - startTime, - endTime, - status, - correlation, + ...runData, } as LogicAppsV2.WorkflowRunAction; }); builder.addCase(setStateAfterUndoRedo, (_, action: PayloadAction) => action.payload.workflow); diff --git a/libs/designer-v2/src/lib/core/utils/loopRepetitions.ts b/libs/designer-v2/src/lib/core/utils/loopRepetitions.ts index 66b7e1da99d..79eb04b0b59 100644 --- a/libs/designer-v2/src/lib/core/utils/loopRepetitions.ts +++ b/libs/designer-v2/src/lib/core/utils/loopRepetitions.ts @@ -13,3 +13,27 @@ export const getLoopsCount = (action: LogicAppsV2.WorkflowRunAction | undefined) } return typeof repetitionCount === 'number' ? repetitionCount : undefined; }; + +export const getScopeRepetitionName = (index: number | undefined): string => String(index).padStart(6, '0'); + +interface AgentRepetitionIdentityParams { + runId: string | undefined; + ownerNodeId: string | undefined; + repetitionName: string | undefined; + repetitionIndex: number | undefined; + parentStatus: string | undefined; +} + +/** Missing run or repetition data leaves the legacy/unscoped path unchanged. */ +export const getAgentRepetitionIdentity = ({ + runId, + ownerNodeId, + repetitionName, + repetitionIndex, + parentStatus, +}: AgentRepetitionIdentityParams): string | undefined => { + if (!runId || !ownerNodeId || repetitionName === undefined || repetitionIndex === undefined) { + return undefined; + } + return [runId, ownerNodeId, repetitionName, String(repetitionIndex), parentStatus ?? ''].join('|'); +}; diff --git a/libs/designer-v2/src/lib/ui/CustomNodes/OperationCardNode.tsx b/libs/designer-v2/src/lib/ui/CustomNodes/OperationCardNode.tsx index a6e3ec74052..3d7eee344c5 100644 --- a/libs/designer-v2/src/lib/ui/CustomNodes/OperationCardNode.tsx +++ b/libs/designer-v2/src/lib/ui/CustomNodes/OperationCardNode.tsx @@ -85,6 +85,7 @@ interface NodeRunDataSyncProps { graphId: string; parentNodeId?: string; isMcpClientSubgraph: boolean; + scopedAgentRepetitionIdentity?: string; selfActionTrackingId?: string; onFetchingChange: (isFetching: boolean) => void; } @@ -95,6 +96,7 @@ const NodeRunDataSync = ({ graphId, parentNodeId, isMcpClientSubgraph, + scopedAgentRepetitionIdentity, selfActionTrackingId, onFetchingChange, }: NodeRunDataSyncProps) => { @@ -106,7 +108,10 @@ const NodeRunDataSync = ({ const repetitionName = useRepetitionName(parentRunIndex, id, operationsInfo); const isWithinAgenticLoop = useIsWithinAgenticLoop(graphId); const parentSubgraphRunData = useSubgraphRunData(parentNodeId ?? ''); + const parentMetadata = useNodeMetadata(parentNodeId ?? ''); + const toolMetadata = useNodeMetadata(id); const toolRunIndex = useRunIndex(graphId); + const ownRunIndex = useRunIndex(id); const mcpToolRunIndex = useToolRunIndex(id); const { isFetching: isRepetitionFetching, data: repetitionRunData } = useNodeRepetition( @@ -138,21 +143,28 @@ const NodeRunDataSync = ({ } }, [dispatch, repetitionRunData, id, selfActionTrackingId]); - const actualToolRunIndex = isMcpClientSubgraph ? mcpToolRunIndex : toolRunIndex; + const actualToolRunIndex = isMcpClientSubgraph ? mcpToolRunIndex : scopedAgentRepetitionIdentity ? ownRunIndex : toolRunIndex; + const hasCurrentToolResults = + !scopedAgentRepetitionIdentity || + (parentMetadata?.subgraphRunDataIdentity === scopedAgentRepetitionIdentity && + toolMetadata?.agentRepetitionIdentity === scopedAgentRepetitionIdentity); useEffect(() => { - if (isWithinAgenticLoop && !isNullOrUndefined(actualToolRunIndex)) { + if (isWithinAgenticLoop && hasCurrentToolResults && !isNullOrUndefined(actualToolRunIndex)) { const subgraphRunData = parentSubgraphRunData?.[id]?.actionResults?.[actualToolRunIndex]; if (subgraphRunData) { dispatch( setRepetitionRunData({ nodeId: id, runData: subgraphRunData as LogicAppsV2.WorkflowRunAction, + ...(scopedAgentRepetitionIdentity && { + agentToolInvocation: { agentRepetitionIdentity: scopedAgentRepetitionIdentity, page: actualToolRunIndex }, + }), }) ); } } - }, [isWithinAgenticLoop, id, dispatch, actualToolRunIndex, parentSubgraphRunData]); + }, [isWithinAgenticLoop, id, dispatch, actualToolRunIndex, parentSubgraphRunData, hasCurrentToolResults, scopedAgentRepetitionIdentity]); return null; }; @@ -213,14 +225,18 @@ const DefaultNode = ({ id, data }: NodeProps) => { const shouldShowPager = hasMcpToolPager(metadata, parentActionMetadata?.type, isMonitoringView) && (!useScopedToolMonitoringData || hasCurrentToolMonitoringData); - // The direct MCP renderer owns a separate tool run from the underlying operation run. - const scopedRunData = useScopedToolMonitoringData - ? hasCurrentToolMonitoringData - ? isMcpClientSubgraph - ? metadata?.toolRunData - : selfRunData - : undefined - : selfRunData; + // MCP's aggregate drives the pager, but only the selected invocation can supply card details. + const invocation = metadata?.agentToolInvocation; + const hasCurrentMcpInvocation = + invocation && invocation.agentRepetitionIdentity === agentRepetitionIdentity && invocation.page === metadata?.toolRunIndex; + let scopedRunData = selfRunData; + if (useScopedToolMonitoringData) { + if (!hasCurrentToolMonitoringData) { + scopedRunData = undefined; + } else if (isMcpClientSubgraph) { + scopedRunData = (hasCurrentMcpInvocation ? selfRunData : undefined) ?? metadata?.toolRunData; + } + } const { dependencies, loopSources } = useTokenDependencies(id); @@ -506,6 +522,7 @@ const DefaultNode = ({ id, data }: NodeProps) => { graphId={graphId} parentNodeId={parentNodeId} isMcpClientSubgraph={metadata?.subgraphType === SUBGRAPH_TYPES.MCP_CLIENT} + scopedAgentRepetitionIdentity={useScopedToolMonitoringData ? agentRepetitionIdentity : undefined} selfActionTrackingId={selfRunData?.correlation?.actionTrackingId} onFetchingChange={setIsRepetitionFetching} /> diff --git a/libs/designer-v2/src/lib/ui/CustomNodes/ScopeCardNode.tsx b/libs/designer-v2/src/lib/ui/CustomNodes/ScopeCardNode.tsx index cf42f854a61..3eb67c39875 100644 --- a/libs/designer-v2/src/lib/ui/CustomNodes/ScopeCardNode.tsx +++ b/libs/designer-v2/src/lib/ui/CustomNodes/ScopeCardNode.tsx @@ -267,9 +267,14 @@ const ScopeCardNode = ({ id, data }: NodeProps) => { if (isNullOrUndefined(agentActionsRepetitionData)) { return; } - const updatePayload = { nodeId: scopeId, runData: agentActionsRepetitionData as LogicAppsV2.RunRepetition[] }; + // Child cards must not apply these results to a different Agent repetition's tool pages. + const updatePayload = { + nodeId: scopeId, + runData: agentActionsRepetitionData, + ...(agentRepetitionIdentity && { agentRepetitionIdentity }), + }; dispatch(setSubgraphRunData(updatePayload)); - }, [dispatch, agentRepetitionRunData, scopeId, agentActionsRepetitionData, isMonitoringView]); + }, [dispatch, agentRepetitionRunData, scopeId, agentActionsRepetitionData, isMonitoringView, agentRepetitionIdentity]); useEffect(() => { if (isMonitoringView && !isTimelineRepetitionSelected) { diff --git a/libs/designer-v2/src/lib/ui/CustomNodes/SubgraphCardNode.tsx b/libs/designer-v2/src/lib/ui/CustomNodes/SubgraphCardNode.tsx index a47d7201104..a17158c7fcd 100644 --- a/libs/designer-v2/src/lib/ui/CustomNodes/SubgraphCardNode.tsx +++ b/libs/designer-v2/src/lib/ui/CustomNodes/SubgraphCardNode.tsx @@ -125,6 +125,11 @@ const SubgraphCardNode = ({ id, data }: NodeProps) => { ); const useScopedToolMonitoringData = shared && sharedTool && isMonitoringView && !isA2AWorkflow && !!agentRepetitionIdentity; const hasCurrentToolMonitoringData = !useScopedToolMonitoringData || metadata?.agentRepetitionIdentity === agentRepetitionIdentity; + const pendingTool = nodesMetadata[graphId]?.pendingBuiltInTool; + const hasPendingToolSelection = + useScopedToolMonitoringData && + pendingTool?.toolNodeId === subgraphId && + pendingTool.invocation.agentRepetitionIdentity === agentRepetitionIdentity; const effectiveToolRunData = useScopedToolMonitoringData && !hasCurrentToolMonitoringData ? undefined : (metadata?.toolRunData ?? metadata?.runData); @@ -249,14 +254,25 @@ const SubgraphCardNode = ({ id, data }: NodeProps) => { dispatch(setFocusNode(newAdditiveSubgraphId)); } else { dispatch(changePanelNode(_id)); - // For built-in tools in monitoring view, fetch inputs/outputs if not already loaded - if (isMonitoringView && isBuiltInAgentTool(_id) && !metadata?.runData?.inputs && runInstance?.id && graphId) { + // Opening the card must not replace a chat-selected invocation with the fallback page while its summary loads. + if ( + isMonitoringView && + isBuiltInAgentTool(_id) && + !hasPendingToolSelection && + (!hasCurrentToolMonitoringData || !metadata?.runData?.inputs) && + runInstance?.id && + graphId + ) { dispatch( fetchBuiltInToolRunData({ toolNodeId: _id, agentNodeId: graphId, runId: runInstance.id, - repetitionName: getScopeRepetitionName(agentRunIndex), + repetitionName: scopeRepetitionName, + ...(useScopedToolMonitoringData && + agentRepetitionIdentity && { + agentToolInvocation: { agentRepetitionIdentity, page: hasCurrentToolMonitoringData ? (metadata?.runIndex ?? 0) : 0 }, + }), }) ); } @@ -274,7 +290,11 @@ const SubgraphCardNode = ({ id, data }: NodeProps) => { isMonitoringView, metadata, runInstance, - agentRunIndex, + scopeRepetitionName, + agentRepetitionIdentity, + hasCurrentToolMonitoringData, + hasPendingToolSelection, + useScopedToolMonitoringData, ] ); diff --git a/libs/designer-v2/src/lib/ui/CustomNodes/__test__/OperationCardNode.spec.tsx b/libs/designer-v2/src/lib/ui/CustomNodes/__test__/OperationCardNode.spec.tsx index 51dec4f0163..c853a775d9b 100644 --- a/libs/designer-v2/src/lib/ui/CustomNodes/__test__/OperationCardNode.spec.tsx +++ b/libs/designer-v2/src/lib/ui/CustomNodes/__test__/OperationCardNode.spec.tsx @@ -447,6 +447,43 @@ describe('OperationCardNode (v2)', () => { expect(screen.getByRole('button')).toHaveAttribute('data-status', 'succeeded'); }); + it('renders only the current shared MCP invocation and keeps the aggregate pager count', () => { + const identity = 'run-1|actual-agent|000002|2|'; + const runData = { status: 'Succeeded', duration: '2s' }; + const metadata = { + graphId: 'actual-agent', + parentNodeId: 'actual-agent', + subgraphType: 'MCP_CLIENT', + toolRunData: { status: 'Failed', repetitionCount: 3 }, + toolRunIndex: 1, + agentRepetitionIdentity: identity, + agentToolInvocation: { agentRepetitionIdentity: identity, page: 1 }, + runData, + }; + mockUseSharedNodeUi.mockReturnValue(true); + mockUseMonitoringView.mockReturnValue(true); + mockUseRunInstance.mockReturnValue({ id: 'run-1' }); + mockUseRunIndex.mockReturnValue(2); + mockUseParentNodeId.mockImplementation((id?: string) => (id === 'testNode' ? 'actual-agent' : undefined)); + mockUseActionMetadata.mockImplementation((id?: string) => (id === 'actual-agent' ? { type: 'Agent' } : undefined)); + mockUseRunData.mockImplementation((id?: string) => (id === 'testNode' ? runData : undefined)); + mockUseNodeMetadata.mockReturnValue(metadata); + + const { rerender } = render(); + expect(screen.getByRole('button', { name: /Succeeded.*2s/i })).toHaveAttribute('data-status', 'succeeded'); + expect(screen.getByTestId('shared-loops-pager-testNode')).toBeInTheDocument(); + + mockUseNodeMetadata.mockReturnValue({ ...metadata, toolRunIndex: 2 }); + rerender(); + expect(screen.getByRole('button', { name: /Failed/i })).toHaveAttribute('data-status', 'failed'); + expect(screen.queryByText('2s')).not.toBeInTheDocument(); + + mockUseRunInstance.mockReturnValue({ id: 'run-2' }); + rerender(); + expect(screen.getByRole('button')).not.toHaveAttribute('data-status'); + expect(screen.queryByTestId('shared-loops-pager-testNode')).not.toBeInTheDocument(); + }); + it('updates run data when the selected repetition response has no actionTrackingId', () => { mockUseMonitoringView.mockReturnValue(true); mockUseRunInstance.mockReturnValue({ id: 'run-1' }); diff --git a/libs/designer-v2/src/lib/ui/CustomNodes/__test__/SubgraphCardNode.spec.tsx b/libs/designer-v2/src/lib/ui/CustomNodes/__test__/SubgraphCardNode.spec.tsx index 4797d73fa2b..f64fc50b0e1 100644 --- a/libs/designer-v2/src/lib/ui/CustomNodes/__test__/SubgraphCardNode.spec.tsx +++ b/libs/designer-v2/src/lib/ui/CustomNodes/__test__/SubgraphCardNode.spec.tsx @@ -203,6 +203,7 @@ vi.mock('../components/card/subgraphCard', () => ({ })); import SubgraphCardNode from '../SubgraphCardNode'; +import { fetchBuiltInToolRunData } from '../../../core/actions/bjsworkflow/monitoring'; describe('SubgraphCardNode (v2)', () => { const defaultProps = { id: 'testNode-#subgraph' } as NodeProps; @@ -262,6 +263,45 @@ describe('SubgraphCardNode (v2)', () => { expect(mockDispatch).toHaveBeenCalledWith({ type: 'panel/changePanelNode', payload: 'testNode' }); }); + it.each([false, true])( + 'opens built-in tool details and only fetches if the current repetition has no pending selection (%s)', + (pending) => { + mockUseSharedNodeUi.mockReturnValue(true); + mockUseMonitoringView.mockReturnValue(true); + mockUseRunInstance.mockReturnValue({ id: 'run' }); + mockUseRunIndex.mockReturnValue(1); + mockUseNodeMetadata.mockReturnValue({ + graphId: 'Agent', + subgraphType: SUBGRAPH_TYPES.AGENT_CONDITION, + agentRepetitionIdentity: 'run|Agent|000000|0|', + }); + mockUseNodesMetadata.mockReturnValue({ + Agent: { + pendingBuiltInTool: { + toolNodeId: 'code_interpreter', + invocation: { agentRepetitionIdentity: pending ? 'run|Agent|000001|1|' : 'run|Agent|000000|0|', page: 2 }, + requestId: 'chat-request', + }, + }, + }); + const { container } = render(); + fireEvent.click(container.querySelector('[data-node-card="tool"]')!); + + expect(mockDispatch).toHaveBeenCalledWith({ type: 'panel/changePanelNode', payload: 'code_interpreter' }); + if (pending) { + expect(fetchBuiltInToolRunData).not.toHaveBeenCalled(); + } else { + expect(fetchBuiltInToolRunData).toHaveBeenCalledWith({ + toolNodeId: 'code_interpreter', + agentNodeId: 'Agent', + runId: 'run', + repetitionName: '000001', + agentToolInvocation: { agentRepetitionIdentity: 'run|Agent|000001|1|', page: 0 }, + }); + } + } + ); + it('opts shared condition false branches into the neutral identity without changing legacy defaults', () => { mockUseSharedNodeUi.mockReturnValue(true); mockUseNodeMetadata.mockReturnValue({ graphId: 'graph1', subgraphType: SUBGRAPH_TYPES.CONDITIONAL_FALSE, actionCount: 0 }); diff --git a/libs/designer-v2/src/lib/ui/common/LoopsPager/helper.ts b/libs/designer-v2/src/lib/ui/common/LoopsPager/helper.ts index 5100f869227..918afba3b52 100644 --- a/libs/designer-v2/src/lib/ui/common/LoopsPager/helper.ts +++ b/libs/designer-v2/src/lib/ui/common/LoopsPager/helper.ts @@ -6,7 +6,7 @@ import { getAllParentsForNode } from '../../../core/utils/graph'; import { getRecordEntry } from '@microsoft/logic-apps-shared'; import { useSelector } from 'react-redux'; -export { getLoopsCount } from '../../../core/utils/loopRepetitions'; +export { getAgentRepetitionIdentity, getLoopsCount, getScopeRepetitionName } from '../../../core/utils/loopRepetitions'; /** * Gets repetition name for API call. @@ -35,41 +35,6 @@ export const getRepetitionName = ( return repetitionName; }; -/** - * Gets repetition name for API call. - * @param {number | undefined} index - Node's parent loop index. - * @returns {string} Repetition name. - */ -export const getScopeRepetitionName = (index: number | undefined): string => { - return String(index).padStart(6, '0'); -}; - -interface AgentRepetitionIdentityParams { - runId: string | undefined; - ownerNodeId: string | undefined; - repetitionName: string | undefined; - repetitionIndex: number | undefined; - parentStatus: string | undefined; -} - -/** - * Builds the authoritative identity used to scope agent monitoring data to a specific selected iteration. - * If the run identity is unavailable (legacy/synthetic paths), we intentionally skip scoping and keep - * existing behavior unchanged. - */ -export const getAgentRepetitionIdentity = ({ - runId, - ownerNodeId, - repetitionName, - repetitionIndex, - parentStatus, -}: AgentRepetitionIdentityParams): string | undefined => { - if (!runId || !ownerNodeId || repetitionName === undefined || repetitionIndex === undefined) { - return undefined; - } - return [runId, ownerNodeId, repetitionName, String(repetitionIndex), parentStatus ?? ''].join('|'); -}; - /** * Hook that computes the repetition name inside a selector. * Returns a string primitive, so useSelector's default === comparison diff --git a/libs/designer-v2/src/lib/ui/panel/runHistoryPanel/__test__/agentChatContent.spec.tsx b/libs/designer-v2/src/lib/ui/panel/runHistoryPanel/__test__/agentChatContent.spec.tsx index ea40d8bfe5a..ab621ecaf45 100644 --- a/libs/designer-v2/src/lib/ui/panel/runHistoryPanel/__test__/agentChatContent.spec.tsx +++ b/libs/designer-v2/src/lib/ui/panel/runHistoryPanel/__test__/agentChatContent.spec.tsx @@ -2,8 +2,10 @@ import { describe, expect, it, vi, beforeEach } from 'vitest'; // Mock all external dependencies before importing the component const mockDispatch = vi.fn(); +const mockStore = { getState: () => ({ workflow: {} }) }; vi.mock('react-redux', () => ({ useDispatch: () => mockDispatch, + useStore: () => mockStore, })); vi.mock('react-intl', () => ({ @@ -24,15 +26,20 @@ vi.mock('../../../../core/queries/runs', () => ({ vi.mock('../../../../core/state/designerOptions/designerOptionsSelectors', () => ({ useMonitoringView: vi.fn(() => true), + useSharedNodeUi: vi.fn(() => false), })); -vi.mock('../../../../core/state/workflow/workflowSelectors', () => ({ - useAgentLastOperations: vi.fn(() => ({})), - useAgentOperations: vi.fn(() => []), - useFocusElement: vi.fn(() => undefined), - useUriForAgentChat: vi.fn(() => undefined), - useRunInstance: vi.fn(() => ({ id: 'run-123', properties: { status: 'Succeeded' } })), -})); +vi.mock('../../../../core/state/workflow/workflowSelectors', () => { + const run = { id: 'run-123', properties: { status: 'Succeeded' } }; + return { + getSelectedAgentRepetitionIdentity: vi.fn(() => 'run-123|Agent|000001|1|'), + useAgentLastOperations: vi.fn(() => ({})), + useAgentOperations: vi.fn(() => []), + useFocusElement: vi.fn(() => undefined), + useUriForAgentChat: vi.fn(() => undefined), + useRunInstance: vi.fn(() => run), + }; +}); vi.mock('../../../../core/state/designerView/designerViewSelectors', () => ({ useIsA2AWorkflow: vi.fn(() => false), @@ -84,30 +91,41 @@ vi.mock('@fluentui/react-components', () => ({ })); import React from 'react'; -import { renderHook } from '@testing-library/react'; +import { act, render, renderHook } from '@testing-library/react'; import { changePanelNode } from '../../../../core'; import { setFocusNode, setRunIndex } from '../../../../core/state/workflow/workflowSlice'; import { fetchBuiltInToolRunData } from '../../../../core/actions/bjsworkflow/monitoring'; -import { useRunInstance, useAgentLastOperations } from '../../../../core/state/workflow/workflowSelectors'; +import { useRunInstance } from '../../../../core/state/workflow/workflowSelectors'; +import { useChatHistory } from '../../../../core/queries/runs'; +import { useSharedNodeUi } from '../../../../core/state/designerOptions/designerOptionsSelectors'; +import { parseChatHistory } from '../../agentChat/helper'; describe('AgentChatContent - toolResultCallback', () => { beforeEach(() => { vi.clearAllMocks(); }); - it('should dispatch fetchBuiltInToolRunData for built-in tools like code_interpreter', async () => { - // Import the component module to test the callback behavior + it.each([false, true])('selects a built-in chat result without changing an old Shared tool page (Shared: %s)', async (shared) => { + vi.mocked(useSharedNodeUi).mockReturnValue(shared); + vi.mocked(useChatHistory, { partial: true }).mockReturnValue({ data: [] }); const { AgentChatContent } = await import('../agentChatContent'); - - // We test the toolResultCallback logic by verifying it dispatches correctly for built-in tools - // The key behavior: isBuiltInAgentTool('code_interpreter') returns true, - // so it should dispatch fetchBuiltInToolRunData + setFocusNode + changePanelNode - - // Since we can't easily extract the callback from the component, - // we verify the imports and mock setup are correct - expect(fetchBuiltInToolRunData).toBeDefined(); - expect(changePanelNode).toBeDefined(); - expect(setFocusNode).toBeDefined(); + render(); + const [, selectTool] = vi.mocked(parseChatHistory).mock.calls[0]; + act(() => selectTool('Agent', 'code_interpreter', 1, 2)); + + expect(vi.mocked(setRunIndex).mock.calls.map(([selection]) => selection)).toEqual([ + { page: 1, nodeId: 'Agent' }, + ...(!shared ? [{ page: 2, nodeId: 'code_interpreter' }] : []), + ]); + expect(fetchBuiltInToolRunData).toHaveBeenCalledWith({ + toolNodeId: 'code_interpreter', + agentNodeId: 'Agent', + runId: 'run-123', + repetitionName: '000001', + ...(shared && { agentToolInvocation: { agentRepetitionIdentity: 'run-123|Agent|000001|1|', page: 2 } }), + }); + expect(changePanelNode).toHaveBeenCalledWith('code_interpreter'); + expect(setFocusNode).toHaveBeenCalledWith('code_interpreter'); }); it('should have correct run instance available for built-in tool data fetching', () => { diff --git a/libs/designer-v2/src/lib/ui/panel/runHistoryPanel/agentChatContent.tsx b/libs/designer-v2/src/lib/ui/panel/runHistoryPanel/agentChatContent.tsx index c1622092391..f2f639ecaf0 100644 --- a/libs/designer-v2/src/lib/ui/panel/runHistoryPanel/agentChatContent.tsx +++ b/libs/designer-v2/src/lib/ui/panel/runHistoryPanel/agentChatContent.tsx @@ -3,8 +3,9 @@ import { useCallback, useEffect, useMemo, useState } from 'react'; import { useIntl } from 'react-intl'; import { ChatbotUI } from '@microsoft/logic-apps-chatbot'; import { useAgentChatInvokeUri, useCancelRun, useChatHistory } from '../../../core/queries/runs'; -import { useMonitoringView } from '../../../core/state/designerOptions/designerOptionsSelectors'; +import { useMonitoringView, useSharedNodeUi } from '../../../core/state/designerOptions/designerOptionsSelectors'; import { + getSelectedAgentRepetitionIdentity, useAgentLastOperations, useAgentOperations, useFocusElement, @@ -13,8 +14,9 @@ import { } from '../../../core/state/workflow/workflowSelectors'; import { isNullOrUndefined, isBuiltInAgentTool, LogEntryLevel, LoggerService, RunService } from '@microsoft/logic-apps-shared'; import { Button, Dialog, DialogActions, DialogBody, DialogContent, DialogTitle, DialogTrigger } from '@fluentui/react-components'; -import { useDispatch } from 'react-redux'; +import { useDispatch, useStore } from 'react-redux'; import { changePanelNode, type AppDispatch } from '../../../core'; +import type { RootState } from '../../../core/store'; import { clearFocusElement, setFocusNode, @@ -41,6 +43,8 @@ export const AgentChatContent = () => { const agentOperations = useAgentOperations(); const agentLastOperations = useAgentLastOperations(agentOperations); const isA2AWorkflow = useIsA2AWorkflow(); + const shared = useSharedNodeUi(); + const store = useStore(); const agentChatSuffixUri = useUriForAgentChat(conversation.length > 0 ? conversation[0].metadata?.parentId : undefined); const focusElement = useFocusElement(); const { mutateAsync: refreshChat } = useRefreshChatMutation(); @@ -80,28 +84,32 @@ export const AgentChatContent = () => { const toolResultCallback = useCallback( (agentName: string, toolName: string, iteration: number, subIteration: number, mcpToolName?: string) => { const agentLastOperation = JSON.parse(rawAgentLastOperations)?.[agentName]?.[toolName]; + const isBuiltInTool = isBuiltInAgentTool(toolName); + const scopedBuiltInTool = shared && !isA2AWorkflow && isBuiltInTool && !!runInstance?.id; if (isA2AWorkflow) { dispatch(setTimelineRepetitionIndex(iteration)); } else { dispatch(setRunIndex({ page: iteration, nodeId: agentName })); - if (mcpToolName) { - dispatch(setToolRunIndex({ page: subIteration, nodeId: toolName })); - } else { - dispatch(setRunIndex({ page: subIteration, nodeId: toolName })); + if (!scopedBuiltInTool) { + dispatch((mcpToolName ? setToolRunIndex : setRunIndex)({ page: subIteration, nodeId: toolName })); } } // For built-in tools (e.g. code_interpreter), there is no child operation in the graph. // Navigate to the tool node itself and fetch its run data from the parent agent repetition. - if (isBuiltInAgentTool(toolName)) { + if (isBuiltInTool) { const repetitionName = String(iteration).padStart(6, '0'); if (runInstance?.id) { + const agentRepetitionIdentity = scopedBuiltInTool + ? getSelectedAgentRepetitionIdentity(store.getState().workflow, agentName) + : undefined; dispatch( fetchBuiltInToolRunData({ toolNodeId: toolName, agentNodeId: agentName, runId: runInstance.id, repetitionName, + ...(agentRepetitionIdentity && { agentToolInvocation: { agentRepetitionIdentity, page: subIteration } }), }) ); } @@ -112,7 +120,7 @@ export const AgentChatContent = () => { dispatch(changePanelNode(agentLastOperation)); } }, - [dispatch, isA2AWorkflow, rawAgentLastOperations, runInstance] + [dispatch, isA2AWorkflow, rawAgentLastOperations, runInstance, shared, store] ); const toolContentCallback = useCallback( diff --git a/libs/designer-v2/src/lib/ui/panel/runTreeView/TreeActionItem.tsx b/libs/designer-v2/src/lib/ui/panel/runTreeView/TreeActionItem.tsx index da25df8838e..640bc836e80 100644 --- a/libs/designer-v2/src/lib/ui/panel/runTreeView/TreeActionItem.tsx +++ b/libs/designer-v2/src/lib/ui/panel/runTreeView/TreeActionItem.tsx @@ -225,6 +225,11 @@ export const TreeActionItem = ({ id, content, icon, repetitionName, treeItemProp const agentNodeId = data?.repetition?.properties?.repetitionIndexes?.[0]?.scopeName; const parentRepetitionName = data?.parentRepetition?.name; if (agentNodeId && selectedRun?.id && parentRepetitionName) { + if (useScopedAgentData && repetitionIndex?.itemIndex !== undefined) { + // Commit the parent selection before the request starts (which dispatches pending synchronously). + dispatch(setRunIndex({ nodeId: agentNodeId, page: repetitionIndex.itemIndex })); + } + const agentRepetitionIdentity = getSelectionIdentity(repetitionIndex?.itemIndex); dispatch( fetchBuiltInToolRunData({ toolNodeId: id, @@ -233,6 +238,7 @@ export const TreeActionItem = ({ id, content, icon, repetitionName, treeItemProp repetitionName: parentRepetitionName, inputsLink: data?.inputsLink, outputsLink: data?.outputsLink, + ...(agentRepetitionIdentity && { agentToolInvocation: { agentRepetitionIdentity, page: itemRunIndex } }), }) ); }