diff --git a/Localize/lang/strings.json b/Localize/lang/strings.json index 39f84014fcb..5096f73b099 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", @@ -846,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", @@ -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", @@ -2016,6 +2022,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 +2109,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 +2206,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 +2571,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 +2721,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", @@ -2866,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", @@ -3276,6 +3288,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", @@ -4036,6 +4049,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 +4473,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", @@ -4535,9 +4550,11 @@ "_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", + "_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 +4718,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 +5913,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", @@ -5971,9 +5990,11 @@ "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", + "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/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..ff733fa3d33 --- /dev/null +++ b/e2e/designer/sharedNodeUiOverview.spec.ts @@ -0,0 +1,155 @@ +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 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); + 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..14235572d18 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,89 @@ 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'); + 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); + } + 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 +213,177 @@ 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+(?:\\/actions)?\\?/.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]\?/; + 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') { + 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 } }), + ...(flag === 'true' && repetition === '000000' && { code_interpreter: { status: 'Failed', iterations: 2 } }), + }, + }, + }, + }); + }); + 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 ['Regular_Tool', 'Managed_MCP_Server']) { + await expect(card(id)).toHaveAttribute('data-status', 'succeeded'); + } + 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(); + 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); 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..ad54ff64bb6 --- /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]': { + // The title owns its line height so a three-line card still fits the reserved bounds. + fontSize: tokens.fontSizeBase400, + }, + '& [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..40c2211dbd8 --- /dev/null +++ b/libs/designer-ui-v2/src/nodes/primitives/LoopBodyJoin.tsx @@ -0,0 +1,53 @@ +import { makeStyles, tokens } from '@fluentui/react-components'; +import { NodeLine } from './NodeLine'; + +const useStyles = makeStyles({ + join: { + position: 'absolute', + transform: 'translateX(-50%)', + pointerEvents: 'none', + }, + 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-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, + 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..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 @@ -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,128 @@ 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('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' }); + 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 +687,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..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 @@ -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', () => ({ @@ -181,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; @@ -201,6 +224,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 +263,53 @@ 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 }); + 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 +406,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 +647,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..918afba3b52 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 { getAgentRepetitionIdentity, getLoopsCount, getScopeRepetitionName } from '../../../core/utils/loopRepetitions'; /** * Gets repetition name for API call. @@ -64,15 +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'); -}; - /** * 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/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 5a2259ca0f0..640bc836e80 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, }) @@ -196,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, @@ -204,6 +238,7 @@ export const TreeActionItem = ({ id, content, icon, repetitionName, treeItemProp repetitionName: parentRepetitionName, inputsLink: data?.inputsLink, outputsLink: data?.outputsLink, + ...(agentRepetitionIdentity && { agentToolInvocation: { agentRepetitionIdentity, page: itemRunIndex } }), }) ); } @@ -217,7 +252,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,