diff --git a/.github/workflows/pr-coverage.yml b/.github/workflows/pr-coverage.yml index c04d9eb7146..86e74ce2198 100644 --- a/.github/workflows/pr-coverage.yml +++ b/.github/workflows/pr-coverage.yml @@ -86,6 +86,8 @@ jobs: **/*Models.ts **/*Interface.ts **/*Interfaces.ts + **/interfaces.ts + **/interfaces.tsx **/types.ts **/types.tsx **/styles.ts diff --git a/Localize/lang/strings.json b/Localize/lang/strings.json index 5096f73b099..67a005b9e8e 100644 --- a/Localize/lang/strings.json +++ b/Localize/lang/strings.json @@ -399,9 +399,11 @@ "5LV34t": "The ''{invalidProperties}'' properties are invalid for the ''{authType}'' authentication type.", "5N/tfe": "Extraction progress details", "5OvGgn": "Body", + "5QUuaP": "Jump to failed iteration", "5R1r3q": "Create a new connection", "5SAQOb": "Authority", "5Tqzsm": "Categorization", + "5UmjLL": "Failed…", "5Vbd0e": "Select a knowledge hub", "5VhY2X": "Loading models...", "5WTRY8": "Errors", @@ -654,6 +656,7 @@ "9emgHc": "Specify which HTTP status codes should trigger a retry. Select one or more status codes.", "9euy52": "Complete", "9gb/xS": "Create", + "9hDI1a": "Failed iteration {iteration}", "9hKeBq": "Select an Azure OpenAI resource", "9iYe3N": "The designer does not support workflows with multiple triggers. Use Run details to view this run.", "9klmbJ": "Save", @@ -1966,6 +1969,7 @@ "YoQara": "None", "YpTC5c": "Status", "YqKlGx": "Connect to external services and applications", + "YrNXP1": "Failed iterations {first} to {last}", "Yrw/Qt": "Your personal and company data are protected in this chat", "YsOyuE": "Create agent parameter", "Yskw5t": "Add Action", @@ -2426,9 +2430,11 @@ "_5LV34t.comment": "Error message when having multiple invalid authentication properties", "_5N/tfe.comment": "Keyboard-scrollable extraction milestones and contextual recovery details", "_5OvGgn.comment": "The title of the body field in the static result query action", + "_5QUuaP.comment": "Accessible name and tooltip for failed-iteration destination select in the loop pager", "_5R1r3q.comment": "Button text to create a new connection", "_5SAQOb.comment": "Authority Label Display Name", "_5Tqzsm.comment": "Categorization section title", + "_5UmjLL.comment": "Visible compact prompt text for failed-iteration destination select in the loop pager", "_5Vbd0e.comment": "Placeholder text for knowledge hub dropdown", "_5VhY2X.comment": "Placeholder while models load for create form", "_5WTRY8.comment": "The tab label for the errors tab on the errors panel", @@ -2681,6 +2687,7 @@ "_9emgHc.comment": "tooltip for retry policy HTTP status codes setting", "_9euy52.comment": "Text to indicate that the artifact upload is completed", "_9gb/xS.comment": "Button text for creating a group", + "_9hDI1a.comment": "Option label for a failed loop iteration destination in the loop pager", "_9hKeBq.comment": "Select the Azure Cognitive Service Open AI resource to use for this connection", "_9iYe3N.comment": "Message shown instead of the designer canvas when a Consumption workflow definition has more than one trigger and a run is selected in monitoring view. The backend supports the workflow, but the designer cannot render it; the Run details action opens the full run experience.", "_9klmbJ.comment": "Button text for saving changes for parameter in the customize parameter panel", @@ -3993,6 +4000,7 @@ "_YoQara.comment": "Display text for when About Panel has no Tags", "_YpTC5c.comment": "Label for the status column", "_YqKlGx.comment": "Action in an app category description", + "_YrNXP1.comment": "Submenu label for a range of failed loop iteration destinations", "_Yrw/Qt.comment": "Letting user know that their data is protected in the chatbot", "_YsOyuE.comment": "Create agent parameter", "_Yskw5t.comment": "Text on example action node", diff --git a/e2e/designer/sharedNodeUiConnections.spec.ts b/e2e/designer/sharedNodeUiConnections.spec.ts index 42aa5dbaf3e..8990d9dfce4 100644 --- a/e2e/designer/sharedNodeUiConnections.spec.ts +++ b/e2e/designer/sharedNodeUiConnections.spec.ts @@ -60,6 +60,41 @@ for (const flag of ['true', 'false'] as const) { expect((await getSerializedWorkflowFromStateV2(page)).definition.actions).toEqual(before.definition.actions); }); + if (flag === 'true') { + test('restores the serialized branch DAG with one Undo after duplicating a nested Scope', async ({ page }) => { + await openSharedWorkflow(page, 'All Scope Nodes', flag); + const readActions = async () => (await getSerializedWorkflowFromStateV2(page)).definition.actions; + const readScopeBody = async () => (await readActions()).Switch.cases.Scope_Case.actions.Scope.actions; + const before = await readActions(); + const scopeBody = before.Switch.cases.Scope_Case.actions.Scope.actions; + const undo = page.getByRole('button', { name: 'Undo', exact: true }); + await expect(undo).toBeDisabled(); + + const nestedScope = page.locator('#msla-node-Scope_nested'); + await nestedScope.press('Enter'); + await nestedScope.focus(); + await page.keyboard.press('ControlOrMeta+d'); + await expect.poll(async () => Object.keys(await readScopeBody()).length).toBe(Object.keys(scopeBody).length + 1); + const after = await readScopeBody(); + const duplicateId = Object.keys(after).find((id) => !scopeBody[id]); + if (!duplicateId) { + throw new Error('Duplicate must add a new Scope inside the original branch.'); + } + expect(after[duplicateId].type).toBe('Scope'); + expect(after[duplicateId].runAfter).toEqual({ Scope_nested: ['SUCCEEDED'] }); + expect(after.Scope_empty.runAfter).toEqual({ + [duplicateId]: scopeBody.Scope_empty.runAfter.Scope_nested, + }); + await expect + .poll(async () => Object.values((await readScopeBody())[duplicateId].actions ?? {})) + .toEqual(Object.values(scopeBody.Scope_nested.actions)); + + await undo.click(); + await expect.poll(readActions).toEqual(before); + await expect(undo).toBeDisabled(); + }); + } + 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'); diff --git a/e2e/designer/sharedNodeUiForeachFailureMenu.spec.ts b/e2e/designer/sharedNodeUiForeachFailureMenu.spec.ts new file mode 100644 index 00000000000..fa77607e32a --- /dev/null +++ b/e2e/designer/sharedNodeUiForeachFailureMenu.spec.ts @@ -0,0 +1,158 @@ +import { expect, test } from '@playwright/test'; +import { openSharedWorkflow, waitForViewport } from './utils/sharedNodeUi'; + +const scopeRunId = '/foreach-failure-menu-run'; +const scopeRepetitions = `/url${scopeRunId}/actions/Foreach/scopeRepetitions`; +const times = { startTime: '2026-01-01T00:00:00Z', endTime: '2026-01-01T00:00:01Z' }; + +test( + 'jumps between confirmed Foreach failures by keyboard without clipping the pager or covering the outgoing edge', + { + tag: ['@mock', '@shared-node-ui'], + }, + async ({ page }) => { + // Dev-mode StandardRunService returns no failed repetitions before calling HTTP. Exercise the real + // Standard request builder on the fixture only; all other run service calls stay in Local dev mode. + await page.route(/\/LocalDesigner\/localDesignerV2\.tsx(?:\?|$)/, async (route) => { + const response = await route.fetch(); + await route.fulfill({ + response, + body: `${await response.text()} + const fixtureRunService = new runService.constructor({ + ...runService.options, + isDev: false, + httpClient: { + async get({ uri, queryParameters }) { + const url = new URL(uri, window.location.origin); + url.search = new URLSearchParams(queryParameters).toString(); + const response = await fetch(url); + if (!response.ok) throw new Error("Foreach fixture returned HTTP " + response.status); + return response.json(); + }, + }, + }); + const originalGetScopeRepetitions = runService.getScopeRepetitions.bind(runService); + runService.getScopeRepetitions = (action, status) => + action.runId === ${JSON.stringify(scopeRunId)} && action.nodeId === "Foreach" && status === "Failed" + ? fixtureRunService.getScopeRepetitions(action, status) + : originalGetScopeRepetitions(action, status);`, + }); + }); + await page.route( + (url) => url.pathname === scopeRepetitions, + (route) => + route.fulfill({ + json: { + value: [1, 5].map((itemIndex) => ({ + id: `${scopeRunId}/actions/Foreach/scopeRepetitions/${String(itemIndex).padStart(6, '0')}`, + properties: { ...times, status: 'Failed', repetitionIndexes: [{ scopeName: 'Foreach', itemIndex }] }, + })), + }, + }) + ); + + await openSharedWorkflow(page, 'ForEach'); + await page.evaluate(() => { + const store = window.DesignerStoreV2; + store.dispatch({ + type: 'designerOptions/initDesignerOptions', + payload: { ...store.getState().designerOptions, isMonitoringView: true, readOnly: true }, + }); + }); + const history = page.locator('.fui-InlineDrawer').filter({ has: page.getByRole('heading', { name: 'Run history', exact: true }) }); + await history.locator('.fui-DrawerHeaderNavigation button').click(); + await expect(history).toBeHidden(); + + const [filteredRequest] = await Promise.all([ + page.waitForRequest((request) => new URL(request.url()).pathname === scopeRepetitions), + page.evaluate( + ({ scopeRunId, times }) => { + const store = window.DesignerStoreV2; + store.dispatch({ type: 'workflow/setRunIndex', payload: { nodeId: 'Foreach', page: 3 } }); + store.dispatch({ + type: 'workflow/setRepetitionRunData', + payload: { nodeId: 'Foreach', runData: { ...times, status: 'Failed', iterationCount: 123456 } }, + }); + store.dispatch({ + type: 'workflow/setRunInstance', + payload: { id: scopeRunId, name: scopeRunId.slice(1), properties: { status: 'Failed' } }, + }); + }, + { scopeRunId, times } + ), + ]); + const query = new URL(filteredRequest.url()).searchParams; + expect(query.get('$filter')).toBe("status eq 'Failed'"); + expect(query.get('api-version')).toBe('2018-11-01'); + + await page.getByRole('button', { name: 'Zoom view to fit', exact: true }).click(); + await waitForViewport(page); + + const card = page.locator('#msla-node-Foreach[data-node-card="foreach"]'); + const row = card.locator('[data-loop-pager-row]'); + const pager = row.getByRole('group', { name: 'Iterations', exact: true }); + const number = pager.getByRole('textbox', { name: /Iteration number, 1 to 123[,\s]?456/ }); + const chooser = pager.getByRole('button', { name: 'Jump to failed iteration', exact: true }); + await expect(number).toHaveValue('4'); + await expect(chooser).toHaveAttribute('aria-haspopup', 'menu'); + await expect(pager.getByRole('combobox')).toHaveCount(0); + + await chooser.press('ArrowDown'); + const menu = page.getByRole('menu').filter({ has: page.getByRole('menuitem', { name: 'Failed iteration 2', exact: true }) }); + const previousFailure = menu.getByRole('menuitem', { name: 'Previous failed iteration', exact: true }); + const nextFailure = menu.getByRole('menuitem', { name: 'Next failed iteration', exact: true }); + await expect(menu.getByRole('menuitem')).toHaveText([ + 'Previous failed iteration', + 'Next failed iteration', + 'Failed iteration 2', + 'Failed iteration 6', + ]); + await expect(previousFailure).toBeEnabled(); + await expect(nextFailure).toBeEnabled(); + await expect(previousFailure).toBeFocused(); + await page.keyboard.press('Escape'); + await expect(menu).toBeHidden(); + await expect(chooser).toBeFocused(); + await expect(number).toHaveValue('4'); + + await chooser.press('ArrowDown'); + await expect(previousFailure).toBeFocused(); + await page.keyboard.press('ArrowDown'); + await expect(nextFailure).toBeFocused(); + await page.keyboard.press('Enter'); + await expect(menu).toBeHidden(); + await expect(number).toHaveValue('6'); + + const total = pager.getByText('/ 123456', { exact: true }); + await expect(total).toBeInViewport({ ratio: 1 }); + await expect + .poll(() => + total.evaluate((element) => { + const row = element.closest('[data-loop-pager-row]')!.getBoundingClientRect(); + const label = element.getBoundingClientRect(); + const range = document.createRange(); + range.selectNodeContents(element); + const text = range.getBoundingClientRect(); + return text.width > 0 && text.left >= Math.max(row.left, label.left) - 1 && text.right <= Math.min(row.right, label.right) + 1; + }) + ) + .toBe(true); + + const port = card.locator('.react-flow__handle.source'); + // Same clearance predicate as the existing simulated-run spec; use the actual React Flow path, not its painted arrow. + const outgoing = page.locator('.react-flow__edge[data-id^="Foreach%2D#scope-"] .msla-shared-edge-path').first(); + await expect + .poll(async () => { + const controls = await pager.boundingBox(); + const source = await port.boundingBox(); + const edgeStartY = await outgoing.evaluate((path: SVGPathElement) => { + const transform = path.getScreenCTM(); + return transform && path.getPointAtLength(0).matrixTransform(transform).y; + }); + return controls && source && edgeStartY !== null + ? Math.min(source.y + source.height, edgeStartY) - (controls.y + controls.height) + : -1; + }) + .toBeGreaterThanOrEqual(0); + } +); diff --git a/e2e/designer/sharedNodeUiOttoParity.spec.ts b/e2e/designer/sharedNodeUiOttoParity.spec.ts new file mode 100644 index 00000000000..848f822a2c4 --- /dev/null +++ b/e2e/designer/sharedNodeUiOttoParity.spec.ts @@ -0,0 +1,163 @@ +import { readFileSync } from 'node:fs'; +import { expect, test, type Locator, type Page } from '@playwright/test'; +import scopeRun from '../../__mocks__/runs/simpleScoped/simpleScoped.json' with { type: 'json' }; +import { LoadRunFile } from './utils/GoToWorkflow'; +import { openSharedWorkflow, waitForViewport } from './utils/sharedNodeUi'; + +// Read Compose's iconUri from source text instead of importing compose.ts directly: +// compose.ts transitively pulls in logic-apps-shared TS files with parameter properties, +// which fail under Node 22's default strip-only TypeScript execution in Playwright CI. +const composeManifestIconUri = (() => { + const source = readFileSync( + new URL('../../libs/logic-apps-shared/src/designer-client-services/lib/consumption/manifests/compose.ts', import.meta.url), + 'utf8' + ); + const match = source.match(/iconUri:\s*'([^']+)'/); + if (!match) { + throw new Error('Could not extract Compose manifest iconUri'); + } + return match[1]; +})(); + +// Fluent's data-icon-name is only provided by the unit-test mock; match the real Braces SVG paths. +const bracesPath = { regular: 'M6.5 3A2.5 2.5', filled: 'M3.5 5.75A2.75 2.75' }; + +async function expectComposeIcon( + surface: Locator, + shared: boolean, + legacyArtwork: string | RegExp, + variant: keyof typeof bracesPath = 'regular' +) { + const tile = surface.locator('[data-node-glyph]'); + if (shared) { + await expect(surface.locator(`[data-tone="violet"] [data-node-glyph] svg:has(path[d^="${bracesPath[variant]}"])`)).toBeVisible(); + await expect(tile.locator('img')).toHaveCount(0); + } else { + const artwork = surface.locator('img[src]'); + await expect(artwork).toBeVisible(); + await expect(artwork).toHaveAttribute('src', legacyArtwork); + await expect(tile).toHaveCount(0); + } +} + +async function enableScopeRunRawControls(page: Page) { + const action = scopeRun.properties.actions.Increment_variable_3; + // The local run service supplies the recorded values, but the fixture omits URLs needed to expose the raw buttons. + const actions = { + ...scopeRun.properties.actions, + Increment_variable_3: { + ...action, + inputsLink: { ...action.inputsLink, uri: '/mock/scope-run/inputs' }, + outputsLink: { ...action.outputsLink, uri: '/mock/scope-run/outputs' }, + }, + }; + const { id, type, properties } = scopeRun; + await page.route(/\/__mocks__\/runs\/simpleScoped\/simpleScoped\.json(?:\?|$)/, (route) => + route.fulfill({ + contentType: 'application/javascript', + body: `export const id = ${JSON.stringify(id)}; export const type = ${JSON.stringify(type)}; + export const properties = ${JSON.stringify({ ...properties, actions })};`, + }) + ); +} + +async function resizeDetailsDrawer(page: Page, drawer: Locator, width: number) { + await expect(drawer).toBeVisible(); + // The operation drawer has no named resize control; its direct col-resize child handles mouse drags. + const { x, y, right } = await drawer.evaluate((element) => { + const handle = Array.from(element.children).find((child) => getComputedStyle(child).cursor === 'col-resize'); + if (!handle) { + throw new Error('Operation drawer is missing its resize handle'); + } + const bounds = handle.getBoundingClientRect(); + return { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2, right: element.getBoundingClientRect().right }; + }); + await page.mouse.move(x, y); + await page.mouse.down(); + await page.mouse.move(Math.round(right - width), y, { steps: 8 }); + await page.mouse.up(); + await expect.poll(async () => Math.round((await drawer.boundingBox())?.width ?? 0)).toBe(width); +} + +async function expectPayloadLayout(panel: Locator, layout: 'stacked' | 'side-by-side') { + const headers = panel.getByRole('button', { name: /^(Inputs|Outputs)$/ }); + await expect(headers).toHaveText(['Inputs', 'Outputs']); + for (const label of ['Show raw inputs', 'Show raw outputs']) { + const button = panel.getByRole('button', { name: label, exact: true }); + await expect(button).toBeVisible(); + await expect(button).toBeEnabled(); + } + await expect + .poll(async () => { + // Measure the header rows, not their contents, so icon/text widths cannot change the layout assertion. + const [inputs, outputs] = await Promise.all([headers.nth(0).locator('..').boundingBox(), headers.nth(1).locator('..').boundingBox()]); + if (!inputs || !outputs) { + return 'not laid out'; + } + if (Math.abs(inputs.x - outputs.x) <= 2 && outputs.y >= inputs.y + inputs.height - 2) { + return 'stacked'; + } + return Math.abs(inputs.y - outputs.y) <= 2 && outputs.x >= inputs.x + inputs.width - 2 ? 'side-by-side' : 'misaligned'; + }) + .toBe(layout); +} + +test.use({ viewport: { width: 1600, height: 1000 } }); + +for (const flag of ['true', 'false'] as const) { + const shared = flag === 'true'; + test.describe(`Standard Otto parity, flag ${flag}`, { tag: ['@mock', '@shared-node-ui'] }, () => { + test('uses the Compose glyph or legacy artwork across the canvas, operation drawer, and picker', async ({ page }) => { + // Keep the legacy Avatar from switching to its error glyph due to a remote image load. + await page.route('**/icons/compose.svg', (route) => + route.fulfill({ contentType: 'image/svg+xml', path: 'libs/designer-v2/src/lib/common/images/builtinoperationicons/compose.svg' }) + ); + await openSharedWorkflow(page, 'General Run After', flag); + const compose = page.locator('#msla-node-Compose'); + const manifestArtwork = composeManifestIconUri; + await expectComposeIcon(compose, shared, manifestArtwork); + await compose.click(); + await expectComposeIcon(compose, shared, manifestArtwork, 'filled'); + + const drawer = page.locator('.msla-panel-container').filter({ has: page.locator('#msla-node-details-panel-Compose') }); + await expectComposeIcon(drawer.locator('.msla-panel-card-header'), shared, manifestArtwork); + await drawer.getByRole('button', { name: 'Close', exact: true }).click(); + await expect(drawer).toBeHidden(); + + await page.getByRole('button', { name: 'Insert a new step between Init all and Compose', exact: true }).press('Enter'); + await page.getByRole('menuitem', { name: 'Add an action', exact: true }).click(); + await page.getByRole('searchbox', { name: 'Search for an action', exact: true }).fill('compose'); + const result = page.locator('.msla-result-list').getByRole('button', { name: 'Compose', exact: true }); + await expectComposeIcon(result, shared, /\/icons\/compose\.svg$/); + }); + + test('lays out recorded Inputs and Outputs by drawer width without losing DOM order or raw controls', async ({ page }) => { + await enableScopeRunRawControls(page); + await openSharedWorkflow(page, 'Scope', flag); + await LoadRunFile(page, 'simpleScoped'); + + const history = page.locator('.fui-InlineDrawer').filter({ has: page.getByRole('heading', { name: 'Run history', exact: true }) }); + if (await history.isVisible()) { + await history.locator('.fui-DrawerHeaderNavigation button').click(); + await expect(history).toBeHidden(); + } + await page.getByRole('button', { name: 'Zoom view to fit', exact: true }).click(); + await waitForViewport(page); + const increment = page.locator('#msla-node-Increment_variable_3'); + await expect( + shared + ? increment.locator('[data-node-subtitle-kind="status"]').getByText('Succeeded', { exact: true }) + : increment.getByAltText('Succeeded', { exact: true }) + ).toBeVisible(); + await increment.click(); + const panel = page.locator('#msla-node-details-panel-Increment_variable_3'); + const drawer = page.locator('.msla-panel-container').filter({ has: panel }); + await expect(drawer).toHaveCSS('width', '480px'); + await expect(panel.locator('[data-monitoring-payload-comparison] [data-monitoring-payload-grid]')).toHaveCount(shared ? 1 : 0); + await expectPayloadLayout(panel, 'stacked'); + + await resizeDetailsDrawer(page, drawer, 880); + await expectPayloadLayout(panel, shared ? 'side-by-side' : 'stacked'); + }); + }); +} diff --git a/e2e/designer/sharedNodeUiSimulatedRuns.spec.ts b/e2e/designer/sharedNodeUiSimulatedRuns.spec.ts index 14235572d18..4dfa7323a75 100644 --- a/e2e/designer/sharedNodeUiSimulatedRuns.spec.ts +++ b/e2e/designer/sharedNodeUiSimulatedRuns.spec.ts @@ -32,21 +32,26 @@ const runIndex = (page: Page, id: string, tool = false) => 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 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 viewport = graph?.closest('.react-flow__viewport'); + const ctm = edge?.getScreenCTM(); + if (!graph || !header || !card || !edge || !viewport || !ctm) { + return null; + } + const zoom = new DOMMatrixReadOnly(getComputedStyle(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), + edgeStart: Math.round((edge.getPointAtLength(0).matrixTransform(ctm).y - top) / zoom), }; }); @@ -183,13 +188,13 @@ for (const flag of ['true', 'false'] as const) { } else { await expect(body).toHaveCount(0); } - const expanded = await measureForeach(page); + 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); + await expect.poll(async () => (await measureForeach(page))?.graph ?? Number.POSITIVE_INFINITY).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. @@ -213,6 +218,98 @@ for (const flag of ['true', 'false'] as const) { }); }); + if (flag === 'true') { + test('hides the previous Foreach error and raw I/O while the selected iteration is pending', async ({ page }) => { + // The Local Designer's mock HTTP client does not send requests by default. + 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 (options.uri.startsWith('/url/foreach-parity-run/actions/Increment_variable_2/repetitions/')) { + return fetch(options.uri).then(response => response.json()); + } + return originalGet.apply(this, arguments); + };`, + }); + }); + const errorMessage = 'Simulated failure from the first iteration'; + const repetitions = /\/foreach-parity-run\/actions\/Increment_variable_2\/repetitions\/00000[01]\?/; + let releaseSecond = () => {}; + const pending = new Promise((resolve) => { + releaseSecond = resolve; + }); + await page.route(repetitions, async (route) => { + const name = new URL(route.request().url()).pathname.split('/').pop(); + const first = name === '000000'; + if (!first) { + await pending; + } + await route.fulfill({ + json: { + name, + properties: { + ...times, + status: first ? 'Failed' : 'Succeeded', + ...(first && { + code: 'FixtureFailure', + error: { code: 'FixtureFailure', message: errorMessage }, + inputsLink: { uri: '/simulated-foreach/000000/inputs' }, + outputsLink: { uri: '/simulated-foreach/000000/outputs' }, + }), + }, + }, + }); + }); + + await openSharedWorkflow(page, 'ForEach', flag); + await enterSimulatedMonitoring(page); + await page.evaluate( + ({ times }) => { + const store = (window as DesignerWindow).DesignerStoreV2; + store.dispatch({ type: 'workflow/setRunIndex', payload: { nodeId: 'Foreach', page: 0 } }); + store.dispatch({ + type: 'workflow/setRepetitionRunData', + payload: { nodeId: 'Foreach', runData: { ...times, status: 'Succeeded', iterationCount: 2 } }, + }); + store.dispatch({ + type: 'workflow/setRunInstance', + payload: { id: '/foreach-parity-run', name: 'foreach-parity-run', properties: { status: 'Failed' } }, + }); + }, + { times } + ); + + const action = page.locator('#msla-node-Increment_variable_2'); + await action.click(); + const panel = page.locator('#msla-node-details-panel-Increment_variable_2'); + const priorError = panel.getByText(errorMessage, { exact: true }); + const rawInputs = panel.getByRole('button', { name: 'Show raw inputs', exact: true }); + const rawOutputs = panel.getByRole('button', { name: 'Show raw outputs', exact: true }); + const priorValue = panel.locator('[aria-labelledby="inputs-Increment_variable_2"] pre').filter({ hasText: 'var1' }); + await expect(priorError).toBeVisible(); + await expect(rawInputs).toBeVisible(); + await expect(rawOutputs).toBeVisible(); + await expect(priorValue).toBeVisible(); + try { + const secondRequest = page.waitForRequest(/\/Increment_variable_2\/repetitions\/000001\?/); + await page.getByTestId('msla-pager-v2-foreach').getByLabel('Next iteration', { exact: true }).click(); + await secondRequest; + await expect(panel).toBeVisible(); + await expect(priorError).toHaveCount(0); + await expect(rawInputs).toHaveCount(0); + await expect(rawOutputs).toHaveCount(0); + await expect(priorValue).toHaveCount(0); + } finally { + releaseSecond(); + } + await expect(action).toHaveAttribute('data-status', 'succeeded'); + await expect(priorError).toHaveCount(0); + }); + } + 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. diff --git a/libs/designer-ui-v2/.storybook/check-inventory.mjs b/libs/designer-ui-v2/.storybook/check-inventory.mjs index a372fb1ddc7..ed2be75619b 100644 --- a/libs/designer-ui-v2/.storybook/check-inventory.mjs +++ b/libs/designer-ui-v2/.storybook/check-inventory.mjs @@ -38,6 +38,7 @@ const visualExports = [ 'LoopBodyJoin', 'NodeLine', 'NodeActionAdd', + 'MonitoringPayloadComparison', 'IfIconRegular', 'IfIconFilled', 'NodeFrame', diff --git a/libs/designer-ui-v2/README.md b/libs/designer-ui-v2/README.md index c39e4cf65df..e74e718ec2f 100644 --- a/libs/designer-ui-v2/README.md +++ b/libs/designer-ui-v2/README.md @@ -21,7 +21,7 @@ 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 **40** +Start with **Start here / Introduction** and **API and boundaries**. All **41** public visual exports (including `DesignerUiScope` and both condition icons) have individual typed metadata, native Overview docs, and supported examples. The API page documents all **39** nonvisual runtime exports and public types without @@ -71,6 +71,10 @@ stock light and 12.4:1 in stock dark. Title color, typography, geometry and node surface values are unchanged. Custom host themes still require their own contrast verification. +The Monitoring payload comparison story exercises the layout at a fixed browser +viewport while resizing the content area. The shell accepts the host's existing +Inputs, Outputs, and Properties sections; it does not render payloads or controls. + Excluded: `NodeBodyToggle` (no verified runtime dependency), CoreAI code/assets/default hooks, Aptos, MCP SVG, Otto models/stores/aliases/services/real graph handles, layout engines, and application mutation/adapters. MCP preserves its canonical public Fluent Regular/Regular fallback and brand suppression. No Otto files were modified. Otto still consumes its local source; cross-repository migration is not complete until that host imports the shared package. **Unverified acceptance:** written file-level OSS/legal clearance (MIT declaration is not clearance); public design acceptance; complete rendered interaction and matched two-host visual acceptance, including light/dark, RTL, forced colors and reduced motion; iframe/webview/CSP/clipping checks; feed/name/provenance and ownership/ruleset confirmation. Release eligibility does not establish that these checks passed. @@ -126,7 +130,7 @@ All added props are optional; omitted values retain the previous behavior. | `NodeStatusBadge` | `label` defaults to `strings[status]`; `detail` defaults to none; explicit empty `label` is preserved. `live=true` is the standalone default (`role="status"` with implicit polite semantics); `live=false` opts out. Explicit `role` takes precedence. Canvas composites opt out. Forwarded `aria-label` is host-supplied. The nine `NodeRunStatus` tones are frozen. | | Cards, `NodeCard`, `NodeFrame` | `statusDisplay='badge'`; `statusTone`/`statusTint` default to frozen tone and no tint; `statusLabel` defaults to dictionary text; `statusAriaLabel` defaults to no badge-name override; `statusDetail` defaults to none; `inactive=false`. For `statusDisplay='contained'`, `NodeCard` exposes status context to `NodeText`, so hosts set status once (on `NodeCard`) and use `subtitleKind='status'` without duplicating status subtitle strings through adapters. Inactive ancestors provide `NodeInactiveContext` so nested inactive cards/handles/branch outputs do not compound the 0.4 opacity. The host supplies the card's `aria-label`. | | `getNodeStatusLabel(status, strings?, detail?, label?)` | Returns `(label ?? strings[status])` plus a nonempty detail. Strings default to English; detail/label default to none. Hosts reuse this text when constructing the owning card's accessible name. | -| `NodeIterationPager` | Required `current`, `count`, `onChange` use zero-based indices; display/input is one-based. `editable=false`; `failed` omitted means no failed-jump controls; `strings` defaults to `defaultNodeIterationPagerStrings`. Invalid/nonpositive totals render nothing; indices and input are bounded. Run dispatch and failure evidence stay host-owned. | +| `NodeIterationPager` | Required `current`, `count`, `onChange` use zero-based indices; display/input is one-based. `editable=false`; `failed` omitted means no failed-jump controls. Optional `failedDestinations` adds a direct select in editable mode. For a constrained Foreach card row, `compactFailureNavigation` combines relative and direct jumps in one menu. Long lists group destinations by iteration range without dropping any. `strings` defaults to `defaultNodeIterationPagerStrings`, with optional `failedDestinationSelect`, `failedDestinationPrompt`, `failedDestinationOption`, and `failedDestinationRange`. Invalid/nonpositive totals render nothing; indices and input are bounded. Run dispatch and failure evidence stay host-owned. | | `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. | diff --git a/libs/designer-ui-v2/src/index.ts b/libs/designer-ui-v2/src/index.ts index 374ea7c5d9f..fc5f25e4926 100644 --- a/libs/designer-ui-v2/src/index.ts +++ b/libs/designer-ui-v2/src/index.ts @@ -1,4 +1,6 @@ export * from './nodes'; +export { MonitoringPayloadComparison } from './monitoring/MonitoringPayloadComparison'; +export type { MonitoringPayloadComparisonProps } from './monitoring/MonitoringPayloadComparison'; export { DesignerUiScope, useDesignerUiOutlet } from './theme/DesignerUiScope'; export type { DesignerUiScopeProps, DesignerUiThemeOverrides } from './theme/DesignerUiScope'; export { designerUiTokens, nodeCardVars } from './theme/tokens'; diff --git a/libs/designer-ui-v2/src/monitoring/MonitoringPayloadComparison.tsx b/libs/designer-ui-v2/src/monitoring/MonitoringPayloadComparison.tsx new file mode 100644 index 00000000000..a0e7630d712 --- /dev/null +++ b/libs/designer-ui-v2/src/monitoring/MonitoringPayloadComparison.tsx @@ -0,0 +1,52 @@ +import { makeStyles, mergeClasses, tokens } from '@fluentui/react-components'; +import type { ReactNode } from 'react'; + +const MONITORING_PANE_MIN_WIDTH = '20rem'; + +const useStyles = makeStyles({ + root: { + display: 'grid', + gridTemplateColumns: 'minmax(0, 1fr)', + rowGap: tokens.spacingVerticalL, + }, + comparisonGrid: { + display: 'grid', + // Tracks wrap against this pane's available width, including when the drawer is pinned or resized. + gridTemplateColumns: `repeat(auto-fit, minmax(min(100%, ${MONITORING_PANE_MIN_WIDTH}), 1fr))`, + columnGap: tokens.spacingHorizontalL, + rowGap: tokens.spacingVerticalL, + }, + pane: { + minInlineSize: 0, + }, +}); + +export interface MonitoringPayloadComparisonProps { + inputsSection: ReactNode; + outputsSection: ReactNode; + propertiesSection: ReactNode; + className?: string; +} + +/** + * Responsive Inputs/Outputs shell for host-owned monitoring sections. + * Layout only: the host still owns payload rendering, links, copy, and loading/error states. + */ +export const MonitoringPayloadComparison: React.FC = ({ + inputsSection, + outputsSection, + propertiesSection, + className, +}) => { + const styles = useStyles(); + + return ( +
+
+
{inputsSection}
+
{outputsSection}
+
+ {propertiesSection} +
+ ); +}; diff --git a/libs/designer-ui-v2/src/nodes/__test__/contracts.spec.ts b/libs/designer-ui-v2/src/nodes/__test__/contracts.spec.ts index e751d4ba4a5..f9b595610c2 100644 --- a/libs/designer-ui-v2/src/nodes/__test__/contracts.spec.ts +++ b/libs/designer-ui-v2/src/nodes/__test__/contracts.spec.ts @@ -87,6 +87,9 @@ describe('additive monitoring string contracts', () => { expect(defaultNodeStrings.pager).toBe(defaultNodeIterationPagerStrings); expect(defaultNodeStrings.runAfter).toBe(defaultNodeRunAfterStrings); expect(defaultNodeIterationPagerStrings.position(2, 5)).toBe('2 of 5'); + expect(defaultNodeIterationPagerStrings.failedDestinationSelect).toBe('Jump to failed iteration'); + expect(defaultNodeIterationPagerStrings.failedDestinationPrompt).toBe('Failed…'); + expect(defaultNodeIterationPagerStrings.failedDestinationOption?.(3)).toBe('Failed iteration 3'); expect(defaultNodeRunAfterStrings.collapsed(7)).toBe('Runs after 7 actions'); }); diff --git a/libs/designer-ui-v2/src/nodes/__test__/monitoring.spec.tsx b/libs/designer-ui-v2/src/nodes/__test__/monitoring.spec.tsx index 7690b5e5acf..119ed3e1c74 100644 --- a/libs/designer-ui-v2/src/nodes/__test__/monitoring.spec.tsx +++ b/libs/designer-ui-v2/src/nodes/__test__/monitoring.spec.tsx @@ -1,4 +1,5 @@ import { fireEvent, render, screen } from '@testing-library/react'; +import { useState } from 'react'; import { describe, expect, it, vi } from 'vitest'; import * as ui from '../..'; import type { NodeLineVariant } from '../..'; @@ -81,6 +82,161 @@ describe('NodeIterationPager', () => { unmount(); }); + it('shows direct failed destinations in editable mode and dispatches the selected zero-based index', () => { + const { onChange } = renderPager({ + editable: true, + current: 0, + count: 8, + failed: [2, 4, 6], + failedDestinations: [6, 2, 4, 2, 0, -1, 2.5, 8], + }); + const select = screen.getByRole('combobox', { name: 'Jump to failed iteration' }); + const options = Array.from(select.querySelectorAll('option')).map((option) => option.textContent); + expect(options).toEqual(['Failed…', 'Failed iteration 3', 'Failed iteration 5', 'Failed iteration 7']); + expect(screen.getByRole('textbox')).toHaveValue('1'); + expect(screen.getByText('/ 8')).toBeVisible(); + expect(screen.getByRole('button', { name: 'Next failed iteration' }).nextElementSibling).toBe(select); + fireEvent.click(select); + fireEvent.change(select, { target: { value: '3' } }); + expect(onChange).not.toHaveBeenCalled(); + fireEvent.change(select, { target: { value: '6' } }); + expect(onChange).toHaveBeenCalledExactlyOnceWith(6); + expect(select).toHaveValue(''); + }); + + it('offers all failure navigation in one compact menu without removing ordinary navigation', () => { + const args = { + compactFailureNavigation: true, + editable: true, + current: 3, + count: 10, + failed: [2, 4, 8], + failedDestinations: [2, 4, 8], + }; + const { onChange } = renderPager(args); + const trigger = screen.getByRole('button', { name: 'Jump to failed iteration' }); + expect(screen.queryByRole('combobox')).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Previous iteration' })).toBeEnabled(); + expect(screen.getByRole('button', { name: 'Next iteration' })).toBeEnabled(); + expect(screen.getByRole('textbox')).toHaveValue('4'); + expect(screen.getByText('/ 10')).toBeVisible(); + + for (const [name, index] of [ + ['Previous failed iteration', 2], + ['Next failed iteration', 4], + ['Failed iteration 9', 8], + ] as const) { + fireEvent.click(trigger); + fireEvent.click(screen.getByRole('menuitem', { name })); + expect(onChange).toHaveBeenLastCalledWith(index); + } + expect(onChange).toHaveBeenCalledTimes(3); + }); + + it('opens only the requested range of a long compact failure list, including the final destination', () => { + const failed = Array.from({ length: 66 }, (_, index) => (index + 1) * 2); + const { onChange } = renderPager({ + compactFailureNavigation: true, + editable: true, + count: 200, + failed, + failedDestinations: failed, + }); + + fireEvent.click(screen.getByRole('button', { name: 'Jump to failed iteration' })); + expect(screen.getByRole('menuitem', { name: 'Next failed iteration' })).toBeEnabled(); + expect(screen.queryByRole('menuitem', { name: 'Failed iteration 133' })).not.toBeInTheDocument(); + + fireEvent.click(screen.getByRole('menuitem', { name: 'Failed iterations 131 to 133' })); + expect(screen.queryByRole('menuitem', { name: 'Failed iteration 3' })).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('menuitem', { name: 'Failed iteration 133' })); + expect(onChange).toHaveBeenCalledExactlyOnceWith(132); + }); + + it('stays in compact mode without restoring separate failure buttons when jumping to a loop sole failed iteration', () => { + const ControlledCompactPager = () => { + const [current, setCurrent] = useState(0); + return ( + + ); + }; + render(); + + const group = screen.getByRole('group', { name: 'Iterations' }); + const input = screen.getByRole('textbox', { name: 'Iteration number, 1 to 100000' }); + const position = screen.getByText('/ 100000'); + const trigger = screen.getByRole('button', { name: 'Jump to failed iteration' }); + + expect(screen.queryByRole('button', { name: 'Previous failed iteration' })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Next failed iteration' })).not.toBeInTheDocument(); + expect(position).toHaveAttribute('dir', 'ltr'); + const compactInputWidths = propertyValues(input, 'width'); + expect(compactInputWidths.some((value) => value.includes('6ch'))).toBe(true); + + // Jump to the sole failed iteration (index 3 -> display 4): compact layout must stay active + // and separate failure buttons must not reappear, while focus rescues cleanly to the input. + trigger.focus(); + fireEvent.click(trigger); + fireEvent.click(screen.getByRole('menuitem', { name: 'Failed iteration 4' })); + + expect(input).toHaveValue('4'); + expect(input).toHaveFocus(); + expect(screen.queryByRole('button', { name: 'Jump to failed iteration' })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Previous failed iteration' })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Next failed iteration' })).not.toBeInTheDocument(); + expect(group.querySelector('[data-pager-action="previous-failed"]')).toBeNull(); + expect(group.querySelector('[data-pager-action="next-failed"]')).toBeNull(); + expect(position).toHaveAttribute('dir', 'ltr'); + expect(propertyValues(input, 'width').some((value) => value.includes('6ch'))).toBe(true); + + // Stepping away from the sole failed iteration restores the compact menu trigger. + fireEvent.click(screen.getByRole('button', { name: 'Previous iteration' })); + expect(input).toHaveValue('3'); + expect(screen.getByRole('button', { name: 'Jump to failed iteration' })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Previous failed iteration' })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Next failed iteration' })).not.toBeInTheDocument(); + }); + + it.each([ + { failedDestinations: [0, 1], hostFocus: false, focusRole: 'combobox' }, + { failedDestinations: [1], hostFocus: false, focusRole: 'textbox' }, + { failedDestinations: [1], hostFocus: true, focusRole: 'button' }, + ])('honors $focusRole focus after a controlled jump', ({ failedDestinations, hostFocus, focusRole }) => { + const ControlledPager = () => { + const [current, setCurrent] = useState(0); + return ( + <> + + { + if (hostFocus) { + screen.getByRole('button', { name: 'Host focus target' }).focus(); + } + setCurrent(target); + }} + /> + + ); + }; + render(); + const select = screen.getByRole('combobox'); + select.focus(); + fireEvent.change(select, { target: { value: '1' } }); + expect(screen.getByRole(focusRole, focusRole === 'button' ? { name: 'Host focus target' } : undefined)).toHaveFocus(); + }); + it('commits an editable value on Enter, clamped to the one-based range', () => { const { onChange } = renderPager({ editable: true, current: 1 }); const input = screen.getByRole('textbox', { name: 'Iteration number, 1 to 5' }); @@ -224,3 +380,41 @@ describe('NodeLine run states', () => { expect(propertyValues(container.querySelector('path') as SVGPathElement, 'opacity')).toEqual([String(ui.nodeMetrics.inactiveOpacity)]); }); }); + +describe('NodeIterationPager trailing failure chunk', () => { + it('renders a single trailing failed iteration directly instead of a one-item range submenu', () => { + const failed = Array.from({ length: 65 }, (_, index) => (index + 1) * 2); + const { onChange } = renderPager({ + compactFailureNavigation: true, + editable: true, + current: 0, + count: 200, + failed, + failedDestinations: failed, + }); + fireEvent.click(screen.getByRole('button', { name: 'Jump to failed iteration' })); + expect(screen.queryByRole('menuitem', { name: 'Failed iterations 131 to 131' })).not.toBeInTheDocument(); + const trailingItem = screen.getByRole('menuitem', { name: 'Failed iteration 131' }); + fireEvent.click(trailingItem); + expect(onChange).toHaveBeenCalledExactlyOnceWith(130); + }); +}); + +describe('MonitoringPayloadComparison', () => { + it('renders inputs, outputs, and properties inside the responsive comparison shell', () => { + const { container } = render( + Inputs} + outputsSection={
Outputs
} + propertiesSection={
Properties
} + /> + ); + const root = container.querySelector('[data-monitoring-payload-comparison]')!; + expect(root).toHaveClass('host-monitoring-shell'); + const grid = root.querySelector('[data-monitoring-payload-grid]')!; + expect(grid).toContainElement(screen.getByTestId('inputs-pane')); + expect(grid).toContainElement(screen.getByTestId('outputs-pane')); + expect(root).toContainElement(screen.getByTestId('properties-pane')); + }); +}); diff --git a/libs/designer-ui-v2/src/nodes/primitives/NodeIterationPager.tsx b/libs/designer-ui-v2/src/nodes/primitives/NodeIterationPager.tsx index a172eb261de..d9105b72fd7 100644 --- a/libs/designer-ui-v2/src/nodes/primitives/NodeIterationPager.tsx +++ b/libs/designer-ui-v2/src/nodes/primitives/NodeIterationPager.tsx @@ -1,7 +1,13 @@ -import { forwardRef, useEffect, useState } from 'react'; -import type { HTMLAttributes, KeyboardEvent, MouseEvent } from 'react'; -import { Button, makeStyles, mergeClasses, tokens } from '@fluentui/react-components'; -import { ChevronDoubleLeftRegular, ChevronDoubleRightRegular, ChevronLeftRegular, ChevronRightRegular } from '@fluentui/react-icons'; +import { forwardRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; +import type { ChangeEvent, HTMLAttributes, KeyboardEvent, MouseEvent } from 'react'; +import { Button, Menu, MenuItem, MenuList, MenuPopover, MenuTrigger, makeStyles, mergeClasses, tokens } from '@fluentui/react-components'; +import { + ChevronDoubleLeftRegular, + ChevronDoubleRightRegular, + ChevronLeftRegular, + ChevronRightRegular, + ErrorCircleRegular, +} from '@fluentui/react-icons'; import type { NodeIterationPagerStrings } from '../strings'; import { defaultNodeIterationPagerStrings } from '../strings'; @@ -27,9 +33,81 @@ const useStyles = makeStyles({ border: `${tokens.strokeWidthThin} solid ${tokens.colorNeutralStroke1}`, borderRadius: tokens.borderRadiusSmall, }, + failedSelect: { + boxSizing: 'border-box', + width: '4.75em', + minWidth: 0, + fontSize: tokens.fontSizeBase200, + color: tokens.colorNeutralForeground1, + backgroundColor: tokens.colorNeutralBackground1, + border: `${tokens.strokeWidthThin} solid ${tokens.colorNeutralStroke1}`, + borderRadius: tokens.borderRadiusSmall, + }, position: { whiteSpace: 'nowrap', paddingInline: tokens.spacingHorizontalXXS }, + compact: { gap: 0, fontSize: tokens.fontSizeBase100, fontVariantNumeric: 'tabular-nums' }, + compactInput: { + font: 'inherit', + // Fit six digits without reducing the three 24px button targets. + width: `calc(6ch + 2 * ${tokens.strokeWidthThin})`, + paddingInline: 0, + }, + compactPosition: { paddingInline: 0, marginInlineStart: tokens.spacingHorizontalXXS }, + compactArrow: { ':dir(rtl) svg': { transform: 'scaleX(-1)' } }, }); +// Keep each Fluent menu small, including for lists too large for a single level of ranges. +const failureMenuPageSize = 32; + +function FailureDestinationItems({ + indexes, + strings, + onSelect, +}: { + indexes: readonly number[]; + strings: NodeIterationPagerStrings; + onSelect: (index: number) => void; +}) { + if (indexes.length <= failureMenuPageSize) { + const label = strings.failedDestinationOption ?? defaultNodeIterationPagerStrings.failedDestinationOption; + return indexes.map((index) => ( + onSelect(index)}> + {label?.(index + 1)} + + )); + } + + let rangeSize = failureMenuPageSize; + while (Math.ceil(indexes.length / rangeSize) > failureMenuPageSize) { + rangeSize *= failureMenuPageSize; + } + const optionLabel = strings.failedDestinationOption ?? defaultNodeIterationPagerStrings.failedDestinationOption; + const label = strings.failedDestinationRange ?? defaultNodeIterationPagerStrings.failedDestinationRange; + return Array.from({ length: Math.ceil(indexes.length / rangeSize) }, (_, rangeIndex) => { + const start = rangeIndex * rangeSize; + const end = Math.min(start + rangeSize, indexes.length); + // Avoid wrapping a single trailing failure in a redundant "N to N" submenu. + if (end - start === 1) { + return ( + onSelect(indexes[start])}> + {optionLabel?.(indexes[start] + 1)} + + ); + } + return ( + + + {label?.(indexes[start] + 1, indexes[end - 1] + 1)} + + + + + + + + ); + }); +} + export interface NodeIterationPagerProps extends Omit, 'onChange' | 'children'> { /** Zero-based selected iteration. Out-of-range or non-finite values are clamped for display. */ current: number; @@ -39,6 +117,13 @@ export interface NodeIterationPagerProps extends Omit void; /** Zero-based failed iterations; enables the previous/next failed jumps. Out-of-range entries are ignored. */ failed?: readonly number[]; + /** + * Zero-based failed iterations that are safe to pick directly. Omitted keeps direct-selection UI hidden; + * out-of-range, duplicate, and current entries are ignored. + */ + failedDestinations?: readonly number[]; + /** Consolidates failure actions when direct destinations exist, for the constrained Foreach card row. */ + compactFailureNavigation?: boolean; /** Renders a numeric input instead of read-only position text. */ editable?: boolean; strings?: NodeIterationPagerStrings; @@ -56,6 +141,8 @@ export const NodeIterationPager = forwardRef 0 ? toIndex(current, total) : 0; + const inputRef = useRef(null); + const selectRef = useRef(null); + const failureTriggerRef = useRef(null); + const failureMenuRef = useRef(null); + const restoreInputFocus = useRef(false); const [draft, setDraft] = useState(String(index + 1)); - // Host updates (including a stale current that was clamped) replace any uncommitted draft. - useEffect(() => setDraft(String(index + 1)), [index]); - - if (total <= 0) { - return null; - } - + const validFailedDestinations = useMemo( + () => + Array.from(new Set((failedDestinations ?? []).filter((value) => Number.isInteger(value) && value >= 0 && value < total))).sort( + (a, b) => a - b + ), + [failedDestinations, total] + ); + const failedDestinationIndexes = useMemo( + () => validFailedDestinations.filter((value) => value !== index), + [validFailedDestinations, index] + ); // Failed jumps target the nearest valid failed iteration strictly before/after the selection. const validFailed = (failed ?? []).filter((value) => Number.isInteger(value) && value >= 0 && value < total); const previousFailed = validFailed.reduce( @@ -87,6 +183,41 @@ export const NodeIterationPager = forwardRef 0; + const showCompactMenu = + useCompactFailureLayout && (failedDestinationIndexes.length > 0 || previousFailed !== undefined || nextFailed !== undefined); + const showFailedDestinationSelect = editable && !compactFailureNavigation && failedDestinationIndexes.length > 0; + const failedDestinationLabel = strings.failedDestinationSelect ?? defaultNodeIterationPagerStrings.failedDestinationSelect; + const setFailureTriggerRef = useCallback((trigger: HTMLButtonElement | null) => { + const previous = failureTriggerRef.current; + if (!trigger && previous) { + const focused = previous.ownerDocument.activeElement; + restoreInputFocus.current = focused === previous || !!failureMenuRef.current?.contains(focused); + } + failureTriggerRef.current = trigger; + }, []); + const setSelectRef = useCallback((select: HTMLSelectElement | null) => { + const previous = selectRef.current; + restoreInputFocus.current = !select && !!previous && previous.ownerDocument.activeElement === previous; + selectRef.current = select; + }, []); + // Only rescue focus when the focused chooser was removed but this pager survived, and the host didn't take focus. + useLayoutEffect(() => { + const input = inputRef.current; + if (restoreInputFocus.current && input && input.ownerDocument.activeElement === input.ownerDocument.body) { + input.focus(); + } + restoreInputFocus.current = false; + }, [showFailedDestinationSelect, showCompactMenu]); + // Host updates (including a stale current that was clamped) replace any uncommitted draft. + useEffect(() => setDraft(String(index + 1)), [index]); + + if (total <= 0) { + return null; + } const go = (target: number | undefined) => { if (target !== undefined && target !== index && target >= 0 && target < total) { @@ -105,6 +236,15 @@ export const NodeIterationPager = forwardRef) => { + if (event.target.value !== '') { + const target = Number(event.target.value); + if (failedDestinationIndexes.includes(target)) { + go(target); + } + } + }; + // The pager lives inside a draggable, keyboard-navigable canvas node; keys typed here must not // reach canvas shortcuts. Tab is left alone so focus can still leave the group. const isolateKeys = (event: KeyboardEvent) => { @@ -125,12 +265,12 @@ export const NodeIterationPager = forwardRef - {hasFailed ? ( + {hasFailed && !useCompactFailureLayout ? ( + +
+
+          {`{\n  "message": "Long payload text wraps inside each pane without widening the host layout.",\n  "id": "abc123"\n}`}
+        
+
+ + ); +} + +const inputsSection = ; +const outputsSection = ; +const propertiesSection = ; + +const meta = { + title: 'Monitoring/MonitoringPayloadComparison', + component: MonitoringPayloadComparison, + args: { + inputsSection, + outputsSection, + propertiesSection, + }, + parameters: { + docs: { + description: { + component: 'Responsive layout for host-rendered Inputs, Outputs, and Properties. The host owns payload content and controls.', + }, + }, + }, +} satisfies Meta; + +export default meta; + +type Story = StoryObj; + +export const Default: Story = {}; + +function ResizableHost(args: MonitoringPayloadComparisonProps) { + const [width, setWidth] = useState(656); + return ( +
+ +
+ +
+
+ ); +} + +export const HostWidthFixture: Story = { + render: (args) => , + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + const host = canvas.getByTestId('monitoring-host'); + const grid = host.querySelector('[data-monitoring-payload-grid]'); + if (!grid) { + throw new Error('Monitoring payload grid did not render'); + } + const [inputsPane, outputsPane] = Array.from(grid.children); + const inputTop = () => inputsPane.getBoundingClientRect().top; + const outputTop = () => outputsPane.getBoundingClientRect().top; + const inputs = canvas.getByRole('button', { name: 'Open Inputs' }); + const outputs = canvas.getByRole('button', { name: /^Open Outputs/ }); + const properties = canvas.getByRole('button', { name: 'Open Properties' }); + const rootFontSize = Number.parseFloat(getComputedStyle(canvasElement.ownerDocument.documentElement).fontSize); + const gap = Number.parseFloat(getComputedStyle(grid).columnGap); + const splitWidth = 40 * rootFontSize + gap; + const initialWidth = host.style.inlineSize; + + // Resize the host directly so interacting with the slider cannot steal focus. + host.style.inlineSize = `${splitWidth - 1}px`; + await userEvent.click(inputs); + await expect(outputTop()).toBeGreaterThan(inputTop()); + + host.style.inlineSize = `${splitWidth}px`; + await expect(grid.getBoundingClientRect().width).toBeCloseTo(splitWidth); + await expect(outputTop()).toBe(inputTop()); + await expect(inputs).toHaveFocus(); + await userEvent.tab(); + await expect(outputs).toHaveFocus(); + + host.style.inlineSize = `${splitWidth + 1}px`; + await expect(outputTop()).toBe(inputTop()); + host.style.inlineSize = `${splitWidth - 1}px`; + await expect(outputTop()).toBeGreaterThan(inputTop()); + await expect(outputs).toHaveFocus(); + await userEvent.tab(); + await expect(properties).toHaveFocus(); + host.style.inlineSize = initialWidth; + }, +}; diff --git a/libs/designer-ui/src/lib/panel/__test__/panelcontainer.spec.tsx b/libs/designer-ui/src/lib/panel/__test__/panelcontainer.spec.tsx index 5691eaf349b..710b714ffb2 100644 --- a/libs/designer-ui/src/lib/panel/__test__/panelcontainer.spec.tsx +++ b/libs/designer-ui/src/lib/panel/__test__/panelcontainer.spec.tsx @@ -120,6 +120,27 @@ describe('ui/panel/panelContainer', () => { expect(nestedContainer(panel).props.className).not.toContain('msla-panel-container-nested-dual'); }); + it('keeps each icon with its own header when selection changes or closes', () => { + const selectedIcon = Selected glyph; + const pinnedIcon = Pinned glyph; + const props: PanelContainerProps = { + ...minimal, + node: { ...makeNode('selected'), operationIcon: selectedIcon }, + alternateSelectedNode: { ...makeNode('pinned'), operationIcon: pinnedIcon }, + alternateSelectedNodePersistence: 'pinned', + }; + const iconsByNode = (node: PanelContainerProps['node']) => { + renderer.render(); + return Object.fromEntries( + findPanelHeaders(renderer.getRenderOutput()).map(({ props }) => [props.nodeData.nodeId, props.nodeData.operationIcon]) + ); + }; + + expect(iconsByNode(props.node)).toStrictEqual({ selected: selectedIcon, pinned: pinnedIcon }); + expect(iconsByNode(makeNode('connector'))).toStrictEqual({ connector: undefined, pinned: pinnedIcon }); + expect(iconsByNode(undefined)).toStrictEqual({ pinned: pinnedIcon }); + }); + it('should close the selected pane instead of unpinning when the pinned node matches the selected node', () => { const onClose = vi.fn(); const onUnpinAction = vi.fn(); diff --git a/libs/designer-ui/src/lib/panel/panelcontainer.tsx b/libs/designer-ui/src/lib/panel/panelcontainer.tsx index 184cb156a76..00ca3a57b48 100644 --- a/libs/designer-ui/src/lib/panel/panelcontainer.tsx +++ b/libs/designer-ui/src/lib/panel/panelcontainer.tsx @@ -25,6 +25,8 @@ export type PanelContainerProps = { alternateSelectedNode: PanelNodeData | undefined; alternateSelectedNodeHeaderItems: JSX.Element[]; alternateSelectedNodePersistence: 'pinned' | 'selected'; + /** Mount a host observer only while this node's details pane is rendered. */ + renderNodeObserver?: (nodeId: string) => React.ReactNode; layerProps?: ILayerProps; canResubmit?: boolean; overrideWidth?: string; @@ -61,6 +63,7 @@ export const PanelContainer = ({ nodeHeaderItems, alternateSelectedNodeHeaderItems, alternateSelectedNodePersistence, + renderNodeObserver, onClose, trackEvent, onCommentChange, @@ -237,6 +240,7 @@ export const PanelContainer = ({ className={mergeClasses('msla-panel-layout', `msla-panel-border-${type}`, isAlternateSelectedNode && 'msla-panel-layout-pinned')} id={isAlternateSelectedNode ? alternateSelectedNodeContainerId : undefined} > + {renderNodeObserver?.(nodeId)} {renderHeader(contentsNode)}
{isLoading ? ( @@ -264,7 +268,15 @@ export const PanelContainer = ({
); }, - [renderHeader, panelErrorMessage, trackEvent, panelErrorTitle, alternateSelectedNodeContainerId, enableNodeNavigation] + [ + renderHeader, + renderNodeObserver, + panelErrorMessage, + trackEvent, + panelErrorTitle, + alternateSelectedNodeContainerId, + enableNodeNavigation, + ] ); const minWidth = isDualView ? Number.parseInt(PanelSize.DualView, 10) : undefined; diff --git a/libs/designer-ui/src/lib/panel/panelheader/__test__/panelheader.spec.tsx b/libs/designer-ui/src/lib/panel/panelheader/__test__/panelheader.spec.tsx index 9ef5f5c152d..6d31174f5bf 100644 --- a/libs/designer-ui/src/lib/panel/panelheader/__test__/panelheader.spec.tsx +++ b/libs/designer-ui/src/lib/panel/panelheader/__test__/panelheader.spec.tsx @@ -152,4 +152,27 @@ describe('lib/panel/panelHeader/main', () => { .toJSON(); expect(panelHeader).toMatchSnapshot(); }); + + it('renders operationIcon normally and suppresses it while loading or in error state', () => { + const icon = ; + const renderHeader = (overrides: Partial) => { + const tree = renderer.create( + + + + ); + return tree.root.findAllByProps({ 'data-testid': 'shared-panel-glyph' }); + }; + + expect(renderHeader({ isLoading: false, isError: false })).toHaveLength(1); + expect(renderHeader({ isLoading: true, isError: false })).toHaveLength(0); + expect(renderHeader({ isLoading: false, isError: true })).toHaveLength(0); + }); }); diff --git a/libs/designer-ui/src/lib/panel/panelheader/panelheader.tsx b/libs/designer-ui/src/lib/panel/panelheader/panelheader.tsx index 7692c24ac21..49f455f5fd5 100644 --- a/libs/designer-ui/src/lib/panel/panelheader/panelheader.tsx +++ b/libs/designer-ui/src/lib/panel/panelheader/panelheader.tsx @@ -5,6 +5,7 @@ import type { TitleChangeHandler } from './panelheadertitle'; import { PanelHeaderTitle } from './panelheadertitle'; import { Button, + makeStyles, Menu, MenuList, MenuPopover, @@ -71,6 +72,13 @@ const OverflowIcon = bundleIcon(MoreVertical24Filled, MoreVertical24Regular); const ResubmitIcon = bundleIcon(ReplayFilled, ReplayRegular); const ChevronRightIcon = bundleIcon(ChevronRightFilled, ChevronRightRegular); +const useStyles = makeStyles({ + operationIcon: { + marginRight: '4px', + flexShrink: 0, + }, +}); + const CloseButton = (props: PanelHeaderProps & { nodeId: string }): JSX.Element => { const { nodeId, onClose, enableNodeNavigation = false } = props; @@ -150,6 +158,7 @@ const OverflowButton = (props: PanelHeaderProps): JSX.Element => { }; export const PanelHeader = (props: PanelHeaderProps): JSX.Element => { + const styles = useStyles(); const { nodeData, suppressDefaultNodeSelectFunctionality, @@ -170,7 +179,7 @@ export const PanelHeader = (props: PanelHeaderProps): JSX.Element => { customIcon, } = props; - const { comment, displayName: title, iconUri: cardIcon, isError, isLoading, nodeId } = nodeData; + const { comment, displayName: title, iconUri: cardIcon, isError, isLoading, nodeId, operationIcon } = nodeData; const intl = useIntl(); const [isTriggerInfoDismissed, setIsTriggerInfoDismissed] = useState(false); @@ -232,7 +241,8 @@ export const PanelHeader = (props: PanelHeaderProps): JSX.Element => { <>
- {customIcon ?? iconComponent} + {customIcon ?? + (!isLoading && !isError && operationIcon ? {operationIcon} : iconComponent)}
({ + OperationSearchGroup: ({ operationApi, operationActionsData, onConnectorClick, onOperationClick }: any) => ( +
+ + {operationActionsData.map((op: any) => ( + + ))} +
+ ), +})); + +vi.mock('../../../browseResults', () => ({ + BrowseGrid: ({ operationsData, onOperationSelected }: any) => ( +
+ {operationsData.map((op: any) => ( + + ))} +
+ ), +})); + +const makeOperation = (id: string, summary: string, apiId = 'connectionProviders/control', apiName = 'Control') => + ({ + id, + name: id, + type: 'BuiltIn', + properties: { + summary, + description: `${summary} description`, + operationType: id, + api: { + id: apiId, + name: apiName.toLowerCase(), + displayName: apiName, + brandColor: '#0078D4', + iconUri: 'https://example.com/icon.svg', + }, + }, + }) as DiscoveryOperation; + +const renderGrid = (props: Partial[0]> = {}) => + render( + + + + ); + +describe('SearchResultsGridV2', () => { + afterEach(cleanup); + + it('renders a spinner while searching and an empty alert when no operations match', () => { + const { rerender } = renderGrid({ isLoadingSearch: true }); + expect(screen.getByText('Searching for results...')).toBeInTheDocument(); + + rerender( + + + + ); + expect(screen.getByRole('alert')).toHaveTextContent('No results found for "missing-op"'); + }); + + it('passes custom operation icons through grouped connector search results', () => { + const onConnectorClick = vi.fn(); + const onOperationClick = vi.fn(); + renderGrid({ + groupByConnector: true, + isLoadingMore: true, + operationSearchResults: [makeOperation('if', 'Condition'), makeOperation('switch', 'Switch')], + onConnectorClick, + onOperationClick, + renderOperationIcon: (op) => , + }); + + expect(screen.getByText('Searching for results...')).toBeInTheDocument(); + expect(screen.getByTestId('custom-icon-if')).toBeInTheDocument(); + expect(screen.getByTestId('custom-icon-switch')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Control' })); + expect(onConnectorClick).toHaveBeenCalledWith('connectionProviders/control'); + fireEvent.click(screen.getByRole('button', { name: 'Condition' })); + expect(onOperationClick).toHaveBeenCalledWith('if', 'connectionProviders/control'); + }); + + it('passes custom operation icons through flat BrowseGrid results', () => { + const onOperationClick = vi.fn(); + renderGrid({ + groupByConnector: false, + operationSearchResults: [makeOperation('foreach', 'For each')], + onOperationClick, + renderOperationIcon: (op) => , + }); + + expect(screen.getByTestId('flat-browse-grid')).toBeInTheDocument(); + expect(screen.getByTestId('flat-icon-foreach')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'For each' })); + expect(onOperationClick).toHaveBeenCalledWith('foreach', 'connectionProviders/control'); + }); +}); diff --git a/libs/designer-ui/src/lib/panel/recommendationpanel/operationGroupDetails/searchResult/searchResultV2.tsx b/libs/designer-ui/src/lib/panel/recommendationpanel/operationGroupDetails/searchResult/searchResultV2.tsx index 3d30810747c..4d911088018 100644 --- a/libs/designer-ui/src/lib/panel/recommendationpanel/operationGroupDetails/searchResult/searchResultV2.tsx +++ b/libs/designer-ui/src/lib/panel/recommendationpanel/operationGroupDetails/searchResult/searchResultV2.tsx @@ -7,13 +7,13 @@ import { SearchResultSortOptions } from '../../../types'; import { OperationSearchGroup } from '../../operationSearchGroup'; import { List } from '@fluentui/react'; import { Spinner, Text } from '@fluentui/react-components'; -import type { DiscoveryOpArray } from '@microsoft/logic-apps-shared'; -import type { PropsWithChildren } from 'react'; +import type { DiscoveryOpArray, DiscoveryOperation, DiscoveryResultTypes } from '@microsoft/logic-apps-shared'; +import type { PropsWithChildren, ReactNode } from 'react'; import React, { useMemo } from 'react'; import { useIntl } from 'react-intl'; import { BrowseGrid } from '../../browseResults'; -import { getOperationCardDataFromOperation } from '../../helpers'; import { RecommendationPanelConstants } from '../../../../constants'; +import { getOperationCardDataFromOperation } from '../../helpers'; import { OperationActionDataFromOperation } from './helper'; export type SearchResultsGridV2Props = { @@ -26,6 +26,7 @@ export type SearchResultsGridV2Props = { displayRuntimeInfo: boolean; groupByConnector: boolean; setGroupByConnector: (groupByConnector: boolean) => void; + renderOperationIcon?: (operation: DiscoveryOperation) => ReactNode; }; const maxOperationsToDisplay = RecommendationPanelConstants.SEARCH_VIEW.MAX_OPERATIONS_IN_SEARCH_GROUP; @@ -39,6 +40,7 @@ export const SearchResultsGridV2: React.FC { const intl = useIntl(); @@ -85,7 +87,10 @@ export const SearchResultsGridV2: React.FC getOperationCardDataFromOperation(operation))} + operationActionsData={operations.map((operation) => ({ + ...getOperationCardDataFromOperation(operation), + icon: renderOperationIcon?.(operation), + }))} onConnectorClick={onConnectorClick} onOperationClick={onOperationClick} maxOperationsToDisplay={maxOperationsToDisplay} @@ -93,11 +98,14 @@ export const SearchResultsGridV2: React.FC ); }, - [onConnectorClick, onOperationClick, operationSearchResults] + [onConnectorClick, onOperationClick, operationSearchResults, renderOperationIcon] ); const sortedOperationsData = useMemo(() => { - const operationCardData = operationSearchResults.map((operation) => OperationActionDataFromOperation(operation)); + const operationCardData = operationSearchResults.map((operation) => ({ + ...OperationActionDataFromOperation(operation), + icon: renderOperationIcon?.(operation), + })); if (resultsSorting !== SearchResultSortOptions.unsorted) { operationCardData.sort((a, b) => @@ -106,7 +114,7 @@ export const SearchResultsGridV2: React.FC - + {/* Fluent v8 List caches pages by items + version; bumping version forces re-render when renderOperationIcon toggles */} + ) : ( <> diff --git a/libs/designer-ui/src/lib/panel/recommendationpanel/recommendationPanelCard/__test__/recommendationPanelCard.spec.tsx b/libs/designer-ui/src/lib/panel/recommendationpanel/recommendationPanelCard/__test__/recommendationPanelCard.spec.tsx index cefb57fb75d..1d28c22ac81 100644 --- a/libs/designer-ui/src/lib/panel/recommendationpanel/recommendationPanelCard/__test__/recommendationPanelCard.spec.tsx +++ b/libs/designer-ui/src/lib/panel/recommendationpanel/recommendationPanelCard/__test__/recommendationPanelCard.spec.tsx @@ -147,4 +147,19 @@ describe('RecommendationPanelCard', () => { expect(onConnectorClick).toHaveBeenCalledWith('test-group-api-id'); }); }); + + it('renders a host-provided operation icon slot when available', () => { + const operationDataWithIcon: OperationsData = { + ...mockOperationData, + data: { + ...mockOperationData.data, + icon: icon, + }, + }; + + const { container } = renderWithProviders(); + + expect(screen.getByTestId('operation-icon-slot')).toBeTruthy(); + expect(container.querySelector('.msla-recommendation-panel-card-operation-icon')).toBeTruthy(); + }); }); diff --git a/libs/designer-ui/src/lib/panel/recommendationpanel/recommendationPanelCard/index.tsx b/libs/designer-ui/src/lib/panel/recommendationpanel/recommendationPanelCard/index.tsx index be86114ab5a..a2ffc78384c 100644 --- a/libs/designer-ui/src/lib/panel/recommendationpanel/recommendationPanelCard/index.tsx +++ b/libs/designer-ui/src/lib/panel/recommendationpanel/recommendationPanelCard/index.tsx @@ -1,12 +1,22 @@ import { getPreviewTag } from '../../../utils'; import type { OperationActionData, OperationGroupCardData } from '../interfaces'; -import { Badge, Caption1, Card, mergeClasses, Text } from '@fluentui/react-components'; +import { Badge, Caption1, Card, makeStyles, mergeClasses, Text } from '@fluentui/react-components'; import { InfoDot } from '../../../infoDot'; import { ChevronRight12Regular } from '@fluentui/react-icons'; import { ConnectorAvatar } from '../connectorAvatar'; import { FavoriteButton } from '../favoriteButton'; import { useIntl } from 'react-intl'; +const useStyles = makeStyles({ + operationIconSlot: { + width: '24px', + height: '24px', + display: 'inline-flex', + alignItems: 'center', + justifyContent: 'center', + }, +}); + export interface OperationsData { type: 'Operation'; data: OperationActionData; @@ -39,10 +49,12 @@ export const RecommendationPanelCard = ({ showConnectorName, hideFavorites = false, }: RecommendationPanelCardProps) => { + const styles = useStyles(); const { data } = operationData; const { apiId = '', connectorName, description, iconUri, brandColor, isCustom } = data; const isOperationAction = isOperationData(operationData); + const operationIcon = isOperationAction ? operationData.data.icon : undefined; const operationTitle = isOperationAction ? operationData.data.title : (connectorName ?? ''); const previewTag = isOperationAction ? getPreviewTag(operationData.data.releaseStatus) : undefined; @@ -80,15 +92,21 @@ export const RecommendationPanelCard = ({ title={operationTitle} >
- + {isOperationAction && operationIcon ? ( + + ) : ( + + )}
diff --git a/libs/designer-ui/src/lib/panel/types.ts b/libs/designer-ui/src/lib/panel/types.ts index 6b227c2b4a9..a691cd4d017 100644 --- a/libs/designer-ui/src/lib/panel/types.ts +++ b/libs/designer-ui/src/lib/panel/types.ts @@ -1,4 +1,5 @@ import type { LogicAppsV2 } from '@microsoft/logic-apps-shared'; +import type { ReactNode } from 'react'; import type { PanelTab } from './panelUtil'; export interface PanelNodeData { @@ -14,6 +15,8 @@ export interface PanelNodeData { selectedTab: string | undefined; subgraphType: string | undefined; tabs: PanelTab[]; + /** Optional icon for a loaded operation; pending and error states use the existing header artwork. */ + operationIcon?: ReactNode; } export type SearchResultSortOption = 'unsorted' | 'ascending' | 'descending'; diff --git a/libs/designer-v2/src/lib/core/actions/bjsworkflow/__test__/duplicateScopedRunAfter.spec.ts b/libs/designer-v2/src/lib/core/actions/bjsworkflow/__test__/duplicateScopedRunAfter.spec.ts new file mode 100644 index 00000000000..99c4ebb8a06 --- /dev/null +++ b/libs/designer-v2/src/lib/core/actions/bjsworkflow/__test__/duplicateScopedRunAfter.spec.ts @@ -0,0 +1,338 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { Deserialize } from '../../../parsers/BJSWorkflow/BJSDeserializer'; +import { initializeGraphState } from '../../../parsers/ParseReduxAction'; +import { DynamicLoadStatus, initializeNodeOperationInputsData } from '../../../state/operation/operationMetadataSlice'; +import { initWorkflowSpec, replaceId, setWorkflowKind } from '../../../state/workflow/workflowSlice'; +import { resetWorkflowState } from '../../../state/global'; +import { createDesignerStore, designerReducer } from '../../../store'; +import type { Workflow } from '../../../../common/models/workflow'; +import type { Operations } from '../../../state/workflow/workflowInterfaces'; +import { duplicateOperations, pasteScopeOperation } from '../copypaste'; +import { commitWorkflowExtraction } from '../workflowExtraction'; +import { deleteOperation } from '../delete'; +import * as operationDeserializer from '../operationdeserializer'; +import { serializeOperation } from '../serializer'; +import { onUndoClick, storeStateToUndoRedoHistory } from '../undoRedo'; +import { RUN_AFTER_STATUS, type LogicAppsV2 } from '@microsoft/logic-apps-shared'; + +vi.mock('@microsoft/logic-apps-shared', async (importOriginal) => ({ + ...(await importOriginal()), + OperationManifestService: () => ({ + isSupported: () => true, + getOperationManifest: async (_connector: string, operation: string) => ({ + properties: { + inputs: {}, + outputs: {}, + ...(operation === 'scope' && { allowChildOperations: true, childOperationsLocation: ['actions'] }), + }, + }), + }), +})); + +const definition = { + $schema: 'https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#', + contentVersion: '1.0.0.0', + triggers: { manual: { type: 'Request', kind: 'Http', inputs: { schema: {} } } }, + actions: { + Condition: { + type: 'If', + expression: '@equals(1,1)', + actions: { + Before: { type: 'Compose', inputs: 'before', runAfter: {} }, + GuardScope: { + type: 'Scope', + runAfter: { Before: [RUN_AFTER_STATUS.SUCCEEDED] }, + actions: { + Fallback: { type: 'Compose', inputs: 'fallback', runAfter: {} }, + Escalate: { + type: 'Compose', + inputs: 'escalate', + runAfter: { Fallback: [RUN_AFTER_STATUS.FAILED, RUN_AFTER_STATUS.TIMEDOUT] }, + }, + }, + }, + After: { type: 'Compose', inputs: 'after', runAfter: { GuardScope: [RUN_AFTER_STATUS.FAILED, RUN_AFTER_STATUS.TIMEDOUT] } }, + }, + else: { actions: { OtherBranch: { type: 'Compose', inputs: 'outside', runAfter: {} } } }, + }, + }, + outputs: {}, +}; + +const initializeOperations = (operations: Operations) => + initializeNodeOperationInputsData( + Object.entries(operations).map(([id, action]) => ({ + id, + operationInfo: { type: action.type, operationId: action.type, connectorId: 'connectionless' }, + nodeInputs: { parameterGroups: {}, dynamicLoadStatus: DynamicLoadStatus.SUCCEEDED }, + nodeOutputs: { outputs: {}, dynamicLoadStatus: DynamicLoadStatus.SUCCEEDED }, + nodeDependencies: { inputs: {}, outputs: {} }, + })) + ); + +const initializeStore = (shared: boolean) => { + const state = designerReducer(undefined, { type: '@@init' }); + const store = createDesignerStore({ ...state, designerOptions: { ...state.designerOptions, useSharedNodeUi: shared } }); + const workflow: Workflow = { kind: 'Stateful', definition, connectionReferences: {}, parameters: {} }; + const deserializedWorkflow = Deserialize(definition, null, true, workflow.kind); + + store.dispatch(initWorkflowSpec('BJS')); + store.dispatch(setWorkflowKind('stateful')); + store.dispatch( + initializeGraphState.fulfilled({ deserializedWorkflow, originalDefinition: definition }, 'probe-init', { + workflowDefinition: workflow, + runInstance: null, + }) + ); + + store.dispatch(initializeOperations(deserializedWorkflow.actionData)); + + return store; +}; + +describe('Duplicate scope', () => { + beforeEach(() => { + vi.spyOn(operationDeserializer, 'initializeOperationMetadata').mockImplementation( + async ({ actionData }, _references, _workflowParameters, _customCode, _workflowKind, dispatch) => { + dispatch(initializeOperations(actionData)); + } + ); + vi.spyOn(operationDeserializer, 'initializeDynamicDataInNodes').mockResolvedValue(undefined); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('preserves scoped serialization statuses, rewires follower runAfter statuses, and supports single-step undo', async () => { + const store = initializeStore(true); + const historyBefore = store.getState().undoRedo.past.length; + const { graph, operations, nodesMetadata } = store.getState().workflow; + const serializedSource = (await serializeOperation(store.getState(), 'GuardScope')) as LogicAppsV2.ScopeAction; + expect(serializedSource.actions?.Escalate.runAfter).toEqual({ Fallback: [RUN_AFTER_STATUS.FAILED, RUN_AFTER_STATUS.TIMEDOUT] }); + + await store.dispatch(duplicateOperations({ nodeIds: ['GuardScope'] })).unwrap(); + + const afterDuplicate = store.getState().workflow.operations as Record; + const duplicatedScopeId = Object.keys(afterDuplicate).find((id) => { + const operation = afterDuplicate[id] as LogicAppsV2.ScopeAction | undefined; + return id !== 'GuardScope' && operation?.type === 'Scope' && Object.keys(operation.runAfter ?? {}).includes('GuardScope'); + }); + + expect(duplicatedScopeId).toBeDefined(); + const duplicateId = duplicatedScopeId as string; + expect(store.getState().undoRedo.past.length).toBe(historyBefore + 1); + expect(store.getState().workflow.nodesMetadata[duplicateId].graphId).toBe(nodesMetadata.GuardScope.graphId); + expect(afterDuplicate.OtherBranch).toEqual(operations.OtherBranch); + expect((afterDuplicate[duplicateId] as LogicAppsV2.ScopeAction).runAfter).toEqual({ GuardScope: [RUN_AFTER_STATUS.SUCCEEDED] }); + expect(afterDuplicate.After.runAfter).toEqual({ [duplicateId]: [RUN_AFTER_STATUS.FAILED, RUN_AFTER_STATUS.TIMEDOUT] }); + + const serializedDuplicate = (await serializeOperation(store.getState(), duplicateId)) as LogicAppsV2.ScopeAction; + const nestedIds = Object.keys(serializedDuplicate.actions ?? {}); + const fallbackId = nestedIds.find((id) => id.startsWith('Fallback_'))!; + const escalateId = nestedIds.find((id) => id.startsWith('Escalate_'))!; + expect(fallbackId).toMatch(/^Fallback_/); + expect(escalateId).toMatch(/^Escalate_/); + expect(serializedDuplicate.actions?.[escalateId].runAfter).toEqual({ + [fallbackId]: [RUN_AFTER_STATUS.FAILED, RUN_AFTER_STATUS.TIMEDOUT], + }); + + await store.dispatch(onUndoClick()).unwrap(); + expect(store.getState().workflow.operations).toEqual(operations); + expect(store.getState().workflow.graph).toEqual(graph); + expect(store.getState().undoRedo.past).toHaveLength(historyBefore); + }); + + it('blocks interleaved Undo while a multi-node Shared Duplicate is in flight and reverts all copies in one Undo', async () => { + const store = initializeStore(true); + const { graph, operations } = store.getState().workflow; + const historyBefore = store.getState().undoRedo.past.length; + + let releaseScopeMetadata!: () => void; + vi.spyOn(operationDeserializer, 'initializeOperationMetadata').mockImplementationOnce( + async ({ actionData }, _references, _workflowParameters, _customCode, _workflowKind, dispatch) => { + await new Promise((resolve) => { + releaseScopeMetadata = resolve; + }); + dispatch(initializeOperations(actionData)); + } + ); + + const duplicatePromise = store.dispatch(duplicateOperations({ nodeIds: ['GuardScope', 'After'] })).unwrap(); + await vi.waitFor(() => expect(releaseScopeMetadata).toBeDefined()); + expect(store.getState().undoRedo.activeHistoryTransactions).toBe(1); + + // Attempting Undo mid-transaction must be ignored so the batch cannot split history. + await store.dispatch(onUndoClick()).unwrap(); + expect(store.getState().undoRedo.past).toHaveLength(historyBefore + 1); + + releaseScopeMetadata(); + await duplicatePromise; + expect(store.getState().undoRedo.activeHistoryTransactions).toBe(0); + expect(store.getState().undoRedo.past).toHaveLength(historyBefore + 1); + expect(Object.keys(store.getState().workflow.operations).length).toBeGreaterThan(Object.keys(operations).length + 1); + + await store.dispatch(onUndoClick()).unwrap(); + expect(store.getState().workflow.operations).toEqual(operations); + expect(store.getState().workflow.graph).toEqual(graph); + expect(store.getState().undoRedo.past).toHaveLength(historyBefore); + }); + + it('blocks unrelated undoable edits while scope initialization is paused so Undo never restores a half-duplicated graph', async () => { + const store = initializeStore(true); + const { graph, operations } = store.getState().workflow; + const historyBefore = store.getState().undoRedo.past.length; + + let releaseScopeMetadata!: () => void; + vi.spyOn(operationDeserializer, 'initializeOperationMetadata').mockImplementationOnce( + async ({ actionData }, _references, _workflowParameters, _customCode, _workflowKind, dispatch) => { + await new Promise((resolve) => { + releaseScopeMetadata = resolve; + }); + dispatch(initializeOperations(actionData)); + } + ); + + const duplicatePromise = store.dispatch(duplicateOperations({ nodeIds: ['GuardScope', 'After'] })).unwrap(); + await vi.waitFor(() => expect(releaseScopeMetadata).toBeDefined()); + expect(store.getState().undoRedo.past).toHaveLength(historyBefore + 1); + + // Intervening plain undoable edit and async mutation thunk must be blocked without recording a checkpoint. + store.dispatch(replaceId({ originalId: 'OtherBranch', newId: 'RenamedBranch' })); + await store.dispatch(storeStateToUndoRedoHistory({ type: 'unrelated/edit' } as any)); + await store.dispatch(deleteOperation({ nodeId: 'OtherBranch', isTrigger: false })); + expect(store.getState().workflow.operations.OtherBranch).toEqual(operations.OtherBranch); + expect(store.getState().workflow.operations.RenamedBranch).toBeUndefined(); + expect(store.getState().undoRedo.past).toHaveLength(historyBefore + 1); + + releaseScopeMetadata(); + await duplicatePromise; + expect(store.getState().undoRedo.activeHistoryTransactions).toBe(0); + expect(store.getState().undoRedo.past).toHaveLength(historyBefore + 1); + expect(store.getState().workflow.operations.OtherBranch).toEqual(operations.OtherBranch); + expect(Object.keys(store.getState().workflow.operations).length).toBeGreaterThan(Object.keys(operations).length + 1); + + // Single Undo restores the exact pre-Duplicate graph and operations. + await store.dispatch(onUndoClick()).unwrap(); + expect(store.getState().workflow.operations).toEqual(operations); + expect(store.getState().workflow.graph).toEqual(graph); + expect(store.getState().undoRedo.past).toHaveLength(historyBefore); + + // Normal edits and undo checkpoints resume once the transaction has settled. + store.dispatch(replaceId({ originalId: 'OtherBranch', newId: 'RenamedBranch' })); + expect(store.getState().workflow.idReplacements.OtherBranch).toBe('RenamedBranch'); + expect(store.getState().undoRedo.past).toHaveLength(historyBefore + 1); + }); + + it('does not push an undo checkpoint when Shared Duplicate finds no valid nodes', async () => { + const store = initializeStore(true); + const historyBefore = store.getState().undoRedo.past.length; + await store.dispatch(duplicateOperations({ nodeIds: ['NonExistentNode'] })).unwrap(); + expect(store.getState().undoRedo.past).toHaveLength(historyBefore); + expect(store.getState().undoRedo.activeHistoryTransactions).toBe(0); + }); + + it('leaves Legacy Duplicate checkpoints unchanged', async () => { + const store = initializeStore(false); + const historyBefore = store.getState().undoRedo.past.length; + await store.dispatch(duplicateOperations({ nodeIds: ['GuardScope'] })).unwrap(); + expect(store.getState().undoRedo.past).toHaveLength(historyBefore + 2); + }); + + it('refuses workflow extraction while a Shared Duplicate history transaction is in flight', async () => { + const store = initializeStore(true); + let releaseScopeMetadata!: () => void; + const origInitMetadata = operationDeserializer.initializeOperationMetadata; + vi.spyOn(operationDeserializer, 'initializeOperationMetadata').mockImplementationOnce(async (...args) => { + await new Promise((resolve) => { + releaseScopeMetadata = resolve; + }); + return origInitMetadata(...args); + }); + + const duplicatePromise = store.dispatch(duplicateOperations({ nodeIds: ['GuardScope'] })).unwrap(); + await vi.waitFor(() => expect(releaseScopeMetadata).toBeTypeOf('function')); + expect(store.getState().undoRedo.activeHistoryTransactions).toBe(1); + + await expect( + commitWorkflowExtraction( + store, + { createWorkflow: vi.fn(), getExistingWorkflowNames: vi.fn() } as any, + { newWorkflowName: 'Extracted', selectedNodeIds: ['OtherBranch'], sourceFingerprint: 'fp' } as any, + vi.fn() + ) + ).rejects.toThrow('The designer is not available for extraction.'); + + releaseScopeMetadata(); + await duplicatePromise; + expect(store.getState().undoRedo.activeHistoryTransactions).toBe(0); + }); + + it.each(['resetWorkflowState', 'initWorkflowSpec'] as const)( + 'cancels an in-flight Shared Duplicate transaction on %s and drops its late writes', + async (boundary) => { + const store = initializeStore(true); + let releaseScopeMetadata!: () => void; + vi.spyOn(operationDeserializer, 'initializeOperationMetadata').mockImplementationOnce(async (_w, _c, _p, _m, _k, dispatch) => { + await new Promise((resolve) => { + releaseScopeMetadata = resolve; + }); + dispatch(replaceId({ originalId: 'OtherBranch', newId: 'StaleLateWrite' })); + return {}; + }); + + const duplicatePromise = store.dispatch(duplicateOperations({ nodeIds: ['GuardScope'] })).unwrap(); + await vi.waitFor(() => expect(releaseScopeMetadata).toBeTypeOf('function')); + expect(store.getState().undoRedo.activeHistoryTransactions).toBe(1); + + if (boundary === 'resetWorkflowState') { + store.dispatch(resetWorkflowState()); + } else { + store.dispatch(initWorkflowSpec('BJS')); + } + expect(store.getState().undoRedo.activeHistoryTransactions).toBe(0); + + releaseScopeMetadata(); + await duplicatePromise; + expect(store.getState().undoRedo.activeHistoryTransactions).toBe(0); + expect(store.getState().workflow.idReplacements.OtherBranch).toBeUndefined(); + } + ); + + it('skips Shared Duplicate while a standalone pasteScopeOperation is awaiting metadata', async () => { + const store = initializeStore(true); + let releasePaste!: () => void; + const origInitMetadata = operationDeserializer.initializeOperationMetadata; + vi.spyOn(operationDeserializer, 'initializeOperationMetadata').mockImplementationOnce(async (...args) => { + await new Promise((resolve) => { + releasePaste = resolve; + }); + return origInitMetadata(...args); + }); + + const beforeCount = Object.keys(store.getState().workflow.operations).length; + const pastePromise = store + .dispatch( + pasteScopeOperation({ + relationshipIds: { graphId: 'root', parentId: 'Condition', childId: undefined }, + nodeId: 'PastedScope', + serializedValue: { type: 'Scope', actions: { InnerPaste: { type: 'Compose', inputs: 'pasted' } } }, + allConnectionData: {}, + staticResults: {}, + upstreamNodeIds: [], + }) + ) + .unwrap(); + + await vi.waitFor(() => expect(releasePaste).toBeTypeOf('function')); + await store.dispatch(duplicateOperations({ nodeIds: ['OtherBranch'] })).unwrap(); + expect(store.getState().undoRedo.activeHistoryTransactions).toBe(0); + + releasePaste(); + await pastePromise; + // Standalone scope paste added PastedScope + InnerPaste; skipped Shared Duplicate did not add OtherBranch_1. + expect(Object.keys(store.getState().workflow.operations)).toHaveLength(beforeCount + 2); + expect(store.getState().workflow.operations.OtherBranch_1).toBeUndefined(); + }); +}); diff --git a/libs/designer-v2/src/lib/core/actions/bjsworkflow/copypaste.ts b/libs/designer-v2/src/lib/core/actions/bjsworkflow/copypaste.ts index 2402b97c1d9..1d49a04b94c 100644 --- a/libs/designer-v2/src/lib/core/actions/bjsworkflow/copypaste.ts +++ b/libs/designer-v2/src/lib/core/actions/bjsworkflow/copypaste.ts @@ -41,7 +41,9 @@ import { getConnectionReferenceForNodeId } from '../../state/connection/connecti import { getStaticResultForNodeId } from '../../state/staticresultschema/staitcresultsSelector'; import { initScopeCopiedStaticResultProperties } from '../../state/staticresultschema/staticresultsSlice'; import { storeStateToUndoRedoHistory } from './undoRedo'; +import { beginHistoryTransaction, endHistoryTransaction } from '../../state/undoRedo/undoRedoSlice'; import { isWorkflowEditLocked } from '../../state/designerOptions/workflowEditLock'; +import { withHistoryTransaction } from '../../utils/middleware'; type CopyOperationPayload = { nodeId: string; @@ -237,66 +239,83 @@ interface PasteOperationPayload { connectionData?: ConnectionMapping[string]; comment?: string; isParallelBranch?: boolean; + skipUndoSnapshot?: boolean; } +// Tracks standalone (non-transaction) paste operations awaiting async metadata so Shared Duplicate +// does not start a history transaction mid-paste and drop the earlier paste's follow-up dispatches. +let activeStandalonePastes = 0; + export const pasteOperation = createAsyncThunk('pasteOperation', async (payload: PasteOperationPayload, { dispatch, getState }) => { const { nodeId: actionId, relationshipIds, nodeData, nodeTokenData, operationInfo, connectionData, comment, isParallelBranch } = payload; if (!actionId || !relationshipIds || !nodeData) { throw new Error('Operation does not exist'); } - const nodeId = getNonDuplicateNodeId((getState() as RootState).workflow.nodesMetadata, actionId); + const isStandalonePaste = !payload.skipUndoSnapshot; + if (isStandalonePaste) { + activeStandalonePastes += 1; + } - dispatch(setIsPanelLoading(true)); + try { + const nodeId = getNonDuplicateNodeId((getState() as RootState).workflow.nodesMetadata, actionId); - // update workflow - dispatch( - pasteNode({ - nodeId: nodeId, - relationshipIds: relationshipIds, - operation: operationInfo, - isParallelBranch, - }) - ); + dispatch(setIsPanelLoading(true)); - dispatch(setFocusNode(nodeId)); - dispatch(initializeOperationInfo({ id: nodeId, ...operationInfo })); - if (!isExpressionConnectionMapping(connectionData)) { - await initializeOperationDetails(nodeId, operationInfo, getState as () => RootState, dispatch); - } + // update workflow + dispatch( + pasteNode({ + nodeId: nodeId, + relationshipIds: relationshipIds, + operation: operationInfo, + isParallelBranch, + ...(payload.skipUndoSnapshot && { skipUndoSnapshot: true }), + }) + ); - // replace new nodeId if there exists a copy of the copied node - dispatch(initializeNodes({ nodes: [{ ...nodeData, id: nodeId }] })); - - const updatedTokens = (nodeTokenData?.tokens ?? []).map((token) => { - // Modify the actionName to a unique value - return { - ...token, - outputInfo: { - ...token.outputInfo, - actionName: nodeId, - }, - }; - }); + dispatch(setFocusNode(nodeId)); + dispatch(initializeOperationInfo({ id: nodeId, ...operationInfo })); + if (!isExpressionConnectionMapping(connectionData)) { + await initializeOperationDetails(nodeId, operationInfo, getState as () => RootState, dispatch); + } - dispatch( - addDynamicTokens({ - nodeId, - tokens: updatedTokens, - }) - ); + // replace new nodeId if there exists a copy of the copied node + dispatch(initializeNodes({ nodes: [{ ...nodeData, id: nodeId }] })); - if (connectionData) { - dispatch(initCopiedConnectionMap({ connectionReferences: { [nodeId]: connectionData } })); - } - if (comment) { - dispatch(setNodeDescription({ nodeId, description: comment })); - } + const updatedTokens = (nodeTokenData?.tokens ?? []).map((token) => { + // Modify the actionName to a unique value + return { + ...token, + outputInfo: { + ...token.outputInfo, + actionName: nodeId, + }, + }; + }); - updateAllUpstreamNodes(getState() as RootState, dispatch); - dispatch(setIsPanelLoading(false)); + dispatch( + addDynamicTokens({ + nodeId, + tokens: updatedTokens, + }) + ); + + if (connectionData) { + dispatch(initCopiedConnectionMap({ connectionReferences: { [nodeId]: connectionData } })); + } + if (comment) { + dispatch(setNodeDescription({ nodeId, description: comment })); + } - return nodeId; + updateAllUpstreamNodes(getState() as RootState, dispatch); + dispatch(setIsPanelLoading(false)); + + return nodeId; + } finally { + if (isStandalonePaste) { + activeStandalonePastes = Math.max(0, activeStandalonePastes - 1); + } + } }); interface PasteScopeOperationPayload { @@ -307,6 +326,7 @@ interface PasteScopeOperationPayload { staticResults: Record; upstreamNodeIds: string[]; isParallelBranch?: boolean; + skipUndoSnapshot?: boolean; } export const pasteScopeOperation = createAsyncThunk( @@ -324,122 +344,132 @@ export const pasteScopeOperation = createAsyncThunk( if (!actionId || !relationshipIds || !serializedValue) { throw new Error('Operation does not exist'); } - const { graphId, parentId } = relationshipIds; - const state = getState() as RootState; - const idReplacements = state.workflow.idReplacements; - const existingNodesMetadata = replaceIdsOfExistingNodes(state.workflow.nodesMetadata, idReplacements); - const nodeId = getNonDuplicateNodeId(existingNodesMetadata, actionId); - - const workflowActions = { [nodeId]: { ...serializedValue } as ActionDefinition }; - const allActionNames = getAllActionNames(workflowActions, [], true); - - const pasteParams = buildScopeParams(existingNodesMetadata, allActionNames); - const [nodes, _edges, actions, actionNodesMetadata] = buildGraphFromActions( - workflowActions, - graphId, - parentId, - Object.keys(existingNodesMetadata), - true /* shouldAppendAddCase */, - pasteParams - ); - // parentNodeId must reference a nodesMetadata key (the containing graph/scope) so the - // parent-chain walk in getUpstreamNodeIds can climb to ancestor scopes. `parentId` from - // relationshipIds is an edge-placement node (e.g. a `-#subgraph` card) and is not a - // valid metadata key, so use `graphId` (the containing graph) instead, matching how - // pasteScopeInWorkflow finalizes this node's metadata. - const scopeParentNodeId = graphId && graphId !== 'root' ? graphId : undefined; - actionNodesMetadata[nodeId] = { ...actionNodesMetadata[actionId], isRoot: false, parentNodeId: scopeParentNodeId, graphId }; - if (Object.keys(allConnectionData).length > 0) { - const copiedConnections = replaceIdsOfExistingNodes(allConnectionData, pasteParams.renamedNodes); - for (const [id, data] of Object.entries(copiedConnections)) { - if (data.mapping) { - const action = actions[id]; - const inputs = (action as LogicAppsV2.ServiceProvider)?.inputs; - if (inputs) { - actions[id] = { ...action, inputs: remapConnectionExpressionValue(inputs, pasteParams.renamedNodes) }; + const isStandalonePaste = !payload.skipUndoSnapshot; + if (isStandalonePaste) { + activeStandalonePastes += 1; + } + try { + const { graphId, parentId } = relationshipIds; + const state = getState() as RootState; + const idReplacements = state.workflow.idReplacements; + const existingNodesMetadata = replaceIdsOfExistingNodes(state.workflow.nodesMetadata, idReplacements); + const nodeId = getNonDuplicateNodeId(existingNodesMetadata, actionId); + + const workflowActions = { [nodeId]: { ...serializedValue } as ActionDefinition }; + const allActionNames = getAllActionNames(workflowActions, [], true); + + const pasteParams = buildScopeParams(existingNodesMetadata, allActionNames); + const [nodes, _edges, actions, actionNodesMetadata] = buildGraphFromActions( + workflowActions, + graphId, + parentId, + Object.keys(existingNodesMetadata), + true /* shouldAppendAddCase */, + pasteParams + ); + // parentNodeId must reference a nodesMetadata key (the containing graph/scope) so the + // parent-chain walk in getUpstreamNodeIds can climb to ancestor scopes. `parentId` from + // relationshipIds is an edge-placement node (e.g. a `-#subgraph` card) and is not a + // valid metadata key, so use `graphId` (the containing graph) instead, matching how + // pasteScopeInWorkflow finalizes this node's metadata. + const scopeParentNodeId = graphId && graphId !== 'root' ? graphId : undefined; + actionNodesMetadata[nodeId] = { ...actionNodesMetadata[actionId], isRoot: false, parentNodeId: scopeParentNodeId, graphId }; + if (Object.keys(allConnectionData).length > 0) { + const copiedConnections = replaceIdsOfExistingNodes(allConnectionData, pasteParams.renamedNodes); + for (const [id, data] of Object.entries(copiedConnections)) { + if (data.mapping) { + const action = actions[id]; + const inputs = (action as LogicAppsV2.ServiceProvider)?.inputs; + if (inputs) { + actions[id] = { ...action, inputs: remapConnectionExpressionValue(inputs, pasteParams.renamedNodes) }; + } + copiedConnections[id] = { + ...data, + mapping: { ...data.mapping, expression: remapConnectionExpression(data.mapping.expression, pasteParams.renamedNodes) }, + }; } - copiedConnections[id] = { - ...data, - mapping: { ...data.mapping, expression: remapConnectionExpression(data.mapping.expression, pasteParams.renamedNodes) }, - }; } + dispatch(initScopeCopiedConnections(copiedConnections)); } - dispatch(initScopeCopiedConnections(copiedConnections)); - } - for (const [id, action] of Object.entries(actions)) { - const connectionName = (action as LogicAppsV2.ServiceProvider).inputs?.serviceProviderConfiguration?.connectionName; - if ( - action.type.toLowerCase() === 'serviceprovider' && - typeof connectionName === 'string' && - !(getState() as RootState).connections.connectionsMapping[id] - ) { - const mapping = getServiceProviderConnectionMapping(connectionName); - if (isExpressionConnectionMapping(mapping)) { - dispatch( - setNodeConnectionMapping({ - nodeId: id, - mapping: { ...mapping, expression: remapConnectionExpression(mapping.expression, pasteParams.renamedNodes) }, - }) - ); - actions[id] = { - ...action, - inputs: remapConnectionExpressionValue((action as LogicAppsV2.ServiceProvider).inputs, pasteParams.renamedNodes), - }; + for (const [id, action] of Object.entries(actions)) { + const connectionName = (action as LogicAppsV2.ServiceProvider).inputs?.serviceProviderConfiguration?.connectionName; + if ( + action.type.toLowerCase() === 'serviceprovider' && + typeof connectionName === 'string' && + !(getState() as RootState).connections.connectionsMapping[id] + ) { + const mapping = getServiceProviderConnectionMapping(connectionName); + if (isExpressionConnectionMapping(mapping)) { + dispatch( + setNodeConnectionMapping({ + nodeId: id, + mapping: { ...mapping, expression: remapConnectionExpression(mapping.expression, pasteParams.renamedNodes) }, + }) + ); + actions[id] = { + ...action, + inputs: remapConnectionExpressionValue((action as LogicAppsV2.ServiceProvider).inputs, pasteParams.renamedNodes), + }; + } } } - } - if (Object.keys(staticResults).length > 0) { - dispatch(initScopeCopiedStaticResultProperties(replaceIdsOfExistingNodes(staticResults, pasteParams.renamedNodes))); - } - dispatch( - pasteScopeNode({ - relationshipIds, - scopeNode: nodes[0], - operations: actions, - nodesMetadata: actionNodesMetadata, - allActions: allActionNames, - isParallelBranch, - }) - ); - - dispatch(setIsPanelLoading(true)); - - dispatch(setFocusNode(nodeId)); - - const connectionReference = (getState() as RootState).connections.connectionReferences; - const workflowParameters = state.workflowParameters.definitions; - const workflowKind = state.workflow.workflowKind; - const operations = state.workflow.operations; - const nodeMap: Record = {}; - for (const id of Object.keys(operations)) { - nodeMap[id] = id; - } - const extendedIds = extendUpstreamNodeIdsForScopePaste(upstreamNodeIds, graphId, parentId, state, nodeMap); - const upstreamOutputTokens = replaceIdsOfExistingNodes(filterRecordByArray(state.tokens.outputTokens, extendedIds), idReplacements); - const triggerId = getTriggerNodeId(state.workflow); - - await Promise.all([ - initializeOperationMetadata( - { - graph: nodes[0], - actionData: actions, + if (Object.keys(staticResults).length > 0) { + dispatch(initScopeCopiedStaticResultProperties(replaceIdsOfExistingNodes(staticResults, pasteParams.renamedNodes))); + } + dispatch( + pasteScopeNode({ + relationshipIds, + scopeNode: nodes[0], + operations: actions, nodesMetadata: actionNodesMetadata, - staticResults: staticResults, - }, - connectionReference, - workflowParameters, - {}, - workflowKind, - dispatch, - { ...pasteParams, existingOutputTokens: upstreamOutputTokens, rootTriggerId: triggerId } - ), - ]); - await initializeDynamicDataInNodes(getState as () => RootState, dispatch, pasteParams.pasteActionNames); - - updateAllUpstreamNodes(getState() as RootState, dispatch); - dispatch(setIsPanelLoading(false)); - - return nodeId; + allActions: allActionNames, + isParallelBranch, + }) + ); + + dispatch(setIsPanelLoading(true)); + + dispatch(setFocusNode(nodeId)); + + const connectionReference = (getState() as RootState).connections.connectionReferences; + const workflowParameters = state.workflowParameters.definitions; + const workflowKind = state.workflow.workflowKind; + const operations = state.workflow.operations; + const nodeMap: Record = {}; + for (const id of Object.keys(operations)) { + nodeMap[id] = id; + } + const extendedIds = extendUpstreamNodeIdsForScopePaste(upstreamNodeIds, graphId, parentId, state, nodeMap); + const upstreamOutputTokens = replaceIdsOfExistingNodes(filterRecordByArray(state.tokens.outputTokens, extendedIds), idReplacements); + const triggerId = getTriggerNodeId(state.workflow); + + await Promise.all([ + initializeOperationMetadata( + { + graph: nodes[0], + actionData: actions, + nodesMetadata: actionNodesMetadata, + staticResults: staticResults, + }, + connectionReference, + workflowParameters, + {}, + workflowKind, + dispatch, + { ...pasteParams, existingOutputTokens: upstreamOutputTokens, rootTriggerId: triggerId } + ), + ]); + await initializeDynamicDataInNodes(getState as () => RootState, dispatch, pasteParams.pasteActionNames); + + updateAllUpstreamNodes(getState() as RootState, dispatch); + dispatch(setIsPanelLoading(false)); + + return nodeId; + } finally { + if (isStandalonePaste) { + activeStandalonePastes = Math.max(0, activeStandalonePastes - 1); + } + } } ); @@ -538,58 +568,98 @@ type DuplicateOperationsPayload = { // copy/paste building blocks but keeps everything in-memory so the user's clipboard is untouched. export const duplicateOperations = createAsyncThunk( 'duplicateOperations', - async (payload: DuplicateOperationsPayload, { dispatch, getState }) => { + async (payload: DuplicateOperationsPayload, { dispatch, getState, requestId }) => { const { nodeIds } = payload; - if (!nodeIds || nodeIds.length === 0 || isWorkflowEditLocked((getState() as RootState).designerOptions)) { + const initialState = getState() as RootState; + if (!nodeIds || nodeIds.length === 0 || isWorkflowEditLocked(initialState.designerOptions)) { return; } - dispatch(storeStateToUndoRedoHistory({ type: duplicateOperations.pending } as any)); + const useSharedHistoryTransaction = !!initialState.designerOptions.useSharedNodeUi; + if (useSharedHistoryTransaction && (initialState.undoRedo.activeHistoryTransactions || activeStandalonePastes > 0)) { + // Do not interleave overlapping multi-step duplicate batches or drop an in-flight standalone paste's async writes. + return; + } - for (const nodeId of nodeIds) { - // Re-read state each iteration because prior pastes mutate the workflow graph. - const state = getState() as RootState; - if (isWorkflowEditLocked(state.designerOptions)) { + // Tag all dispatches owned by this transaction so historyTransactionGuardMiddleware permits its + // nested async paste/metadata actions while blocking unrelated mutations until it settles. + const txDispatch = ( + useSharedHistoryTransaction ? (action: unknown) => dispatch(withHistoryTransaction(action, requestId) as any) : dispatch + ) as typeof dispatch; + + let snapshotRecorded = false; + const ensureDuplicateSnapshot = () => { + if (snapshotRecorded) { return; } - const graphId = getRecordEntry(state.workflow.nodesMetadata, nodeId)?.graphId; - if (!graphId) { - continue; - } + snapshotRecorded = true; + txDispatch(storeStateToUndoRedoHistory({ type: duplicateOperations.pending } as any)); + }; - // parentId set with no childId inserts the duplicate right below the source node. - const relationshipIds = { graphId, parentId: nodeId, childId: undefined }; - const operationInfo = getRecordEntry(state.operations.operationInfo, nodeId); + if (useSharedHistoryTransaction) { + txDispatch(beginHistoryTransaction()); + } else { + ensureDuplicateSnapshot(); + } - if (isScopeOperation(operationInfo?.type ?? '')) { - const entry = await buildScopeClipboardEntry(state, nodeId); - if (isWorkflowEditLocked((getState() as RootState).designerOptions)) { + try { + for (const nodeId of nodeIds) { + // Re-read state each iteration because prior pastes mutate the workflow graph. + const state = getState() as RootState; + if (isWorkflowEditLocked(state.designerOptions)) { return; } - const upstreamNodeIds = getRecordEntry(state.tokens.outputTokens, removeIdTag(nodeId))?.upstreamNodeIds ?? []; - await dispatch( - pasteScopeOperation({ - relationshipIds, - nodeId: entry.nodeId, - serializedValue: entry.serializedOperation, - allConnectionData: entry.allConnectionData, - staticResults: entry.staticResults, - upstreamNodeIds, - }) - ); - } else { - const entry = JSON.parse(JSON.stringify(buildActionClipboardEntry(state, nodeId))); - await dispatch( - pasteOperation({ - relationshipIds, - nodeId: entry.nodeId, - nodeData: entry.nodeData, - nodeTokenData: entry.nodeTokenData, - operationInfo: entry.nodeOperationInfo, - connectionData: entry.nodeConnectionData, - comment: entry.nodeComment, - }) - ); + const graphId = getRecordEntry(state.workflow.nodesMetadata, nodeId)?.graphId; + if (!graphId) { + continue; + } + + // parentId set with no childId inserts the duplicate right below the source node. + const relationshipIds = { graphId, parentId: nodeId, childId: undefined }; + const operationInfo = getRecordEntry(state.operations.operationInfo, nodeId); + // The outer Duplicate owns one checkpoint for all of its internal pastes. + const undoOptions = useSharedHistoryTransaction ? { skipUndoSnapshot: true } : undefined; + + if (isScopeOperation(operationInfo?.type ?? '')) { + const entry = await buildScopeClipboardEntry(state, nodeId); + if (isWorkflowEditLocked((getState() as RootState).designerOptions)) { + return; + } + const upstreamNodeIds = getRecordEntry(state.tokens.outputTokens, removeIdTag(nodeId))?.upstreamNodeIds ?? []; + // Record the single transaction checkpoint lazily right before the first real mutation + // so an aborted or empty duplicate never pushes a no-op entry or clears Redo history. + ensureDuplicateSnapshot(); + await txDispatch( + pasteScopeOperation({ + relationshipIds, + nodeId: entry.nodeId, + serializedValue: entry.serializedOperation, + allConnectionData: entry.allConnectionData, + staticResults: entry.staticResults, + upstreamNodeIds, + ...undoOptions, + }) + ); + } else { + const entry = JSON.parse(JSON.stringify(buildActionClipboardEntry(state, nodeId))); + ensureDuplicateSnapshot(); + await txDispatch( + pasteOperation({ + relationshipIds, + nodeId: entry.nodeId, + nodeData: entry.nodeData, + nodeTokenData: entry.nodeTokenData, + operationInfo: entry.nodeOperationInfo, + connectionData: entry.nodeConnectionData, + comment: entry.nodeComment, + ...undoOptions, + }) + ); + } + } + } finally { + if (useSharedHistoryTransaction) { + txDispatch(endHistoryTransaction()); } } } diff --git a/libs/designer-v2/src/lib/core/actions/bjsworkflow/monitoring.ts b/libs/designer-v2/src/lib/core/actions/bjsworkflow/monitoring.ts index 527195b27a6..7ead7af20a8 100644 --- a/libs/designer-v2/src/lib/core/actions/bjsworkflow/monitoring.ts +++ b/libs/designer-v2/src/lib/core/actions/bjsworkflow/monitoring.ts @@ -25,7 +25,7 @@ import type { NodeOperation } from '../../state/operation/operationMetadataSlice import { getConnectorWithSwagger } from '../../queries/connections'; import OutputsBinder from '../../utils/monitoring/binders/outputs'; import { getAgentActionsRepetition, getAgentRepetition } from '../../queries/runs'; -import type { AgentToolInvocation } from '../../state/workflow/workflowInterfaces'; +import type { AgentToolInvocation, LoopRepetition } from '../../state/workflow/workflowInterfaces'; /** * Converts raw JSON data into BoundParameters format for display in ValuesPanel. @@ -45,6 +45,8 @@ const convertToBoundParameters = (data: Record): BoundParameters => interface InitInputsOutputsPayload { nodeId: string; inputsOutputs: InputsOutputsBinding; + loopRepetition?: LoopRepetition; + loopPayloadRevision?: string; } interface InputsOutputsBinding { diff --git a/libs/designer-v2/src/lib/core/actions/bjsworkflow/undoRedo.ts b/libs/designer-v2/src/lib/core/actions/bjsworkflow/undoRedo.ts index 916fb726e31..46dc8b1fbdf 100644 --- a/libs/designer-v2/src/lib/core/actions/bjsworkflow/undoRedo.ts +++ b/libs/designer-v2/src/lib/core/actions/bjsworkflow/undoRedo.ts @@ -48,7 +48,7 @@ export const storeStateToUndoRedoHistory = createAsyncThunk( export const onUndoClick = createAsyncThunk('onUndoClick', async (_, { dispatch, getState }): Promise => { const currentRootState = getState() as RootState; - if (isWorkflowEditLocked(currentRootState.designerOptions)) { + if (isWorkflowEditLocked(currentRootState.designerOptions) || currentRootState.undoRedo.activeHistoryTransactions) { return; } const undoRedoState = currentRootState.undoRedo; @@ -89,7 +89,7 @@ export const onUndoClick = createAsyncThunk('onUndoClick', async (_, { dispatch, export const onRedoClick = createAsyncThunk('onRedoClick', async (_, { dispatch, getState }): Promise => { const currentRootState = getState() as RootState; - if (isWorkflowEditLocked(currentRootState.designerOptions)) { + if (isWorkflowEditLocked(currentRootState.designerOptions) || currentRootState.undoRedo.activeHistoryTransactions) { return; } const undoRedoState = currentRootState.undoRedo; diff --git a/libs/designer-v2/src/lib/core/actions/bjsworkflow/workflowExtraction.ts b/libs/designer-v2/src/lib/core/actions/bjsworkflow/workflowExtraction.ts index 6560a807fa3..26178612143 100644 --- a/libs/designer-v2/src/lib/core/actions/bjsworkflow/workflowExtraction.ts +++ b/libs/designer-v2/src/lib/core/actions/bjsworkflow/workflowExtraction.ts @@ -101,7 +101,12 @@ export async function commitWorkflowExtraction( ): Promise { const snapshot = liveStore.getState(); const intl = getIntl(); - if (snapshot.designerView.workflowExtractionBusy || snapshot.designerOptions.readOnly || snapshot.designerOptions.isMonitoringView) { + if ( + snapshot.designerView.workflowExtractionBusy || + snapshot.designerOptions.readOnly || + snapshot.designerOptions.isMonitoringView || + snapshot.undoRedo.activeHistoryTransactions + ) { throw new Error( intl.formatMessage({ id: 'NVB50O', diff --git a/libs/designer-v2/src/lib/core/graphlayout/__test__/branchAxis.spec.tsx b/libs/designer-v2/src/lib/core/graphlayout/__test__/branchAxis.spec.tsx index d21e98c8d81..8e2562ca7ea 100644 --- a/libs/designer-v2/src/lib/core/graphlayout/__test__/branchAxis.spec.tsx +++ b/libs/designer-v2/src/lib/core/graphlayout/__test__/branchAxis.spec.tsx @@ -500,4 +500,75 @@ describe('actual deserialized tool-branch axis contracts', () => { .sort() ); }); + + // Offline-only probe: validates ELK compound placement/containment invariants. + // DOM handle anchor rendering and final routed-path visuals still require browser validation. + it('keeps parallel If/Switch/Agent compounds disjoint in offline ELK placement invariants', async () => { + const source = { + ...definition(), + actions: { + ...definition().actions, + Parallel_if: { + type: 'If', + expression: { equals: [1, 1] }, + actions: { If_true: { type: 'Compose', inputs: 'true-branch', runAfter: {} } }, + else: { actions: { If_false: { type: 'Compose', inputs: 'false-branch', runAfter: {} } } }, + runAfter: {}, + }, + Parallel_switch: { + type: 'Switch', + expression: '@triggerBody()', + cases: { + Case_1: { case: 1, actions: { Switch_case_1: { type: 'Compose', inputs: 'case-1', runAfter: {} } } }, + Case_with_long_localized_label_for_wraps: { + case: 'long-localized-label', + actions: { Switch_case_long: { type: 'Compose', inputs: 'case-long', runAfter: {} } }, + }, + }, + default: { actions: { Switch_default: { type: 'Compose', inputs: 'default', runAfter: {} } } }, + runAfter: {}, + }, + }, + }; + const { nodes, edges, layout } = await accept(source, true); + const ids = [agentId, 'Parallel_if', 'Parallel_switch']; + const compounds = ids.map((id) => nodes.find((node) => node.id === id)!); + const bounds = compounds.map((node) => ({ + id: node.id, + left: node.position.x, + top: node.position.y, + right: node.position.x + node.width!, + bottom: node.position.y + node.height!, + })); + + for (const node of compounds) { + expect(node.parentId).toBeUndefined(); + expect(node.data.handleAxis).toBe('vertical'); + } + + for (let i = 0; i < bounds.length; i++) { + for (let j = i + 1; j < bounds.length; j++) { + const first = bounds[i]; + const second = bounds[j]; + const overlaps = !( + first.right <= second.left || + second.right <= first.left || + first.bottom <= second.top || + second.bottom <= first.top + ); + expect(overlaps, `${first.id} should not overlap ${second.id}`).toBe(false); + } + } + + for (const id of ids) { + expect(edges.find((edge) => edge.source === 'When_a_new_chat_session_starts' && edge.target === id)).toBeDefined(); + const compound = findElkNode(layout, id)!; + for (const child of compound.children!) { + expect(child.x!).toBeGreaterThanOrEqual(0); + expect(child.y!).toBeGreaterThanOrEqual(0); + expect(child.x! + child.width!).toBeLessThanOrEqual(compound.width!); + expect(child.y! + child.height!).toBeLessThanOrEqual(compound.height!); + } + } + }); }); diff --git a/libs/designer-v2/src/lib/core/hooks/useLoopRepetitionAdmission.ts b/libs/designer-v2/src/lib/core/hooks/useLoopRepetitionAdmission.ts new file mode 100644 index 00000000000..19433685412 --- /dev/null +++ b/libs/designer-v2/src/lib/core/hooks/useLoopRepetitionAdmission.ts @@ -0,0 +1,33 @@ +import type { LogicAppsV2 } from '@microsoft/logic-apps-shared'; +import { useEffect } from 'react'; +import { useDispatch } from 'react-redux'; +import isEqual from 'lodash.isequal'; +import type { useNodeRepetition } from '../queries/runs'; +import { useNodeMetadata } from '../state/workflow/workflowSelectors'; +import type { LoopRepetition } from '../state/workflow/workflowInterfaces'; +import { setRepetitionRunData } from '../state/workflow/workflowSlice'; +import { isSameLoopRepetition } from '../utils/loopRepetitions'; + +export function useLoopRepetitionAdmission( + nodeId: string, + repetition?: LoopRepetition, + data?: ReturnType['data'] +) { + const activeRepetition = repetition?.isEmpty ? undefined : repetition; + const metadata = useNodeMetadata(activeRepetition ? nodeId : undefined); + const response = data?.properties as LogicAppsV2.WorkflowRunAction | undefined; + const loopPayloadRevision = data?.loopPayloadRevision; + const hasCurrentResponse = + !!activeRepetition && + isSameLoopRepetition(metadata?.runDataRepetition, activeRepetition) && + metadata?.loopPayloadRevision === loopPayloadRevision && + isEqual(metadata?.runDataRepetitionSource, response); + const dispatch = useDispatch(); + + // Metadata can be rebuilt while the query keeps the same key and result. Watch admission as well as the response. + useEffect(() => { + if (activeRepetition && response && loopPayloadRevision && !hasCurrentResponse) { + dispatch(setRepetitionRunData({ nodeId, runData: response, loopRepetition: activeRepetition, loopPayloadRevision })); + } + }, [dispatch, hasCurrentResponse, nodeId, activeRepetition, response, loopPayloadRevision]); +} diff --git a/libs/designer-v2/src/lib/core/queries/__test__/runs.spec.ts b/libs/designer-v2/src/lib/core/queries/__test__/runs.spec.ts index 2e3792f7fdd..933bb83cd01 100644 --- a/libs/designer-v2/src/lib/core/queries/__test__/runs.spec.ts +++ b/libs/designer-v2/src/lib/core/queries/__test__/runs.spec.ts @@ -66,6 +66,21 @@ describe('runs queries', () => { await waitFor(() => expect(result.current).toEqual({ expressionResult: false })); }); + test('refetches and clears stale condition outputs when loopPayloadRevision changes with identical tracking metadata', async () => { + const baseRun = { correlation: { actionTrackingId: 'same-id' }, startTime: 'start', endTime: 'end' }; + mockRunService.getActionLinks.mockResolvedValueOnce({ outputs: { expressionResult: true } }); + const { result, rerender } = renderHook( + ({ uri, rev }) => useConditionOutputs('Condition', 'run', '000000', { ...baseRun, outputsLink: { uri, contentSize: 16 } }, true, rev), + { initialProps: { uri: 'link-v1', rev: 'rev-1' }, wrapper: createWrapper } + ); + await waitFor(() => expect(result.current).toEqual({ expressionResult: true })); + + mockRunService.getActionLinks.mockResolvedValueOnce({ outputs: { expressionResult: false } }); + rerender({ uri: 'link-v2', rev: 'rev-2' }); + expect(result.current).toBeUndefined(); + await waitFor(() => expect(result.current).toEqual({ expressionResult: false })); + }); + test('does not request secured condition outputs', () => { const outputsLink = { uri: 'fixture-condition-outputs', contentSize: 32, secureData: { properties: ['outputs'] } }; const { result } = renderHook( @@ -170,6 +185,12 @@ describe('runs queries', () => { // Query should be disabled and not make service calls expect(mockRunService.getScopeRepetitions).not.toHaveBeenCalled(); }); + + test('should be disabled when runId is undefined', () => { + renderHook(() => useScopeFailedRepetitions(constants.NODE.TYPE.FOREACH, 'testScope', undefined), { wrapper: createWrapper }); + + expect(mockRunService.getScopeRepetitions).not.toHaveBeenCalled(); + }); }); describe('useAgentActionsRepetition', () => { diff --git a/libs/designer-v2/src/lib/core/queries/runs.ts b/libs/designer-v2/src/lib/core/queries/runs.ts index e607d5c416f..c2254de7408 100644 --- a/libs/designer-v2/src/lib/core/queries/runs.ts +++ b/libs/designer-v2/src/lib/core/queries/runs.ts @@ -1,4 +1,4 @@ -import { useMutation, useQuery, useQueries, useInfiniteQuery, useQueryClient } from '@tanstack/react-query'; +import { replaceEqualDeep, useMutation, useQuery, useQueries, useInfiniteQuery, useQueryClient } from '@tanstack/react-query'; import { type ChatHistory, isNullOrUndefined, @@ -11,6 +11,8 @@ import { getReactQueryClient } from '../ReactQueryProvider'; import { isRunError } from '@microsoft/designer-ui'; import constants from '../../common/constants'; import { useMemo } from 'react'; +import { nanoid } from '@reduxjs/toolkit'; +import isEqual from 'lodash.isequal'; const queryOpts = { cacheTime: 1000 * 60 * 60 * 24, @@ -187,6 +189,26 @@ export const getRun = (runId: string) => { ); }; +type SkippedNodeRepetition = { + properties: { status: string; inputsLink: null; outputsLink: null; startTime: null; endTime: null; trackingId: null; correlation: null }; +}; +type NodeRepetitionResponse = (LogicAppsV2.RunRepetition | SkippedNodeRepetition) & { loopPayloadRevision?: string }; + +function shareLoopPayloadRevision(previous: NodeRepetitionResponse | undefined, next: NodeRepetitionResponse): NodeRepetitionResponse { + const before = previous?.properties; + const after = next.properties; + const samePayload = + !!before && + isEqual(before.inputsLink ?? null, after.inputsLink ?? null) && + isEqual(before.outputsLink ?? null, after.outputsLink ?? null) && + isEqual('inputs' in before ? before.inputs : undefined, 'inputs' in after ? after.inputs : undefined) && + isEqual('outputs' in before ? before.outputs : undefined, 'outputs' in after ? after.outputs : undefined); + + // The token belongs to this cached response, not the current Redux selection. Query keys never contain links. + const revision = (samePayload && previous?.loopPayloadRevision) || nanoid(); + return replaceEqualDeep(previous, { ...next, loopPayloadRevision: revision }); +} + export const useNodeRepetition = ( isEnabled: boolean, nodeId: string, @@ -196,7 +218,7 @@ export const useNodeRepetition = ( parentRunIndex: number | undefined, isWithinAgenticLoop: boolean ) => { - return useQuery( + return useQuery( [runsQueriesKeys.useNodeRepetition, { nodeId, runId, repetitionName, parentStatus, parentRunIndex }], async () => { if (parentStatus === constants.FLOW_STATUS.SKIPPED) { @@ -218,6 +240,7 @@ export const useNodeRepetition = ( { ...queryOpts, retryOnMount: false, + structuralSharing: shareLoopPayloadRevision, enabled: repetitionName !== undefined && parentRunIndex !== undefined && isEnabled && !isWithinAgenticLoop, } ); @@ -231,19 +254,22 @@ export const useConditionOutputs = ( | Pick | { outputsLink: null; correlation: null; startTime: null; endTime: null } | undefined, - enabled: boolean + enabled: boolean, + loopPayloadRevision?: string ) => { const outputsLink = runData?.outputsLink; const canFetch = enabled && !!runId && !!outputsLink?.uri && !outputsLink.secureData; + // Use the opaque loopPayloadRevision for loop repetitions so refreshed output links invalidate + // the cache even when tracking ID and timestamps are unchanged, without putting SAS URIs in keys. const { data } = useQuery( [ runsQueriesKeys.useConditionOutputs, runId, nodeId, repetitionName, - runData?.correlation?.actionTrackingId, - runData?.startTime, - runData?.endTime, + ...(loopPayloadRevision !== undefined + ? [loopPayloadRevision] + : [runData?.correlation?.actionTrackingId, runData?.startTime, runData?.endTime]), ], async () => (await RunService().getActionLinks({ outputsLink }, nodeId)).outputs ?? null, { @@ -319,7 +345,7 @@ export const useScopeFailedRepetitions = (normalizedType: string, nodeId: string }, { ...queryOpts, - enabled: normalizedType === constants.NODE.TYPE.FOREACH || normalizedType === constants.NODE.TYPE.UNTIL, + enabled: Boolean(runId) && (normalizedType === constants.NODE.TYPE.FOREACH || normalizedType === constants.NODE.TYPE.UNTIL), } ); }; diff --git a/libs/designer-v2/src/lib/core/state/__test__/undoRedoSlice.spec.ts b/libs/designer-v2/src/lib/core/state/__test__/undoRedoSlice.spec.ts index f5b7e323eab..770c0a288a3 100644 --- a/libs/designer-v2/src/lib/core/state/__test__/undoRedoSlice.spec.ts +++ b/libs/designer-v2/src/lib/core/state/__test__/undoRedoSlice.spec.ts @@ -1,5 +1,17 @@ import { describe, expect, it } from 'vitest'; -import reducer, { saveStateToHistory, updateStateHistoryOnRedoClick, updateStateHistoryOnUndoClick } from '../undoRedo/undoRedoSlice'; +import { renderHook } from '@testing-library/react'; +import { Provider } from 'react-redux'; +import React from 'react'; +import { configureStore } from '@reduxjs/toolkit'; +import reducer, { + beginHistoryTransaction, + endHistoryTransaction, + saveStateToHistory, + updateStateHistoryOnRedoClick, + updateStateHistoryOnUndoClick, +} from '../undoRedo/undoRedoSlice'; +import { useCanRedo, useCanUndo, useUndoRedoClickToggle } from '../undoRedo/undoRedoSelectors'; +import { initWorkflowSpec } from '../workflow/workflowSlice'; import { StateHistory, StateHistoryItem } from '../undoRedo/undoRedoTypes'; import constants from '../../../common/constants'; @@ -101,4 +113,47 @@ describe('undo redo slice reducers', () => { expect(state.currentEditedPanelNode).toEqual(undefined); expect(state.currentEditedPanelTab).toEqual(undefined); }); + + it('tracks active history transactions and clears them on initWorkflowSpec', () => { + let state: StateHistory = { past: [mockCompressedState1], future: [mockCompressedState2], undoRedoClickToggle: 0 }; + state = reducer(state, beginHistoryTransaction()); + expect(state.activeHistoryTransactions).toBe(1); + state = reducer(state, initWorkflowSpec('BJS')); + expect(state.activeHistoryTransactions).toBe(0); + state = reducer(state, endHistoryTransaction()); + expect(state.activeHistoryTransactions).toBe(0); + }); + + it('disables useCanUndo and useCanRedo while a history transaction is active', () => { + const store = configureStore({ + reducer: { + undoRedo: reducer, + designerOptions: (state = { readOnly: false, isMonitoringView: false }) => state, + }, + preloadedState: { + undoRedo: { + past: [mockCompressedState1], + future: [mockCompressedState2], + undoRedoClickToggle: 1, + activeHistoryTransactions: 1, + }, + designerOptions: { readOnly: false, isMonitoringView: false }, + }, + }); + const wrapper = ({ children }: { children: React.ReactNode }) => React.createElement(Provider, { store }, children); + + const canUndo = renderHook(() => useCanUndo(), { wrapper }); + const canRedo = renderHook(() => useCanRedo(), { wrapper }); + const toggle = renderHook(() => useUndoRedoClickToggle(), { wrapper }); + + expect(canUndo.result.current).toBe(false); + expect(canRedo.result.current).toBe(false); + expect(toggle.result.current).toBe(1); + + store.dispatch(endHistoryTransaction()); + canUndo.rerender(); + canRedo.rerender(); + expect(canUndo.result.current).toBe(true); + expect(canRedo.result.current).toBe(true); + }); }); diff --git a/libs/designer-v2/src/lib/core/state/undoRedo/undoRedoSelectors.ts b/libs/designer-v2/src/lib/core/state/undoRedo/undoRedoSelectors.ts index af2815d8748..fecf2a7d68d 100644 --- a/libs/designer-v2/src/lib/core/state/undoRedo/undoRedoSelectors.ts +++ b/libs/designer-v2/src/lib/core/state/undoRedo/undoRedoSelectors.ts @@ -3,11 +3,17 @@ import type { RootState } from '../../store'; import { isWorkflowEditLocked } from '../designerOptions/workflowEditLock'; export const useCanUndo = () => { - return useSelector((state: RootState) => !isWorkflowEditLocked(state.designerOptions) && state.undoRedo.past.length > 0); + return useSelector( + (state: RootState) => + !isWorkflowEditLocked(state.designerOptions) && !state.undoRedo.activeHistoryTransactions && state.undoRedo.past.length > 0 + ); }; export const useCanRedo = () => { - return useSelector((state: RootState) => !isWorkflowEditLocked(state.designerOptions) && state.undoRedo.future.length > 0); + return useSelector( + (state: RootState) => + !isWorkflowEditLocked(state.designerOptions) && !state.undoRedo.activeHistoryTransactions && state.undoRedo.future.length > 0 + ); }; export const useUndoRedoClickToggle = () => { diff --git a/libs/designer-v2/src/lib/core/state/undoRedo/undoRedoSlice.ts b/libs/designer-v2/src/lib/core/state/undoRedo/undoRedoSlice.ts index b18236c0873..da833fa8a5c 100644 --- a/libs/designer-v2/src/lib/core/state/undoRedo/undoRedoSlice.ts +++ b/libs/designer-v2/src/lib/core/state/undoRedo/undoRedoSlice.ts @@ -1,17 +1,25 @@ import { createSlice, type PayloadAction } from '@reduxjs/toolkit'; import { resetWorkflowState } from '../global'; +import { initWorkflowSpec } from '../workflow/workflowSlice'; import type { StateHistory, StateHistoryItem } from './undoRedoTypes'; export const initialState: StateHistory = { past: [], future: [], undoRedoClickToggle: 0, + activeHistoryTransactions: 0, }; export const undoRedoSlice = createSlice({ name: 'undoRedo', initialState, reducers: { + beginHistoryTransaction: (state) => { + state.activeHistoryTransactions = (state.activeHistoryTransactions ?? 0) + 1; + }, + endHistoryTransaction: (state) => { + state.activeHistoryTransactions = Math.max(0, (state.activeHistoryTransactions ?? 0) - 1); + }, saveStateToHistory: (state, action: PayloadAction<{ stateHistoryItem: StateHistoryItem; limit: number }>) => { state.past = [ ...(state.past.length < action.payload.limit ? state.past : state.past.slice(1, state.past.length)), @@ -56,9 +64,20 @@ export const undoRedoSlice = createSlice({ }, extraReducers: (builder) => { builder.addCase(resetWorkflowState, () => initialState); + // Host workflow reloads replace the graph without always dispatching resetWorkflowState; + // clear any in-flight history transaction counter so Undo/Redo/Duplicate cannot stay locked. + builder.addCase(initWorkflowSpec, (state) => { + state.activeHistoryTransactions = 0; + }); }, }); -export const { saveStateToHistory, updateStateHistoryOnUndoClick, updateStateHistoryOnRedoClick } = undoRedoSlice.actions; +export const { + beginHistoryTransaction, + endHistoryTransaction, + saveStateToHistory, + updateStateHistoryOnUndoClick, + updateStateHistoryOnRedoClick, +} = undoRedoSlice.actions; export default undoRedoSlice.reducer; diff --git a/libs/designer-v2/src/lib/core/state/undoRedo/undoRedoTypes.ts b/libs/designer-v2/src/lib/core/state/undoRedo/undoRedoTypes.ts index fc361f12298..a66596e21e7 100644 --- a/libs/designer-v2/src/lib/core/state/undoRedo/undoRedoTypes.ts +++ b/libs/designer-v2/src/lib/core/state/undoRedo/undoRedoTypes.ts @@ -19,6 +19,9 @@ export interface StateHistory { future: StateHistoryItem[]; // Toggle whenever undo/redo is clicked. This is needed to re-render parameter panel on undo/redo undoRedoClickToggle: number; + // Counts in-flight multi-step mutations (e.g. Shared Duplicate) that own a single undo checkpoint, + // blocking Undo/Redo and overlapping batches until the transaction settles. + activeHistoryTransactions?: number; // On undo/redo, we don't want to lose track of what the edited panel was for past/future state when we change the current state currentEditedPanelTab?: string; currentEditedPanelNode?: string; diff --git a/libs/designer-v2/src/lib/core/state/workflow/workflowInterfaces.ts b/libs/designer-v2/src/lib/core/state/workflow/workflowInterfaces.ts index 730b3e553d7..e66d6f5cf68 100644 --- a/libs/designer-v2/src/lib/core/state/workflow/workflowInterfaces.ts +++ b/libs/designer-v2/src/lib/core/state/workflow/workflowInterfaces.ts @@ -9,6 +9,13 @@ export interface AgentToolInvocation { page: number; } +export interface LoopRepetition { + runId: string; + name: string; + /** True when an admitted ancestor loop has zero iterations for the current outer coordinate. */ + isEmpty?: boolean; +} + export interface NodeMetadata { graphId: string; parentNodeId?: string; @@ -17,6 +24,9 @@ export interface NodeMetadata { isRoot?: boolean; isTrigger?: boolean; runData?: LogicAppsV2.WorkflowRunAction | LogicAppsV2.WorkflowRunTrigger; + runDataRepetition?: LoopRepetition; + runDataRepetitionSource?: LogicAppsV2.WorkflowRunAction; + loopPayloadRevision?: string; actionMetadata?: Record; subgraphRunData?: Record; subgraphRunDataIdentity?: string; diff --git a/libs/designer-v2/src/lib/core/state/workflow/workflowSelectors.ts b/libs/designer-v2/src/lib/core/state/workflow/workflowSelectors.ts index 7e5e3140178..b8e86ee5e8a 100644 --- a/libs/designer-v2/src/lib/core/state/workflow/workflowSelectors.ts +++ b/libs/designer-v2/src/lib/core/state/workflow/workflowSelectors.ts @@ -2,7 +2,7 @@ import commonConstants from '../../../common/constants'; import type { WorkflowEdge, WorkflowNode } from '../../parsers/models/workflowNode'; import type { RootState } from '../../store'; import { createWorkflowEdge, getAllParentsForNode } from '../../utils/graph'; -import type { NodesMetadata, WorkflowState } from './workflowInterfaces'; +import type { LoopRepetition, NodesMetadata, WorkflowState } from './workflowInterfaces'; import { getWorkflowNodeFromGraphState, getWorkflowGraphPath, buildNodeIndex } from './workflowGraphTraversal'; import type { LogicAppsV2 } from '@microsoft/logic-apps-shared'; import { @@ -17,7 +17,7 @@ import { } from '@microsoft/logic-apps-shared'; import { createSelector } from '@reduxjs/toolkit'; import { useMemo } from 'react'; -import { useSelector } from 'react-redux'; +import { shallowEqual, useSelector } from 'react-redux'; import Queue from 'yocto-queue'; import type {} from 'reselect'; import type {} from '@tanstack/react-query'; @@ -26,7 +26,7 @@ import { useEdges } from '@xyflow/react'; import { ErrorLevel } from '../operation/errorLevel'; import type { OperationMetadataState } from '../operation/operationMetadataSlice'; import { getOperationsState } from '../selectors/actionMetadataSelector'; -import { getAgentRepetitionIdentity, getScopeRepetitionName } from '../../utils/loopRepetitions'; +import { getAgentRepetitionIdentity, getLoopRepetition, getScopeRepetitionName, isSameLoopRepetition } from '../../utils/loopRepetitions'; export const getWorkflowState = (state: RootState): WorkflowState => state.workflow; @@ -643,16 +643,17 @@ const selectRunMode = createSelector(getWorkflowState, (state: WorkflowState) => export const useRunMode = (): string | null => useSelector(selectRunMode); -export const useRetryHistory = (id: string): LogicAppsV2.RetryHistory[] | undefined => - useSelector( - useMemo( - () => createSelector(getWorkflowState, (state: WorkflowState) => getRecordEntry(state.nodesMetadata, id)?.runData?.retryHistory), - [id] - ) - ); +const selectLoopRepetition = (state: RootState, id: string): LoopRepetition | undefined => + state.designerOptions?.useSharedNodeUi && state.designerOptions.isMonitoringView ? getLoopRepetition(state.workflow, id) : undefined; -export const getNodeRunData = (state: WorkflowState, id: string): NodesMetadata[string]['runData'] => { +export const useSelectedLoopRepetition = (id: string): LoopRepetition | undefined => + useSelector((state: RootState) => selectLoopRepetition(state, id), shallowEqual); + +export const getNodeRunData = (state: WorkflowState, id: string, repetition?: LoopRepetition): NodesMetadata[string]['runData'] => { const node = getRecordEntry(state.nodesMetadata, id); + if (repetition && !isSameLoopRepetition(node?.runDataRepetition, repetition)) { + return undefined; + } // Keep the previous tool result in state for a return to its cached repetition, but not in the open details panel. if ( node?.agentRepetitionIdentity && @@ -665,7 +666,15 @@ export const getNodeRunData = (state: WorkflowState, id: string): NodesMetadata[ }; export const useRunData = (id: string): NodesMetadata[string]['runData'] => - useSelector(useMemo(() => createSelector(getWorkflowState, (state: WorkflowState) => getNodeRunData(state, id)), [id])); + useSelector((state: RootState) => getNodeRunData(state.workflow, id, selectLoopRepetition(state, id))); + +export const useRetryHistory = (id: string): LogicAppsV2.RetryHistory[] | undefined => + useSelector((state: RootState) => { + const repetition = selectLoopRepetition(state, id); + return repetition + ? getNodeRunData(state.workflow, id, repetition)?.retryHistory + : getRecordEntry(state.workflow.nodesMetadata, id)?.runData?.retryHistory; + }); export const useToolRunData = (id: string): LogicAppsV2.WorkflowRunAction | LogicAppsV2.WorkflowRunTrigger | undefined => useSelector( diff --git a/libs/designer-v2/src/lib/core/state/workflow/workflowSlice.ts b/libs/designer-v2/src/lib/core/state/workflow/workflowSlice.ts index 496c52529d7..6ada1840c5a 100644 --- a/libs/designer-v2/src/lib/core/state/workflow/workflowSlice.ts +++ b/libs/designer-v2/src/lib/core/state/workflow/workflowSlice.ts @@ -32,7 +32,15 @@ import { updateStaticResults, } from '../operation/operationMetadataSlice'; import type { RelationshipIds } from '../panel/panelTypes'; -import type { AgentToolInvocation, ErrorMessage, SpecTypes, WorkflowState, WorkflowKind, NodeMetadata } from './workflowInterfaces'; +import type { + AgentToolInvocation, + ErrorMessage, + LoopRepetition, + SpecTypes, + WorkflowState, + WorkflowKind, + NodeMetadata, +} from './workflowInterfaces'; import type { BoundParameters } from '@microsoft/logic-apps-shared'; import { getParentsUncollapseFromGraphState, getSelectedAgentRepetitionIdentity, getWorkflowNodeFromGraphState } from './workflowSelectors'; import { @@ -59,6 +67,34 @@ import { initializeInputsOutputsBinding, fetchBuiltInToolRunData } from '../../a import { updateAgenticSubgraph, type UpdateAgenticGraphPayload } from '../../parsers/updateAgenticGraph'; import { isA2AWorkflow, shouldClearNodeRunData } from './helper'; import { UnsupportedExceptionCode } from '../../../common/exceptions/unsupported'; +import { getLoopRepetition, getLoopsCount, isSameLoopRepetition } from '../../utils/loopRepetitions'; +import isEqual from 'lodash.isequal'; + +const isLoopNode = (state: WorkflowState, nodeId: string): boolean => { + const type = getRecordEntry(state.operations, nodeId)?.type?.toLowerCase(); + return type === constants.NODE.TYPE.FOREACH || type === constants.NODE.TYPE.UNTIL; +}; + +const isDescendantOf = (nodesMetadata: WorkflowState['nodesMetadata'], nodeId: string, ancestorId: string): boolean => { + let parentId = getRecordEntry(nodesMetadata, nodeId)?.parentNodeId; + while (parentId) { + if (parentId === ancestorId) { + return true; + } + parentId = getRecordEntry(nodesMetadata, parentId)?.parentNodeId; + } + return false; +}; + +// When an outer loop switches iterations (or clamps to a shorter repetition count), reset +// nested loop pages to 0 so stale inner indices do not target out-of-range repetitions. +const resetDescendantLoopRunIndices = (state: WorkflowState, ancestorId: string) => { + for (const [candidateId, candidateMetadata] of Object.entries(state.nodesMetadata)) { + if (candidateId !== ancestorId && isLoopNode(state, candidateId) && isDescendantOf(state.nodesMetadata, candidateId, ancestorId)) { + selectRunPage(candidateMetadata, 0); + } + } +}; const clampToolPage = (page: number, count: number | undefined): number => Number.isInteger(count) ? Math.min(page, Math.max((count ?? 0) - 1, 0)) : page; @@ -462,7 +498,13 @@ export const workflowSlice = createSlice({ }, pasteNode: ( state: WorkflowState, - action: PayloadAction<{ nodeId: string; relationshipIds: RelationshipIds; operation: NodeOperation; isParallelBranch?: boolean }> + action: PayloadAction<{ + nodeId: string; + relationshipIds: RelationshipIds; + operation: NodeOperation; + isParallelBranch?: boolean; + skipUndoSnapshot?: boolean; + }> ) => { const graph = getWorkflowNodeFromGraphState(state, action.payload.relationshipIds.graphId); if (!graph) { @@ -908,7 +950,11 @@ export const workflowSlice = createSlice({ if (!nodeMetadata) { return; } + const changed = nodeMetadata.runIndex !== page; selectRunPage(nodeMetadata, page); + if (changed && isLoopNode(state, nodeId)) { + resetDescendantLoopRunIndices(state, nodeId); + } }, setToolRunIndex: (state: WorkflowState, action: PayloadAction<{ page: number; nodeId: string }>) => { const { page, nodeId } = action.payload; @@ -925,9 +971,17 @@ export const workflowSlice = createSlice({ }, setRepetitionRunData: ( state: WorkflowState, - action: PayloadAction<{ nodeId: string; runData: LogicAppsV2.WorkflowRunAction; agentToolInvocation?: AgentToolInvocation }> + { + payload, + }: PayloadAction<{ + nodeId: string; + runData: LogicAppsV2.WorkflowRunAction; + agentToolInvocation?: AgentToolInvocation; + loopRepetition?: LoopRepetition; + loopPayloadRevision?: string; + }> ) => { - const { nodeId, runData, agentToolInvocation } = action.payload; + const { nodeId, runData, agentToolInvocation, loopRepetition, loopPayloadRevision } = payload; const nodeMetadata = getRecordEntry(state.nodesMetadata, nodeId); if (!nodeMetadata) { return; @@ -937,8 +991,43 @@ export const workflowSlice = createSlice({ setToolInvocationRunData(nodeMetadata, agentToolInvocation, runData); return; } + if (loopRepetition && (!loopPayloadRevision || !isSameLoopRepetition(getLoopRepetition(state, nodeId), loopRepetition))) { + return; + } + const samePayload = + !!loopRepetition && + isSameLoopRepetition(nodeMetadata.runDataRepetition, loopRepetition) && + nodeMetadata.loopPayloadRevision === loopPayloadRevision; + if (samePayload && isEqual(nodeMetadata.runDataRepetitionSource, runData)) { + return; + } + const next = formatRepetitionRunData(runData); + if (loopRepetition) { + if (samePayload) { + // Status can refresh without changing the source of already-bound inputs and outputs. + next.inputs = nodeMetadata.runData?.inputs; + next.outputs = nodeMetadata.runData?.outputs; + } + nodeMetadata.loopPayloadRevision = loopPayloadRevision; + nodeMetadata.runDataRepetition = loopRepetition; + nodeMetadata.runDataRepetitionSource = runData; + } else { + delete nodeMetadata.runDataRepetition; + delete nodeMetadata.runDataRepetitionSource; + delete nodeMetadata.loopPayloadRevision; + } delete nodeMetadata.agentToolInvocation; - nodeMetadata.runData = formatRepetitionRunData(runData); + nodeMetadata.runData = next; + if (loopRepetition && isLoopNode(state, nodeId)) { + const count = getLoopsCount(next); + if (count !== undefined && count >= 0) { + const clampedPage = count === 0 ? 0 : Math.min(Math.max(0, nodeMetadata.runIndex ?? 0), count - 1); + if ((nodeMetadata.runIndex ?? 0) !== clampedPage) { + selectRunPage(nodeMetadata, clampedPage); + resetDescendantLoopRunIndices(state, nodeId); + } + } + } }, clearAllRepetitionRunData: (state: WorkflowState) => { for (const node of Object.values(state.nodesMetadata)) { @@ -953,6 +1042,9 @@ export const workflowSlice = createSlice({ // This is because root nodes typically represent the main workflow and their run data is needed for display for a2a agents if (shouldClearNodeRunData(node)) { delete node.runData; + delete node.runDataRepetition; + delete node.runDataRepetitionSource; + delete node.loopPayloadRevision; delete node.runIndex; } } @@ -1262,10 +1354,21 @@ export const workflowSlice = createSlice({ })); builder.addCase(initializeInputsOutputsBinding.fulfilled, (state, action) => { const { nodeId, inputs, outputs } = action.payload; + const loopRepetition = action.meta?.arg?.loopRepetition; + const loopPayloadRevision = action.meta?.arg?.loopPayloadRevision; const nodeMetadata = getRecordEntry(state.nodesMetadata, nodeId); if (!nodeMetadata) { return; } + if ( + loopRepetition && + (!isSameLoopRepetition(getLoopRepetition(state, nodeId), loopRepetition) || + !isSameLoopRepetition(nodeMetadata.runDataRepetition, loopRepetition) || + !loopPayloadRevision || + nodeMetadata.loopPayloadRevision !== loopPayloadRevision) + ) { + return; + } const existingInputs = nodeMetadata.runData?.inputs; const existingOutputs = nodeMetadata.runData?.outputs; diff --git a/libs/designer-v2/src/lib/core/store.ts b/libs/designer-v2/src/lib/core/store.ts index e716a690176..9e45b09565e 100644 --- a/libs/designer-v2/src/lib/core/store.ts +++ b/libs/designer-v2/src/lib/core/store.ts @@ -17,7 +17,12 @@ import knowledgeHubOptionsReducer from './state/knowledge/optionsSlice'; import { combineReducers, configureStore } from '@reduxjs/toolkit'; import type {} from 'redux-thunk'; -import { extractionMutationGuardMiddleware, monitoringDirtyGuardMiddleware, storeStateHistoryMiddleware } from './utils/middleware'; +import { + extractionMutationGuardMiddleware, + historyTransactionGuardMiddleware, + monitoringDirtyGuardMiddleware, + storeStateHistoryMiddleware, +} from './utils/middleware'; declare global { interface Window { @@ -53,7 +58,7 @@ export const createDesignerStore = (preloadedState?: ReturnType { @@ -16,6 +18,60 @@ export const getLoopsCount = (action: LogicAppsV2.WorkflowRunAction | undefined) export const getScopeRepetitionName = (index: number | undefined): string => String(index).padStart(6, '0'); +/** Use the same outer-to-inner coordinates for the request and for admission to the selected action. */ +export const getLoopRepetition = (state: WorkflowState, nodeId: string): LoopRepetition | undefined => { + const runId = state.runInstance?.id; + if ( + !runId || + state.workflowKind === 'agent' || + getRecordEntry(state.operations, nodeId)?.type?.toLowerCase() === constants.NODE.TYPE.AGENT + ) { + return undefined; + } + + const loopAncestors: { id: string; metadata: WorkflowState['nodesMetadata'][string] | undefined }[] = []; + let parentId = getRecordEntry(state.nodesMetadata, nodeId)?.parentNodeId; + while (parentId) { + const parent = getRecordEntry(state.nodesMetadata, parentId); + const type = getRecordEntry(state.operations, parentId)?.type?.toLowerCase(); + if (type === constants.NODE.TYPE.AGENT) { + return undefined; + } + if (type === constants.NODE.TYPE.FOREACH || type === constants.NODE.TYPE.UNTIL) { + loopAncestors.push({ id: parentId, metadata: parent }); + } + parentId = parent?.parentNodeId; + } + + if (loopAncestors.length === 0) { + return undefined; + } + + // Walk outer-to-inner so each nested loop's admitted runData is validated against its outer coordinate. + loopAncestors.reverse(); + const indexes: string[] = []; + for (let depth = 0; depth < loopAncestors.length; depth++) { + const { metadata } = loopAncestors[depth]; + const isAdmittedForOuterCoordinate = + depth === 0 ? !!metadata?.runData : isSameLoopRepetition(metadata?.runDataRepetition, { runId, name: indexes.join('-') }); + const admittedCount = isAdmittedForOuterCoordinate ? getLoopsCount(metadata?.runData) : undefined; + + if (admittedCount === 0) { + // Returning an empty coordinate hides stale child runData and suppresses impossible child repetition fetches. + return { runId, name: '', isEmpty: true }; + } + + const rawIndex = Math.max(0, metadata?.runIndex ?? 0); + const effectiveIndex = admittedCount !== undefined && admittedCount > 0 ? Math.min(rawIndex, admittedCount - 1) : rawIndex; + indexes.push(getScopeRepetitionName(effectiveIndex)); + } + + return { runId, name: indexes.join('-') }; +}; + +export const isSameLoopRepetition = (left: LoopRepetition | undefined, right: LoopRepetition): boolean => + !!left && !left.isEmpty && !right.isEmpty && left.runId === right.runId && left.name === right.name; + interface AgentRepetitionIdentityParams { runId: string | undefined; ownerNodeId: string | undefined; diff --git a/libs/designer-v2/src/lib/core/utils/middleware.ts b/libs/designer-v2/src/lib/core/utils/middleware.ts index 3fd28e37847..a963cd8668e 100644 --- a/libs/designer-v2/src/lib/core/utils/middleware.ts +++ b/libs/designer-v2/src/lib/core/utils/middleware.ts @@ -1,9 +1,18 @@ import { default as CONSTANTS } from '../../common/constants'; import { isExpressionConnectionMapping } from '../../common/models/workflow'; -import { saveStateToHistory } from '../state/undoRedo/undoRedoSlice'; +import { resetWorkflowState } from '../state/global'; +import { beginHistoryTransaction, endHistoryTransaction, saveStateToHistory } from '../state/undoRedo/undoRedoSlice'; import { undoableActionTypes } from '../state/undoRedo/undoRedoTypes'; import { renameConnectionExpressionParameter } from '../state/connection/connectionSlice'; -import { setIsWorkflowDirty } from '../state/workflow/workflowSlice'; +import { clearAllErrors } from '../state/operation/operationMetadataSlice'; +import { + initWorkflowSpec, + pasteNode, + setHasUnsupportedMultipleTriggers, + setIsWorkflowDirty, + setRunInstance, + setWorkflowKind, +} from '../state/workflow/workflowSlice'; import { setIsWorkflowParametersDirty } from '../state/workflowparameters/workflowparametersSlice'; import type { RootState } from '../store'; import { getCompressedSlicesFromRootState, getEditedPanelNode, getEditedPanelTab, shouldSkipSavingStateToHistory } from './undoredo'; @@ -12,24 +21,169 @@ import type { Middleware } from '@reduxjs/toolkit'; import { setWorkflowExtractionBusy } from '../state/designerView/designerViewSlice'; type DesignerThunk = (dispatch: (action: unknown) => unknown, getState: () => unknown, extraArgument: unknown) => unknown; +type ThunkGuardMeta = { + workflowGeneration?: number; + historyTransaction?: string; + blockedByHistoryTransaction?: boolean; +}; + const workflowGenerationMeta = 'workflowGeneration'; +const historyTransactionMeta = 'historyTransaction'; +const historyTransactionBlockedMeta = 'blockedByHistoryTransaction'; +const thunkMeta = new WeakMap(); + +const wrapThunkWithMeta = (thunk: DesignerThunk, patch: ThunkGuardMeta): DesignerThunk => { + const wrapped: DesignerThunk = (thunkDispatch, thunkGetState, extraArgument) => thunk(thunkDispatch, thunkGetState, extraArgument); + thunkMeta.set(wrapped, { ...thunkMeta.get(thunk), ...patch }); + return wrapped; +}; + +// Tags an action or thunk with the owning history transaction ID so historyTransactionGuardMiddleware +// lets the transaction's own nested async dispatches through while blocking unrelated mutations. +export const withHistoryTransaction = (action: TAction, transactionId: string): TAction => { + if (typeof action === 'function') { + return wrapThunkWithMeta(action as unknown as DesignerThunk, { historyTransaction: transactionId }) as unknown as TAction; + } + if (!action || typeof action !== 'object') { + return action; + } + return { + ...(action as Record), + meta: { + ...((action as { meta?: Record }).meta ?? {}), + [historyTransactionMeta]: transactionId, + }, + } as TAction; +}; + +const markBlockedByHistoryTransaction = (action: TAction): TAction => { + if (typeof action === 'function') { + return wrapThunkWithMeta(action as unknown as DesignerThunk, { blockedByHistoryTransaction: true }) as unknown as TAction; + } + if (!action || typeof action !== 'object') { + return action; + } + return { + ...(action as Record), + meta: { + ...((action as { meta?: Record }).meta ?? {}), + [historyTransactionBlockedMeta]: true, + }, + } as TAction; +}; + +// Non-mutating host/lifecycle and workflow-load actions that must remain allowed while a history +// transaction awaits async metadata (for example host read-only/monitoring locks, workflow reloads, +// and RTK lifecycle wrappers whose bodies already guard on activeHistoryTransactions). +const isAllowedDuringHistoryTransaction = (type: unknown): boolean => + typeof type === 'string' && + (type === resetWorkflowState.type || + type === clearAllErrors.type || + type === initWorkflowSpec.type || + type === setWorkflowKind.type || + type === setRunInstance.type || + type === 'panel/initRunInPanel' || + type === 'customCode/initCustomCode' || + type === setHasUnsupportedMultipleTriggers.type || + type.startsWith('initializeGraphState/') || + type.startsWith('designerOptions/') || + type.startsWith('designerView/') || + type.startsWith('dev/') || + type.startsWith('onUndoClick/') || + type.startsWith('onRedoClick/') || + type.startsWith('duplicateOperations/')); + +// Host lifecycle boundaries that replace the loaded workflow and invalidate any in-flight history +// transaction so its late async callbacks cannot write into the newly loaded graph. +const isHistoryTransactionCancelBoundary = (action: any): boolean => + resetWorkflowState.match(action) || initWorkflowSpec.match(action) || action?.type === 'initializeGraphState/pending'; + +// Keeps multi-step async mutations (e.g. Shared Duplicate awaiting scope metadata) atomic on the +// undo stack: only actions belonging to the active transaction (plus non-mutating host/lifecycle +// actions) may run until the transaction ends. Unrelated thunks started mid-transaction have their +// nested dispatches marked blocked so delayed callbacks cannot leak after the transaction finishes. +export const historyTransactionGuardMiddleware: Middleware = () => { + let activeTransactionId: string | undefined; + + return (next) => (action: any) => { + if (typeof action === 'function') { + const meta = thunkMeta.get(action); + if (meta?.blockedByHistoryTransaction) { + const blockedThunk: DesignerThunk = (thunkDispatch, thunkGetState, extraArgument) => + action((nestedAction: unknown) => thunkDispatch(markBlockedByHistoryTransaction(nestedAction)), thunkGetState, extraArgument); + thunkMeta.set(blockedThunk, meta); + return next(blockedThunk as any); + } + if (meta?.historyTransaction !== undefined) { + const txId = meta.historyTransaction; + const txBoundThunk: DesignerThunk = (thunkDispatch, thunkGetState, extraArgument) => + action((nestedAction: unknown) => thunkDispatch(withHistoryTransaction(nestedAction, txId)), thunkGetState, extraArgument); + thunkMeta.set(txBoundThunk, meta); + return next(txBoundThunk as any); + } + if (activeTransactionId !== undefined) { + const blockedThunk: DesignerThunk = (thunkDispatch, thunkGetState, extraArgument) => + action((nestedAction: unknown) => thunkDispatch(markBlockedByHistoryTransaction(nestedAction)), thunkGetState, extraArgument); + thunkMeta.set(blockedThunk, { ...meta, blockedByHistoryTransaction: true }); + return next(blockedThunk as any); + } + return next(action); + } + + if (isHistoryTransactionCancelBoundary(action)) { + activeTransactionId = undefined; + return next(action); + } + + if (action?.meta?.[historyTransactionBlockedMeta] && !isAllowedDuringHistoryTransaction(action?.type)) { + return action; + } + + const actionTxId: string | undefined = action?.meta?.[historyTransactionMeta]; + if (beginHistoryTransaction.match(action)) { + if (activeTransactionId !== undefined && actionTxId !== activeTransactionId) { + return action; + } + if (actionTxId !== undefined) { + activeTransactionId = actionTxId; + } + return next(action); + } + + if (endHistoryTransaction.match(action)) { + // Drop stray endHistoryTransaction dispatches from transactions already canceled by a reset/reload. + if (actionTxId !== undefined && actionTxId !== activeTransactionId) { + return action; + } + if (actionTxId !== undefined && actionTxId === activeTransactionId) { + activeTransactionId = undefined; + } + return next(action); + } + + // Any action tagged with a transaction ID belongs exclusively to that transaction; if the + // transaction was canceled (activeTransactionId is undefined or a newer ID), drop late writes. + if (actionTxId !== undefined && actionTxId !== activeTransactionId) { + return action; + } + + if (activeTransactionId !== undefined && actionTxId !== activeTransactionId && !isAllowedDuringHistoryTransaction(action?.type)) { + return action; + } + + return next(action); + }; +}; // Only the extraction transaction may modify the editor during persistence. Thunks // retain the graph generation in which they started, so callbacks from the previous // graph remain blocked even if they resume after the extraction lock is released. export const extractionMutationGuardMiddleware: Middleware = ({ dispatch, getState }) => { let workflowGeneration = 0; - const thunkGenerations = new WeakMap(); - - const bindThunkToGeneration = (thunk: DesignerThunk, generation: number): DesignerThunk => { - const boundThunk: DesignerThunk = (thunkDispatch, thunkGetState, extraArgument) => thunk(thunkDispatch, thunkGetState, extraArgument); - thunkGenerations.set(boundThunk, generation); - return boundThunk; - }; const bindActionToGeneration = (action: any, generation: number): any => { if (typeof action === 'function') { - return bindThunkToGeneration(action, generation); + return wrapThunkWithMeta(action, { workflowGeneration: generation }); } if (!action || typeof action !== 'object') { return action; @@ -44,7 +198,8 @@ export const extractionMutationGuardMiddleware: Middleware = ({ dispatch, getSta }; return (next) => (action: any) => { - const actionGeneration = typeof action === 'function' ? thunkGenerations.get(action) : action?.meta?.[workflowGenerationMeta]; + const actionGeneration = + typeof action === 'function' ? thunkMeta.get(action)?.workflowGeneration : action?.meta?.[workflowGenerationMeta]; if (actionGeneration !== undefined && actionGeneration !== workflowGeneration) { return action; } @@ -86,6 +241,12 @@ export const storeStateHistoryMiddleware: Middleware = if (!undoableActionTypes.includes(action.type)) { return next(action); } + if ( + (pasteNode.match(action) && action.payload?.skipUndoSnapshot) || + (action.type === 'pasteScopeOperation/pending' && action.meta?.arg?.skipUndoSnapshot) + ) { + return next(action); + } // Capture pre-mutation state references (cheap — Immer won't mutate these in-place) const preState = getState() as RootState; diff --git a/libs/designer-v2/src/lib/ui/CustomNodes/OperationCardNode.tsx b/libs/designer-v2/src/lib/ui/CustomNodes/OperationCardNode.tsx index 3d7eee344c5..f2fc628c65c 100644 --- a/libs/designer-v2/src/lib/ui/CustomNodes/OperationCardNode.tsx +++ b/libs/designer-v2/src/lib/ui/CustomNodes/OperationCardNode.tsx @@ -54,6 +54,7 @@ import { useToolRunIndex, useActionMetadata, useIsCopilotModifiedNode, + useSelectedLoopRepetition, } from '../../core/state/workflow/workflowSelectors'; import { useIsA2AWorkflow } from '../../core/state/designerView/designerViewSelectors'; import { setRepetitionRunData } from '../../core/state/workflow/workflowSlice'; @@ -77,6 +78,7 @@ import { OperationNodeCard } from './components/card/OperationNodeCard'; import { hasMcpToolPager, type NodePresentation } from '../../core/utils/graph'; import { nodeMetrics } from '@microsoft/designer-ui-v2/metrics'; import { useInitialMountSettled } from '../../core/hooks/useInitialMountSettled'; +import { useLoopRepetitionAdmission } from '../../core/hooks/useLoopRepetitionAdmission'; type OperationGraphNode = Node<{ presentation?: NodePresentation; handleAxis?: 'vertical' | 'horizontal' }>; @@ -91,7 +93,7 @@ interface NodeRunDataSyncProps { } /** Loads repetition and agent tool run data; mounted only in monitoring view so editing cards skip these subscriptions. */ -const NodeRunDataSync = ({ +export const NodeRunDataSync = ({ id, graphId, parentNodeId, @@ -106,6 +108,7 @@ const NodeRunDataSync = ({ const runInstance = useRunInstance(); const parentRunData = useRunData(parentNodeId ?? ''); const repetitionName = useRepetitionName(parentRunIndex, id, operationsInfo); + const loopRepetition = useSelectedLoopRepetition(id); const isWithinAgenticLoop = useIsWithinAgenticLoop(graphId); const parentSubgraphRunData = useSubgraphRunData(parentNodeId ?? ''); const parentMetadata = useNodeMetadata(parentNodeId ?? ''); @@ -114,11 +117,12 @@ const NodeRunDataSync = ({ const ownRunIndex = useRunIndex(id); const mcpToolRunIndex = useToolRunIndex(id); + const effectiveRepetitionName = loopRepetition ? (loopRepetition.isEmpty ? undefined : loopRepetition.name) : repetitionName; const { isFetching: isRepetitionFetching, data: repetitionRunData } = useNodeRepetition( - !!runInstance, + !!runInstance && !loopRepetition?.isEmpty, id, runInstance?.id, - repetitionName, + effectiveRepetitionName, parentRunData?.status, parentRunIndex, isWithinAgenticLoop @@ -130,18 +134,22 @@ const NodeRunDataSync = ({ useEffect(() => () => onFetchingChange(false), [onFetchingChange]); + useLoopRepetitionAdmission(id, isWithinAgenticLoop ? undefined : loopRepetition, repetitionRunData); + const legacyTrackingId = loopRepetition ? undefined : selfActionTrackingId; useEffect(() => { - if (!isNullOrUndefined(repetitionRunData)) { - if ( - !isNullOrUndefined(selfActionTrackingId) && - selfActionTrackingId === repetitionRunData?.properties?.correlation?.actionTrackingId - ) { + if (!loopRepetition && !isNullOrUndefined(repetitionRunData)) { + if (!isNullOrUndefined(legacyTrackingId) && legacyTrackingId === repetitionRunData.properties?.correlation?.actionTrackingId) { // if the correlation id is the same, we don't need to update the repetition run data return; } - dispatch(setRepetitionRunData({ nodeId: id, runData: repetitionRunData.properties as LogicAppsV2.WorkflowRunAction })); + dispatch( + setRepetitionRunData({ + nodeId: id, + runData: repetitionRunData.properties as LogicAppsV2.WorkflowRunAction, + }) + ); } - }, [dispatch, repetitionRunData, id, selfActionTrackingId]); + }, [dispatch, repetitionRunData, id, legacyTrackingId, loopRepetition]); const actualToolRunIndex = isMcpClientSubgraph ? mcpToolRunIndex : scopedAgentRepetitionIdentity ? ownRunIndex : toolRunIndex; const hasCurrentToolResults = diff --git a/libs/designer-v2/src/lib/ui/CustomNodes/ScopeCardNode.tsx b/libs/designer-v2/src/lib/ui/CustomNodes/ScopeCardNode.tsx index 3eb67c39875..1f1a74b954d 100644 --- a/libs/designer-v2/src/lib/ui/CustomNodes/ScopeCardNode.tsx +++ b/libs/designer-v2/src/lib/ui/CustomNodes/ScopeCardNode.tsx @@ -33,6 +33,7 @@ import { useIsActionInSelectedTimelineRepetition, useHandoffActionsForAgent, useFlowErrorsForNode, + useSelectedLoopRepetition, } from '../../core/state/workflow/workflowSelectors'; import { setFocusElement, @@ -78,6 +79,7 @@ import type { ComponentProps } from 'react'; import type { NodeFrameCountLabel } from '@microsoft/designer-ui-v2'; import { getNodePresentation, type NodePresentation } from '../../core/utils/graph'; import { getScopeModel } from './components/card/scopeNodePresentation'; +import { useLoopRepetitionAdmission } from '../../core/hooks/useLoopRepetitionAdmission'; type BranchPort = { id: string; subgraphType?: string }; @@ -192,7 +194,7 @@ const ScopeCardNode = ({ id, data }: NodeProps) => { const runData = useRunData(scopeId); const parentNodeId = useParentNodeId(scopeId); const parentRunData = useRunData(parentNodeId ?? ''); - const selfRunData = useRunData(scopeId); + const loopRepetition = useSelectedLoopRepetition(scopeId); const selected = useIsNodeSelectedInOperationPanel(scopeId); const isMultiSelected = useIsNodeInMultiSelection(scopeId); const isPinned = useIsNodePinnedToOperationPanel(scopeId); @@ -221,10 +223,11 @@ const ScopeCardNode = ({ id, data }: NodeProps) => { [shared, isA2AWorkflow, selectedAgentRunId, scopeId, scopeRepetitionName, runIndex, parentRunData?.status] ); const admittedAgentRepetition = useRef<{ identity: string; data: LogicAppsV2.RunRepetition }>(); - const repetitionName = useRepetitionName(parentRunIndex, scopeId, operationsInfo); + const legacyRepetitionName = useRepetitionName(parentRunIndex, scopeId, operationsInfo); + const repetitionName = loopRepetition ? (loopRepetition.isEmpty ? undefined : loopRepetition.name) : legacyRepetitionName; const rootRef = useRef(null); const { isFetching: isRepetitionFetching, data: repetitionRunData } = useNodeRepetition( - !!isMonitoringView && !!runInstance, + !!isMonitoringView && !!runInstance && !loopRepetition?.isEmpty, scopeId, runInstance?.id, repetitionName, @@ -235,7 +238,11 @@ const ScopeCardNode = ({ id, data }: NodeProps) => { // A nested condition can still have the previous iteration's runData in Redux while the new query loads. const usesRepetition = !!runInstance && parentRunIndex !== undefined; const showConditionOutcome = !!(shared && !id.endsWith('#footer') && isMonitoringView && (isConditional || isSwitch)); - const outcomeRun = usesRepetition ? (isTimelineRepetitionSelected ? repetitionRunData?.properties : undefined) : runData; + const outcomeRun = usesRepetition + ? isTimelineRepetitionSelected && !loopRepetition?.isEmpty + ? repetitionRunData?.properties + : undefined + : runData; const inlineResult = showConditionOutcome && outcomeRun && 'outputs' in outcomeRun ? getExpressionResultFromOutputs(outcomeRun.outputs) : undefined; const linkedOutputs = useConditionOutputs( @@ -243,7 +250,8 @@ const ScopeCardNode = ({ id, data }: NodeProps) => { runInstance?.id, repetitionName, outcomeRun, - showConditionOutcome && isNullOrUndefined(inlineResult) + showConditionOutcome && isNullOrUndefined(inlineResult), + usesRepetition ? repetitionRunData?.loopPayloadRevision : undefined ); const { isFetching: isAgentRepetitionFetching, data: agentRepetitionRunData } = useAgentRepetition( @@ -311,7 +319,7 @@ const ScopeCardNode = ({ id, data }: NodeProps) => { dispatch, agentRepetitionRunData, scopeId, - selfRunData?.correlation?.actionTrackingId, + runData?.correlation?.actionTrackingId, isMonitoringView, isTimelineRepetitionSelected, metadata, @@ -320,19 +328,26 @@ const ScopeCardNode = ({ id, data }: NodeProps) => { scopeRepetitionName, ]); + useLoopRepetitionAdmission(scopeId, isMonitoringView && isTimelineRepetitionSelected ? loopRepetition : undefined, repetitionRunData); + const legacyTrackingId = loopRepetition ? undefined : runData?.correlation?.actionTrackingId; useEffect(() => { - if (isMonitoringView && !isTimelineRepetitionSelected) { + if (loopRepetition || (isMonitoringView && !isTimelineRepetitionSelected)) { return; } if (isNullOrUndefined(repetitionRunData)) { return; } - if (selfRunData?.correlation?.actionTrackingId === repetitionRunData?.properties?.correlation?.actionTrackingId) { + if (legacyTrackingId === repetitionRunData.properties?.correlation?.actionTrackingId) { // if the correlation id is the same, we don't need to update the repetition run data return; } - dispatch(setRepetitionRunData({ nodeId: scopeId, runData: repetitionRunData.properties as LogicAppsV2.WorkflowRunAction })); - }, [dispatch, isMonitoringView, isTimelineRepetitionSelected, repetitionRunData, scopeId, selfRunData?.correlation?.actionTrackingId]); + dispatch( + setRepetitionRunData({ + nodeId: scopeId, + runData: repetitionRunData.properties as LogicAppsV2.WorkflowRunAction, + }) + ); + }, [dispatch, isMonitoringView, isTimelineRepetitionSelected, repetitionRunData, scopeId, legacyTrackingId, loopRepetition]); const { dependencies, loopSources } = useTokenDependencies(scopeId); const [{ isDragging }, drag, dragPreview] = useDrag( @@ -569,16 +584,32 @@ const ScopeCardNode = ({ id, data }: NodeProps) => { const renderLoopsPager = useMemo(() => { // The Agent's own pager selects repetitions; keep it usable while the tool cards wait for the requested page. - if (!Array.isArray(metadata?.runData) && metadata?.runData?.status && !equals(metadata.runData.status, 'InProgress')) { + // Nested loop counts belong to the current outer repetition, just like the card status. + const pagerMetadata = loopRepetition && metadata ? { ...metadata, runData } : metadata; + if ( + pagerMetadata && + !Array.isArray(pagerMetadata.runData) && + pagerMetadata.runData?.status && + !equals(pagerMetadata.runData.status, 'InProgress') + ) { const focusElement = (index: number, id: string) => { dispatch(setFocusElement(`${id}-${index}-0`)); }; // Flag-on swaps only the pager presentation; run-index state and focus behavior stay identical. - const Pager = shared ? SharedLoopsPager : LoopsPager; - return ; + return shared ? ( + + ) : ( + + ); } return null; - }, [dispatch, graphCollapsed, metadata, scopeId, shared]); + }, [dispatch, graphCollapsed, loopRepetition, metadata, presentation.family, runData, scopeId, shared]); const nodeIndex = useNodeIndex(id); 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 c853a775d9b..095227b1e0f 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 @@ -140,6 +140,7 @@ const mockUseIsLeafNode = vi.fn().mockReturnValue(false); const mockUseParentNodeId = vi.fn().mockReturnValue(undefined); const mockUseRunInstance = vi.fn().mockReturnValue(undefined); const mockUseParentRunIndex = vi.fn().mockReturnValue(undefined); +const mockUseSelectedLoopRepetition = vi.fn().mockReturnValue(undefined); const mockUseIsWithinAgenticLoop = vi.fn().mockReturnValue(false); const mockUseSubgraphRunData = vi.fn().mockReturnValue(undefined); const mockUseRunIndex = vi.fn().mockReturnValue(undefined); @@ -153,6 +154,7 @@ vi.mock('../../../core/state/workflow/workflowSelectors', () => ({ useNodeDisplayName: (...args: any[]) => mockUseNodeDisplayName(...args), useNodeMetadata: (...args: any[]) => mockUseNodeMetadata(...args), useRunData: (...args: any[]) => mockUseRunData(...args), + useSelectedLoopRepetition: (...args: any[]) => mockUseSelectedLoopRepetition(...args), useShouldNodeFocus: (...args: any[]) => mockUseShouldNodeFocus(...args), useIsLeafNode: (...args: any[]) => mockUseIsLeafNode(...args), useParentNodeId: (...args: any[]) => mockUseParentNodeId(...args), @@ -299,6 +301,7 @@ describe('OperationCardNode (v2)', () => { mockUseParentNodeId.mockReturnValue(undefined); mockUseRunInstance.mockReturnValue(undefined); mockUseParentRunIndex.mockReturnValue(undefined); + mockUseSelectedLoopRepetition.mockReturnValue(undefined); mockUseIsWithinAgenticLoop.mockReturnValue(false); mockUseSubgraphRunData.mockReturnValue(undefined); mockUseRunIndex.mockReturnValue(undefined); @@ -504,6 +507,27 @@ describe('OperationCardNode (v2)', () => { ); }); + it('updates Shared loop run data on a different page even when both responses have the same tracking ID', () => { + const selection = { runId: 'run-1', name: '000002-000001' }; + const correlation = { actionTrackingId: 'same-id' }; + const runData = { status: 'Succeeded', correlation }; + mockUseSharedNodeUi.mockReturnValue(true); + mockUseMonitoringView.mockReturnValue(true); + mockUseRunInstance.mockReturnValue({ id: selection.runId }); + mockUseParentRunIndex.mockReturnValue(1); + mockUseSelectedLoopRepetition.mockReturnValue(selection); + mockUseRunData.mockImplementation((id: string) => (id === 'testNode' ? { status: 'Failed', correlation } : undefined)); + mockUseNodeRepetition.mockReturnValue({ isFetching: false, data: { properties: runData, loopPayloadRevision: 'scoped-payload' } }); + + render(); + + expect(mockUseNodeRepetition).toHaveBeenCalledWith(true, 'testNode', selection.runId, selection.name, undefined, 1, false); + expect(mockDispatch).toHaveBeenCalledWith({ + type: 'workflow/setRepetitionRunData', + payload: { nodeId: 'testNode', runData, loopRepetition: selection, loopPayloadRevision: 'scoped-payload' }, + }); + }); + it('uses actual immediate Agent parent metadata for tool identity, never the display name', () => { mockUseSharedNodeUi.mockReturnValue(true); mockUseParentNodeId.mockReturnValue('actual-agent'); 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 98907699925..1482c1068b6 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 @@ -138,6 +138,7 @@ vi.mock('../../../core/state/workflow/workflowSelectors', () => ({ useNodeMetadata: (...args: any[]) => mockUseNodeMetadata(...args), useParentNodeId: (...args: any[]) => mockUseParentNodeId(...args), useRunData: (...args: any[]) => mockUseRunData(...args), + useSelectedLoopRepetition: () => undefined, useRunIndex: (...args: any[]) => mockUseRunIndex(...args), useRunInstance: () => mockUseRunInstance(), useParentRunIndex: (...args: any[]) => mockUseParentRunIndex(...args), 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 919d598f899..85cdbe25cd0 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 @@ -46,7 +46,7 @@ import { mapSharedRunVisuals, mapToolNodeStrings, } from './nodeUiStrings'; -import { agentNodeTone, scopeNodeIcon } from './operationNodeGlyphs'; +import { agentNodeTone, getControlOperationGlyph, scopeNodeIcon } from './operationNodeGlyphs'; import { getNodePresentation, SHARED_SCOPE_TITLE_RESERVE, type NodePresentation } from '../../../../core/utils/graph'; import { SharedNodeHoverCard } from './SharedNodeHoverCard'; import { useOperationParameterByName } from '../../../../core/state/operation/operationSelector'; @@ -225,12 +225,21 @@ export const SharedScopeCard = ({ ), }; + const hoverCategory = family === 'agent' ? 'agent' : family === 'scope' ? 'action' : 'control'; + const hoverIcon = + family === 'if' || family === 'switch' + ? getControlOperationGlyph(family)?.icon + : family === 'loop' + ? getControlOperationGlyph('foreach')?.icon + : family === 'scope' + ? scopeNodeIcon + : undefined; const withHover = (card: ReactNode) => ( { tool.rerender(); expect(tool.container.querySelector('[data-node-card="tool"]')).toHaveAttribute('aria-label', `${toolName}, Waiting 1m`); }); + + it.each([ + ['switch', 'control', 'ArrowTurnRightRegular'], + ['loop', 'control', 'ArrowRepeatAllRegular'], + ['scope', 'action', 'BoxMultipleRegular'], + ] as const)( + 'passes the matching %s glyph and category to the hover card instead of falling back to If', + (family, expectedCategory, expectedIcon) => { + vi.useFakeTimers(); + try { + const { container } = render(); + const trigger = container.querySelector('[data-node-card]')!.parentElement!; + fireEvent.mouseOver(trigger); + act(() => { + vi.advanceTimersByTime(1000); + }); + const infoCard = document.querySelector('[data-node-info-card]'); + expect(infoCard).not.toBeNull(); + expect(infoCard!.querySelector(`[data-category="${expectedCategory}"] [data-icon-name="${expectedIcon}"]`)).not.toBeNull(); + } finally { + vi.useRealTimers(); + } + } + ); }); diff --git a/libs/designer-v2/src/lib/ui/CustomNodes/components/card/operationNodeGlyphs.tsx b/libs/designer-v2/src/lib/ui/CustomNodes/components/card/operationNodeGlyphs.tsx index 4c4ba164056..24e25fda3fa 100644 --- a/libs/designer-v2/src/lib/ui/CustomNodes/components/card/operationNodeGlyphs.tsx +++ b/libs/designer-v2/src/lib/ui/CustomNodes/components/card/operationNodeGlyphs.tsx @@ -1,7 +1,15 @@ import type { ReactNode } from 'react'; -import { getNodeGlyph, type NodeIconTone, type NodeVisualKind } from '@microsoft/designer-ui-v2'; +import { getNodeGlyph, IfIconRegular, IfIconFilled, type NodeIconTone, type NodeVisualKind } from '@microsoft/designer-ui-v2'; import { isBuiltInOperation } from '@microsoft/logic-apps-shared'; -import { AgentsFilled, AgentsRegular, BoxMultipleRegular } from '@fluentui/react-icons'; +import { + AgentsFilled, + AgentsRegular, + ArrowRepeatAllFilled, + ArrowRepeatAllRegular, + ArrowTurnRightFilled, + ArrowTurnRightRegular, + BoxMultipleRegular, +} from '@fluentui/react-icons'; export const scopeNodeIcon = ; /** Agent headers render the card's own Agent glyph, so adapters pass this family tone directly. */ @@ -14,6 +22,17 @@ export interface OperationNodeGlyph { tone?: NodeIconTone; } +const loopGlyph = { icon: , selectedIcon: }; +const controlGlyphs = new Map([ + ['if', { icon: , selectedIcon: }], + ['switch', { icon: , selectedIcon: }], + ['foreach', loopGlyph], + ['until', loopGlyph], + ['scope', { icon: scopeNodeIcon, selectedIcon: scopeNodeIcon }], +]); + +export const getControlOperationGlyph = (type: string) => controlGlyphs.get(type.toLowerCase()); + // Tones mirror the legacy designer's brand colors per family (Request teal, HTTP green, variables purple, // data operations violet, Terminate red) so built-ins stay recognizable without per-operation artwork. const groups: { types: readonly string[]; visualKind: NodeVisualKind; tone: NodeIconTone }[] = [ @@ -45,7 +64,16 @@ const groups: { types: readonly string[]; visualKind: NodeVisualKind; tone: Node tone: 'blue', }, { - types: ['javascriptcode', 'inlinejavascript', 'pythoncode', 'executepythoncode', 'inlinepython', 'powershellcode', 'csharpscriptcode'], + types: [ + 'javascriptcode', + 'inlinejavascript', + 'pythoncode', + 'executepythoncode', + 'inlinepython', + 'powershellcode', + 'csharpscriptcode', + 'csharpcode', + ], visualKind: 'inlineCode', tone: 'blue', }, diff --git a/libs/designer-v2/src/lib/ui/__test__/sharedNodeGlyph.spec.tsx b/libs/designer-v2/src/lib/ui/__test__/sharedNodeGlyph.spec.tsx new file mode 100644 index 00000000000..b256305edcf --- /dev/null +++ b/libs/designer-v2/src/lib/ui/__test__/sharedNodeGlyph.spec.tsx @@ -0,0 +1,154 @@ +import { getPickerOperationGlyph } from '../sharedNodeGlyph'; +import { getOperationCardDataFromOperation } from '../panel/recommendation/helpers'; +import { FluentProvider, webLightTheme } from '@fluentui/react-components'; +import { + composeOperation, + csvTableOperation, + currentTimeOperation, + delayUntilOperation, + htmlTableOperation, + httpSwaggerActionOperation, + httpSwaggerTriggerOperation, + ifOperation, + recurrenceOperation, + requestOperation, + scopeOperation, +} from '@microsoft/logic-apps-shared'; +import { render } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; + +describe('sharedNodeGlyph', () => { + it.each([ + { operation: composeOperation, glyph: 'BracesRegular', tone: 'violet' }, + { operation: currentTimeOperation, glyph: 'CalendarClockRegular', tone: 'blue' }, + { operation: csvTableOperation, glyph: 'TableRegular', tone: 'violet' }, + { operation: htmlTableOperation, glyph: 'TableRegular', tone: 'violet' }, + { operation: delayUntilOperation, glyph: 'TimerRegular', tone: 'blue' }, + { operation: httpSwaggerActionOperation, glyph: 'GlobeRegular', tone: 'green' }, + { operation: httpSwaggerTriggerOperation, glyph: 'GlobeRegular', tone: 'green' }, + { operation: recurrenceOperation, glyph: 'ClockRegular', tone: 'blue' }, + { operation: requestOperation, glyph: 'GlobeRegular', tone: 'teal' }, + ])('renders the canonical $glyph with $tone tone for an exact operation regardless of its label', ({ operation, glyph, tone }) => { + const renamed = { ...operation, name: 'Renamed action', properties: { ...operation.properties, summary: 'Renamed action' } }; + const tile = getPickerOperationGlyph(renamed); + const { container } = render({tile}); + + const icon = container.querySelector(`[data-tone="${tone}"] [data-icon-name="${glyph}"]`); + expect(icon).toBeInTheDocument(); + expect(icon?.closest('[aria-hidden]')).toHaveAttribute('aria-hidden', 'true'); + }); + + it.each([ + { + reason: 'a different provider reuses a known ID, label, and type', + operation: { + ...composeOperation, + properties: { + ...composeOperation.properties, + api: { ...composeOperation.properties.api, id: 'connectionProviders/unrelated' }, + }, + }, + }, + { + reason: 'the provider matches but the operation ID is unknown', + operation: { ...composeOperation, id: 'unknown-compose' }, + }, + { + reason: 'raw type conflicts with the known operation metadata', + operation: { ...composeOperation, type: 'ParseJson' }, + }, + { + reason: 'an Expression has no kind', + operation: { ...currentTimeOperation, kind: undefined, properties: { ...currentTimeOperation.properties, operationKind: undefined } }, + }, + { + reason: 'the Expression kind conflicts with the known operation metadata', + operation: { ...currentTimeOperation, kind: 'GetFutureTime' }, + }, + ])('preserves existing artwork when $reason', ({ operation }) => { + expect(getPickerOperationGlyph(operation)).toBeUndefined(); + }); + + it('reuses the condition glyph for an exact built-in If operation', () => { + const tile = getPickerOperationGlyph(ifOperation); + const { container } = render({tile}); + + expect(container.querySelector('[data-node-glyph] [data-icon-name="BranchForkRegular"]')).toBeInTheDocument(); + }); + + it('keeps Scope in the same tile category as its canvas action card', () => { + const { container } = render({getPickerOperationGlyph(scopeOperation)}); + expect(container.querySelector('[data-category="action"] [data-icon-name="BoxMultipleRegular"]')).toBeInTheDocument(); + }); + + it.each([ + { + label: 'Standard CSharpCode', + operation: { + id: 'cSharpCode', + name: 'cSharpCode', + type: 'cSharpCode', + properties: { + api: { id: 'connectionProviders/inlineCode', name: 'inlineCode', displayName: 'Inline Code' }, + summary: 'Execute C Sharp Code', + operationType: 'CSharpCode', + }, + }, + selector: '[data-tone="blue"] [data-icon-name="CodeRegular"]', + }, + { + label: 'Standard invokeNestedAgent', + operation: { + id: 'invokenestedagent', + name: 'invokeNestedAgent', + type: 'nestedagent', + properties: { + api: { id: 'connectionProviders/workflow', name: 'connectionProviders/workflow', displayName: 'Azure Logic Apps' }, + summary: 'Choose a Logic Apps workflow', + operationType: 'NestedAgent', + }, + }, + selector: '[data-tone="pink"] [data-icon-name="AgentsRegular"]', + }, + { + label: 'Consumption invokeWorkflowOperation', + operation: { + id: 'invokeworkflow', + name: 'invokeworkflow', + type: 'invokeworkflow', + properties: { + api: { id: '/connectionProviders/workflow', name: 'connectionProviders/workflow', displayName: 'Azure Logic Apps' }, + summary: 'Choose a Logic Apps workflow', + operationType: 'Workflow', + }, + }, + selector: '[data-tone="blue"] [data-icon-name="FlowRegular"]', + }, + { + label: 'Consumption a2aRequestOperation', + operation: { + id: 'a2aRequest', + name: 'a2aRequest', + type: 'Request', + kind: 'Agent', + properties: { + api: { id: 'connectionProviders/a2aconsumption', name: 'a2aRequest', displayName: 'Agent Request' }, + summary: 'When a new chat session started', + operationType: 'Request', + operationKind: 'Agent', + trigger: 'single', + }, + }, + selector: '[data-tone="teal"] [data-icon-name="GlobeRegular"]', + }, + ])('matches real $label discovery payload', ({ operation, selector }) => { + const tile = getPickerOperationGlyph(operation as any); + const { container } = render({tile}); + expect(container.querySelector(selector)).toBeInTheDocument(); + }); + + it('populates icon in getOperationCardDataFromOperation only when sharedNodeUi is enabled', () => { + expect(getOperationCardDataFromOperation(composeOperation, false).icon).toBeUndefined(); + expect(getOperationCardDataFromOperation(composeOperation, true).icon).toBeDefined(); + }); +}); diff --git a/libs/designer-v2/src/lib/ui/common/LoopsPager/SharedLoopsPager.tsx b/libs/designer-v2/src/lib/ui/common/LoopsPager/SharedLoopsPager.tsx index 6de4e164cb6..540de34f70c 100644 --- a/libs/designer-v2/src/lib/ui/common/LoopsPager/SharedLoopsPager.tsx +++ b/libs/designer-v2/src/lib/ui/common/LoopsPager/SharedLoopsPager.tsx @@ -1,5 +1,6 @@ import { useScopeFailedRepetitions, type AppDispatch } from '../../../core'; -import { useActionMetadata, useNodeMetadata, useRunInstance } from '../../../core/state/workflow/workflowSelectors'; +import constants from '../../../common/constants'; +import { useActionMetadata, useNodeMetadata, useParentRunIndexes, useRunInstance } from '../../../core/state/workflow/workflowSelectors'; import { setRunIndex, setToolRunIndex } from '../../../core/state/workflow/workflowSlice'; import { getLoopsCount } from './helper'; import type { LoopsPagerProps } from './LoopsPager'; @@ -13,18 +14,34 @@ import { useDispatch } from 'react-redux'; * Flag-on counterpart of `LoopsPager`. Run-state reads and guards intentionally mirror the legacy pager * so only the presentation changes; the shared pager stays pure props and the host owns dispatch. */ -export const SharedLoopsPager = ({ metadata, scopeId, collapsed, focusElement, useToolRun }: LoopsPagerProps) => { +export const SharedLoopsPager = ({ + metadata, + scopeId, + collapsed, + focusElement, + useToolRun, + inLoopCardRow, +}: LoopsPagerProps & { inLoopCardRow?: boolean }) => { const intl = useIntl(); const runInstance = useRunInstance(); const dispatch = useDispatch(); const actionMetadata = useActionMetadata(scopeId); const normalizedType = useMemo(() => actionMetadata?.type.toLowerCase(), [actionMetadata]); const nodeMetadata = useNodeMetadata(scopeId); + const parentRunIndexes = useParentRunIndexes(scopeId); const currentPage = (useToolRun ? nodeMetadata?.toolRunIndex : nodeMetadata?.runIndex) ?? 0; const loopsCount = getLoopsCount(useToolRun ? metadata?.toolRunData : metadata?.runData); // Same failure source as legacy: the query only runs for Foreach/Until scopes, so tool-run pagers (MCP) // currently receive no failures and show no failed jumps. A tool-specific failure source is a follow-up. - const { isError, isFetching, data: failedRepetitions } = useScopeFailedRepetitions(normalizedType ?? '', scopeId, runInstance?.id); + const { + isError, + isFetching, + isPreviousData, + data: failedRepetitions, + } = useScopeFailedRepetitions(normalizedType ?? '', scopeId, runInstance?.id); + const isLoopScope = normalizedType === constants.NODE.TYPE.FOREACH || normalizedType === constants.NODE.TYPE.UNTIL; + // The failure query identifies the run and loop, but not the selected iteration of a repeating parent. + const canPickFailures = !!runInstance?.id && isLoopScope && !useToolRun && !isPreviousData && Object.keys(parentRunIndexes).length === 0; const strings = useMemo( () => ({ @@ -59,6 +76,34 @@ export const SharedLoopsPager = ({ metadata, scopeId, collapsed, focusElement, u { defaultMessage: '{current} of {count}', id: 'oMf+lk', description: 'Current loop iteration out of the total iteration count' }, { current, count } ), + failedDestinationSelect: intl.formatMessage({ + defaultMessage: 'Jump to failed iteration', + id: '5QUuaP', + description: 'Accessible name and tooltip for failed-iteration destination select in the loop pager', + }), + failedDestinationPrompt: intl.formatMessage({ + defaultMessage: 'Failed…', + id: '5UmjLL', + description: 'Visible compact prompt text for failed-iteration destination select in the loop pager', + }), + failedDestinationOption: (iteration) => + intl.formatMessage( + { + defaultMessage: 'Failed iteration {iteration}', + id: '9hDI1a', + description: 'Option label for a failed loop iteration destination in the loop pager', + }, + { iteration } + ), + failedDestinationRange: (first, last) => + intl.formatMessage( + { + defaultMessage: 'Failed iterations {first} to {last}', + id: 'YrNXP1', + description: 'Submenu label for a range of failed loop iteration destinations', + }, + { first, last } + ), }), [intl] ); @@ -83,8 +128,10 @@ export const SharedLoopsPager = ({ metadata, scopeId, collapsed, focusElement, u current={currentPage} count={loopsCount} onChange={onChange} - // Legacy only shows failed jumps when failures exist; an empty list would render disabled buttons. - failed={failedRepetitions?.length ? failedRepetitions : undefined} + // Legacy only shows failed jumps when failures exist; suppress stale failures from a previous run. + failed={!isPreviousData && failedRepetitions?.length ? failedRepetitions : undefined} + failedDestinations={canPickFailures ? failedRepetitions : undefined} + compactFailureNavigation={inLoopCardRow && normalizedType === constants.NODE.TYPE.FOREACH} editable strings={strings} /> diff --git a/libs/designer-v2/src/lib/ui/common/LoopsPager/__test__/sharedLoopsPager.spec.tsx b/libs/designer-v2/src/lib/ui/common/LoopsPager/__test__/sharedLoopsPager.spec.tsx index 996089dde59..3fd7f4c6761 100644 --- a/libs/designer-v2/src/lib/ui/common/LoopsPager/__test__/sharedLoopsPager.spec.tsx +++ b/libs/designer-v2/src/lib/ui/common/LoopsPager/__test__/sharedLoopsPager.spec.tsx @@ -7,8 +7,16 @@ import { setRunIndex, setToolRunIndex } from '../../../../core/state/workflow/wo const state = vi.hoisted(() => ({ dispatch: vi.fn(), + actionType: 'Foreach', + runInstanceId: 'run-1' as string | undefined, nodeMetadata: {} as { runIndex?: number; toolRunIndex?: number }, - failed: { isError: false, isFetching: false, data: undefined as number[] | undefined }, + parentRunIndexes: {} as Record, + failed: { + isError: false, + isFetching: false, + isPreviousData: false, + data: undefined as number[] | undefined, + }, })); vi.mock('react-redux', async (importOriginal) => ({ @@ -17,9 +25,10 @@ vi.mock('react-redux', async (importOriginal) => ({ })); vi.mock('../../../../core', () => ({ useScopeFailedRepetitions: () => state.failed })); vi.mock('../../../../core/state/workflow/workflowSelectors', () => ({ - useRunInstance: () => ({ id: 'run-1' }), - useActionMetadata: () => ({ type: 'Foreach' }), + useRunInstance: () => ({ id: state.runInstanceId }), + useActionMetadata: () => ({ type: state.actionType }), useNodeMetadata: () => state.nodeMetadata, + useParentRunIndexes: () => state.parentRunIndexes, })); const renderPager = (props: Partial[0]> = {}) => @@ -39,8 +48,11 @@ const action = (name: string) => document.querySelector(`[data-pager-action="${n describe('SharedLoopsPager', () => { beforeEach(() => { state.dispatch.mockReset(); + state.actionType = 'Foreach'; + state.runInstanceId = 'run-1'; state.nodeMetadata = { runIndex: 1, toolRunIndex: 0 }; - state.failed = { isError: false, isFetching: false, data: undefined }; + state.parentRunIndexes = {}; + state.failed = { isError: false, isFetching: false, isPreviousData: false, data: undefined }; }); afterEach(cleanup); @@ -67,11 +79,79 @@ describe('SharedLoopsPager', () => { state.failed.data = [2]; renderPager({ useToolRun: true }); expect(screen.getByLabelText('Iteration number, 1 to 3')).toHaveValue('1'); + expect(screen.queryByRole('combobox')).not.toBeInTheDocument(); fireEvent.click(action('next-failed')); expect(state.dispatch).toHaveBeenLastCalledWith(setToolRunIndex({ page: 2, nodeId: 'For each' })); expect(state.dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: setRunIndex.type })); }); + it.each(['Foreach', 'Until'])('jumps directly to a non-nearest failed %s iteration using the scope index', (type) => { + const focusElement = vi.fn(); + state.actionType = type; + state.failed.data = [3, 2, 4]; + renderPager({ focusElement }); + const select = screen.getByRole('combobox', { name: 'Jump to failed iteration' }); + fireEvent.change(select, { target: { value: '4' } }); + expect(state.dispatch).toHaveBeenCalledExactlyOnceWith(setRunIndex({ page: 4, nodeId: 'For each' })); + expect(focusElement).toHaveBeenCalledExactlyOnceWith(4, 'For each'); + }); + + it('compacts Foreach failure actions in the constrained card row only', () => { + state.failed.data = [0, 3, 4]; + const focusElement = vi.fn(); + renderPager({ inLoopCardRow: true, focusElement }); + fireEvent.click(screen.getByRole('button', { name: 'Jump to failed iteration' })); + fireEvent.click(screen.getByRole('menuitem', { name: 'Failed iteration 5' })); + expect(state.dispatch).toHaveBeenCalledExactlyOnceWith(setRunIndex({ page: 4, nodeId: 'For each' })); + expect(focusElement).toHaveBeenCalledExactlyOnceWith(4, 'For each'); + }); + + it('keeps the direct select for Until even if given the constrained row option', () => { + state.actionType = 'Until'; + state.failed.data = [0, 3, 4]; + renderPager({ inLoopCardRow: true }); + expect(screen.getByRole('combobox', { name: 'Jump to failed iteration' })).toBeInTheDocument(); + }); + + it.each(['Agent', 'Scope'])('does not offer a direct picker for %s even with failure data', (type) => { + state.actionType = type; + state.failed.data = [3, 4]; + renderPager(); + expect(screen.queryByRole('combobox')).not.toBeInTheDocument(); + expect(action('next')).toBeInTheDocument(); + }); + + it.each([undefined, [], [1], [-1, 9, 2.5]])('keeps numeric paging when failure candidates %j are not actionable', (data) => { + state.failed.data = data; + renderPager(); + expect(screen.queryByRole('combobox')).not.toBeInTheDocument(); + expect(screen.getByRole('textbox')).toHaveValue('2'); + }); + + it('does not expose a picker or failed jumps from retained data for a previous query identity', () => { + state.failed = { ...state.failed, data: [4], isPreviousData: true }; + renderPager(); + expect(screen.queryByRole('combobox')).not.toBeInTheDocument(); + expect(action('next-failed')).toBeNull(); + }); + + it('hides failed-destination selection while showing legacy failed jumps under repeating parents', () => { + state.parentRunIndexes = { parentA: 1 }; + state.failed.data = [4, 3]; + renderPager({ inLoopCardRow: true }); + expect(screen.queryByRole('combobox', { name: 'Jump to failed iteration' })).toBeNull(); + expect(screen.queryByRole('button', { name: 'Jump to failed iteration' })).toBeNull(); + expect(action('next-failed')).toBeInTheDocument(); + }); + + it('hides failed-destination selection when there is no current run id', () => { + state.runInstanceId = undefined; + state.failed.data = [4, 3]; + renderPager(); + expect(screen.queryByRole('combobox', { name: 'Jump to failed iteration' })).toBeNull(); + expect(action('next-failed')).toBeInTheDocument(); + }); + it.each([ ['collapsed', { collapsed: true }, {}], ['no iterations', { metadata: { runData: {} } }, {}], diff --git a/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/PanelLoopRunData.tsx b/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/PanelLoopRunData.tsx new file mode 100644 index 00000000000..2b3bd928f48 --- /dev/null +++ b/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/PanelLoopRunData.tsx @@ -0,0 +1,37 @@ +import { useLoopRepetitionAdmission } from '../../../core/hooks/useLoopRepetitionAdmission'; +import { useNodeRepetition } from '../../../core/queries/runs'; +import type { LoopRepetition } from '../../../core/state/workflow/workflowInterfaces'; +import { + useIsActionInSelectedTimelineRepetition, + useIsWithinAgenticLoop, + useParentNodeId, + useParentRunIndex, + useRunData, + useSelectedLoopRepetition, +} from '../../../core/state/workflow/workflowSelectors'; + +export function PanelLoopRunData({ nodeId }: { nodeId: string }) { + const repetition = useSelectedLoopRepetition(nodeId); + return repetition && !repetition.isEmpty ? : null; +} + +function PanelRepetitionQuery({ nodeId, repetition }: { nodeId: string; repetition: LoopRepetition }) { + // Pass nodeId (not graphId) so top-level Agent nodes are recognized as agentic loops too. + const isWithinAgenticLoop = useIsWithinAgenticLoop(nodeId); + const isTimelineRepetitionSelected = useIsActionInSelectedTimelineRepetition(nodeId); + const parentId = useParentNodeId(nodeId); + const parentStatus = useRunData(parentId ?? '')?.status; + const parentRunIndex = useParentRunIndex(nodeId); + // Cards can unmount due to viewport culling or graph collapse. The open pane observes the same query independently. + const { data } = useNodeRepetition( + isTimelineRepetitionSelected, + nodeId, + repetition.runId, + repetition.name, + parentStatus, + parentRunIndex, + isWithinAgenticLoop + ); + useLoopRepetitionAdmission(nodeId, !isWithinAgenticLoop && isTimelineRepetitionSelected ? repetition : undefined, data); + return null; +} diff --git a/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/__test__/nodeDetailsPanel.spec.tsx b/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/__test__/nodeDetailsPanel.spec.tsx index 726a38de3c5..0142dfcbf85 100644 --- a/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/__test__/nodeDetailsPanel.spec.tsx +++ b/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/__test__/nodeDetailsPanel.spec.tsx @@ -92,6 +92,7 @@ vi.mock('../../../../core/utils/graph', () => ({ isOperationNameValid: vi.fn(), })); vi.mock('../usePanelNodeData', () => ({ usePanelNodeData: vi.fn() })); +vi.mock('../PanelLoopRunData', () => ({ PanelLoopRunData: () => null })); vi.mock('../useRawInputsOutputs', () => ({ useRawInputsOutputs: vi.fn() })); vi.mock('@microsoft/logic-apps-shared', async (importOriginal) => ({ ...(await importOriginal()), diff --git a/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/__test__/repetitionMonitoring.spec.tsx b/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/__test__/repetitionMonitoring.spec.tsx new file mode 100644 index 00000000000..a908f46e3e9 --- /dev/null +++ b/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/__test__/repetitionMonitoring.spec.tsx @@ -0,0 +1,549 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { act, render, renderHook, waitFor } from '@testing-library/react'; +import { FluentProvider, webLightTheme } from '@fluentui/react-components'; +import { PanelLocation } from '@microsoft/designer-ui'; +import { IntlProvider } from 'react-intl'; +import type { LogicAppsV2 } from '@microsoft/logic-apps-shared'; +import type { ReactNode } from 'react'; +import { Provider } from 'react-redux'; +import { describe, expect, it, vi } from 'vitest'; +import { getMonitoringTabError } from '../../../../common/utilities/error'; +import { initializeInputsOutputsBinding } from '../../../../core/actions/bjsworkflow/monitoring'; +import { initializeGraphState } from '../../../../core/parsers/ParseReduxAction'; +import { Deserialize } from '../../../../core/parsers/BJSWorkflow/BJSDeserializer'; +import { runsQueriesKeys } from '../../../../core/queries/runs'; +import { changePanelNode, collapsePanel, setAlternateSelectedNode } from '../../../../core/state/panel/panelSlice'; +import { useRootWorkflowGraphForLayout, useRunData, useSelectedLoopRepetition } from '../../../../core/state/workflow/workflowSelectors'; +import { + initialWorkflowState, + setRepetitionRunData, + setRunIndex, + toggleCollapsedGraphId, +} from '../../../../core/state/workflow/workflowSlice'; +import { createDesignerStore, designerReducer } from '../../../../core/store'; +import { getNode } from '../../../../core/utils/graph'; +import { NodeRunDataSync } from '../../../CustomNodes/OperationCardNode'; +import { NodeDetailsPanel } from '../nodeDetailsPanel'; +import { useRawInputsOutputs } from '../useRawInputsOutputs'; + +const service = vi.hoisted(() => ({ getActionLinks: vi.fn(), getRepetition: vi.fn() })); +vi.mock('@microsoft/logic-apps-shared', async (importOriginal) => ({ + ...(await importOriginal()), + RunService: () => service, + OperationManifestService: () => ({ isSupported: () => false }), +})); + +const innerActions: LogicAppsV2.WorkflowDefinition['actions'] = { + Condition: { + type: 'If', + expression: '@equals(1,1)', + actions: { Scope: { type: 'Scope', actions: { Inner: { type: 'Compose', inputs: 'inside' } } } }, + else: { actions: { Else_action: { type: 'Compose', inputs: 'outside' } } }, + }, +}; + +const getExecution = (status: 'Failed' | 'Succeeded', uri: string): LogicAppsV2.WorkflowRunAction => ({ + status, + code: status === 'Failed' ? 'ActionFailed' : 'OK', + ...(status === 'Failed' && { error: { code: 'LoopError', message: 'Failure in the first item' } }), + startTime: '2026-01-01T00:00:00Z', + endTime: '2026-01-01T00:00:01Z', + correlation: { actionTrackingId: 'same-id', clientTrackingId: 'client' }, + inputsLink: { uri, contentSize: 10 }, + outputsLink: { contentSize: 0 }, + retryHistory: [], +}); + +function setup(shared: boolean, loop: boolean, nestedLoop = false, workflowKind?: 'agent') { + service.getRepetition.mockReset(); + service.getActionLinks.mockReset().mockImplementation(async (metadata) => ({ + inputs: { item: metadata?.inputsLink?.uri }, + outputs: {}, + })); + const actions = nestedLoop ? { Nested: { type: 'Foreach' as const, foreach: '@createArray(1,2)', actions: innerActions } } : innerActions; + const definition = { + ...initialWorkflowState.originalDefinition, + actions: loop ? { Loop: { type: 'Foreach' as const, foreach: '@createArray(1,2)', actions } } : innerActions, + }; + const parsed = Deserialize(definition, null); + const state = designerReducer(undefined, { type: '@@init' }); + const oldExecution = getExecution('Failed', 'first-item'); + const store = createDesignerStore({ + ...state, + designerOptions: { ...state.designerOptions, isMonitoringView: true, useSharedNodeUi: shared }, + workflow: { + ...initialWorkflowState, + workflowKind, + graph: parsed.graph, + operations: parsed.actionData, + nodesMetadata: { + ...parsed.nodesMetadata, + ...(!loop && { Inner: { ...parsed.nodesMetadata.Inner, runData: oldExecution } }), + }, + runInstance: { id: 'run' } as LogicAppsV2.RunInstanceDefinition, + }, + }); + // Match the designer's fresh-cache behavior when an observer changes query keys. + const client = new QueryClient({ + defaultOptions: { queries: { retry: false, cacheTime: 60_000, staleTime: 60_000, refetchOnMount: false } }, + }); + const wrapper = ({ children }: { children: ReactNode }) => ( + + {children} + + ); + return { store, wrapper, oldExecution, definition, client }; +} + +const useDetails = () => { + const metadata = useRunData('Inner'); + const { data } = useRawInputsOutputs('Inner'); + return { + error: getMonitoringTabError(metadata?.error, metadata?.status, metadata?.code), + rawLink: metadata?.inputsLink?.uri, + input: data?.inputs.item, + }; +}; + +const ignoreFetching = () => undefined; +const DetailsPanel = () => ( + + + + + +); +const RepetitionCard = () => ( + +); + +const withRepetitionCard = + (wrapper: ({ children }: { children: ReactNode }) => JSX.Element) => + ({ children }: { children: ReactNode }) => + wrapper({ + children: ( + <> + + {children} + + ), + }); + +const VisibleRepetitionCard = () => { + const graph = useRootWorkflowGraphForLayout(); + return graph && getNode('Inner', graph) ? : null; +}; + +describe('Monitoring details for nested actions', () => { + it('re-admits stable cached data after same-run graph initialization and still accepts a fresh response for that key', async () => { + const { store, wrapper, oldExecution, definition, client } = setup(true, true); + service.getRepetition.mockResolvedValue({ properties: oldExecution }); + const view = renderHook(() => useRawInputsOutputs('Inner'), { wrapper: withRepetitionCard(wrapper) }); + await waitFor(() => expect(view.result.current.data?.inputs.item).toBe('first-item')); + const revision = view.result.current.data?.loopPayloadRevision; + + act(() => + store.dispatch( + initializeGraphState.fulfilled( + { deserializedWorkflow: Deserialize(definition, null), originalDefinition: definition }, + 'same-run', + { workflowDefinition: { kind: 'Stateful', definition, connectionReferences: {}, parameters: {} }, runInstance: null } + ) + ) + ); + await waitFor(() => expect(view.result.current.data?.inputs.item).toBe('first-item')); + expect(view.result.current.data?.loopPayloadRevision).toBe(revision); + expect(service.getRepetition).toHaveBeenCalledTimes(1); + expect(service.getActionLinks).toHaveBeenCalledTimes(1); + + act(() => client.setQueriesData([runsQueriesKeys.useNodeRepetition], { properties: getExecution('Succeeded', 'refreshed-item') })); + await waitFor(() => expect(view.result.current.data?.inputs.item).toBe('refreshed-item')); + expect(view.result.current.data?.loopPayloadRevision).not.toBe(revision); + expect(service.getActionLinks).toHaveBeenCalledTimes(2); + }); + + it('reuses raw payload and its revision when returning to an unchanged cached iteration', async () => { + const { store, wrapper, oldExecution, client } = setup(true, true); + service.getRepetition + .mockResolvedValueOnce({ properties: oldExecution }) + .mockResolvedValueOnce({ properties: getExecution('Succeeded', 'second-item') }); + const { result } = renderHook(() => useRawInputsOutputs('Inner'), { + wrapper: withRepetitionCard(wrapper), + }); + + await waitFor(() => expect(result.current.data?.inputs.item).toBe('first-item')); + const firstRevision = result.current.data?.loopPayloadRevision; + act(() => store.dispatch(setRunIndex({ nodeId: 'Loop', page: 1 }))); + await waitFor(() => expect(result.current.data?.inputs.item).toBe('second-item')); + expect(result.current.data?.loopPayloadRevision).not.toBe(firstRevision); + + act(() => store.dispatch(setRunIndex({ nodeId: 'Loop', page: 0 }))); + await waitFor(() => expect(result.current.data?.inputs.item).toBe('first-item')); + expect(result.current.data?.loopPayloadRevision).toBe(firstRevision); + expect(service.getRepetition).toHaveBeenCalledTimes(2); + expect(service.getActionLinks).toHaveBeenCalledTimes(2); + expect( + client + .getQueryCache() + .findAll(['actionInputsOutputs']) + .filter(({ state }) => !!state.data) + ).toHaveLength(2); + }); + + it('loads a pinned descendant after its Scope collapses and reuses the query when its card remounts', async () => { + const { store, wrapper, oldExecution } = setup(true, true); + let resolveNext!: (value: { properties: LogicAppsV2.WorkflowRunAction }) => void; + service.getRepetition.mockResolvedValueOnce({ properties: oldExecution }).mockImplementationOnce( + () => + new Promise((resolve) => { + resolveNext = resolve; + }) + ); + store.dispatch(setAlternateSelectedNode({ nodeId: 'Inner', updatePanelOpenState: true })); + const view = renderHook(useDetails, { + wrapper: ({ children }) => + wrapper({ + children: ( + <> + + + {children} + + ), + }), + }); + await waitFor(() => expect(view.result.current.input).toBe('first-item')); + expect(service.getRepetition).toHaveBeenCalledTimes(1); + + act(() => store.dispatch(toggleCollapsedGraphId({ id: 'Scope' }))); + expect(view.result.current.input).toBe('first-item'); + expect(service.getRepetition).toHaveBeenCalledTimes(1); + act(() => { + store.dispatch(setRunIndex({ nodeId: 'Loop', page: 1 })); + }); + expect(view.result.current).toEqual({ error: undefined, rawLink: undefined, input: undefined }); + expect(store.getState().panel.operationContent.alternateSelectedNode).toMatchObject({ nodeId: 'Inner', persistence: 'pinned' }); + await waitFor(() => expect(service.getRepetition).toHaveBeenLastCalledWith({ nodeId: 'Inner', runId: 'run' }, '000001')); + await act(async () => resolveNext({ properties: getExecution('Succeeded', 'second-item') })); + await waitFor(() => expect(view.result.current.input).toBe('second-item')); + + act(() => store.dispatch(toggleCollapsedGraphId({ id: 'Scope' }))); + expect(view.result.current.input).toBe('second-item'); + expect(service.getRepetition).toHaveBeenCalledTimes(2); + expect(service.getActionLinks).toHaveBeenCalledTimes(2); + }); + + it('observes both distinct rendered panes and reuses the same query when their selections converge', async () => { + const { store, wrapper, client, oldExecution } = setup(true, true); + service.getRepetition.mockResolvedValue({ properties: oldExecution }); + store.dispatch(changePanelNode('Inner')); + store.dispatch(setAlternateSelectedNode({ nodeId: 'Else_action', panelPersistence: 'selected', updatePanelOpenState: true })); + const { container } = render(, { wrapper }); + expect(container.querySelectorAll('.msla-panel-layout')).toHaveLength(2); + await waitFor(() => expect(service.getRepetition.mock.calls.map(([action]) => action.nodeId).sort()).toEqual(['Else_action', 'Inner'])); + act(() => store.dispatch(setAlternateSelectedNode({ nodeId: 'Inner', panelPersistence: 'selected', updatePanelOpenState: true }))); + expect(container.querySelectorAll('.msla-panel-layout')).toHaveLength(1); + const query = client.getQueryCache().find([runsQueriesKeys.useNodeRepetition, { nodeId: 'Inner' }], { exact: false }); + expect(query?.getObserversCount()).toBe(1); + expect(service.getRepetition).toHaveBeenCalledTimes(2); + }); + + it.each([ + ['flag off', false, undefined], + ['Agent workflow', true, 'agent'], + ] as const)('does not observe the ordinary loop query from a rendered pane with %s', (_label, shared, workflowKind) => { + const { store, wrapper, client } = setup(shared, true, false, workflowKind); + store.dispatch(changePanelNode('Inner')); + const { container } = render(, { wrapper }); + expect(container.querySelector('.msla-panel-layout')).toBeInTheDocument(); + expect(client.getQueryCache().findAll([runsQueriesKeys.useNodeRepetition])).toHaveLength(0); + expect(service.getRepetition).not.toHaveBeenCalled(); + }); + + it.each(['primary', 'alternate'] as const)( + 'loads the open %s pane when the node is in the graph but its card is not mounted', + async (pane) => { + const { store, wrapper: Wrapper, oldExecution } = setup(true, true); + service.getRepetition.mockResolvedValue({ properties: oldExecution }); + store.dispatch( + pane === 'primary' + ? changePanelNode('Inner') + : setAlternateSelectedNode({ nodeId: 'Inner', panelPersistence: 'selected', updatePanelOpenState: true }) + ); + expect(getNode('Inner', store.getState().workflow.graph!)).toBeDefined(); + const { container } = render(, { wrapper: Wrapper }); + expect(container.querySelector('.msla-panel-layout')).toBeInTheDocument(); + await waitFor(() => expect(store.getState().workflow.nodesMetadata.Inner.runData?.inputsLink?.uri).toBe('first-item')); + expect(service.getRepetition).toHaveBeenCalledTimes(1); + act(() => store.dispatch(collapsePanel())); + expect(container.querySelector('.msla-panel-layout')).not.toBeInTheDocument(); + act(() => store.dispatch(setRunIndex({ nodeId: 'Loop', page: 1 }))); + expect(service.getRepetition).toHaveBeenCalledTimes(1); + } + ); + + it('keeps bound inputs on a same-link status refresh without issuing a new payload request', async () => { + const { store, wrapper, oldExecution, client } = setup(true, true); + const repetition = { runId: 'run', name: '000000' }; + const bound = { item: { displayName: 'Item', value: 'first-item' } }; + const boundOutputs = { result: { displayName: 'Result', value: 'first-output' } }; + service.getRepetition.mockResolvedValue({ properties: oldExecution }); + const { result } = renderHook(() => useRawInputsOutputs('Inner'), { wrapper: withRepetitionCard(wrapper) }); + await waitFor(() => expect(result.current.data?.inputs.item).toBe('first-item')); + const revision = result.current.data?.loopPayloadRevision; + const applyBound = () => + initializeInputsOutputsBinding.fulfilled({ nodeId: 'Inner', inputs: bound, outputs: boundOutputs }, 'binding', { + nodeId: 'Inner', + inputsOutputs: { nodeId: 'Inner', inputs: bound, outputs: boundOutputs }, + loopRepetition: repetition, + loopPayloadRevision: result.current.data?.loopPayloadRevision, + }); + act(() => store.dispatch(applyBound())); + expect(store.getState().workflow.nodesMetadata.Inner.runData?.inputs).toEqual(bound); + act(() => + client.setQueriesData([runsQueriesKeys.useNodeRepetition], { properties: { ...oldExecution, status: 'Succeeded', code: 'OK' } }) + ); + await waitFor(() => + expect(store.getState().workflow.nodesMetadata.Inner.runData).toMatchObject({ + status: 'Succeeded', + inputs: bound, + outputs: boundOutputs, + }) + ); + expect(result.current.data?.loopPayloadRevision).toBe(revision); + expect(result.current.data?.inputs.item).toBe('first-item'); + expect(service.getActionLinks).toHaveBeenCalledTimes(1); + }); + + it('isolates changed links, same-URI security metadata, removals, and late bindings within one repetition', async () => { + const { store, wrapper, oldExecution, client } = setup(true, true); + const repetition = { runId: 'run', name: '000000' }; + const refresh = (runData: LogicAppsV2.WorkflowRunAction) => + client.setQueriesData([runsQueriesKeys.useNodeRepetition], { properties: runData }); + let resolveChanged!: (value: { inputs: { item: string } }) => void; + service.getActionLinks + .mockResolvedValueOnce({ inputs: { item: 'first-item' } }) + .mockImplementationOnce( + () => + new Promise((resolve) => { + resolveChanged = resolve; + }) + ) + .mockResolvedValueOnce({ inputs: { item: '[redacted]' } }) + .mockResolvedValueOnce({ inputs: {} }); + service.getRepetition.mockResolvedValue({ properties: oldExecution }); + const { result } = renderHook(() => useRawInputsOutputs('Inner'), { wrapper: withRepetitionCard(wrapper) }); + await waitFor(() => expect(result.current.data?.inputs.item).toBe('first-item')); + const lateInputs = { item: { displayName: 'Item', value: 'first-item' } }; + const lateBinding = initializeInputsOutputsBinding.fulfilled({ nodeId: 'Inner', inputs: lateInputs, outputs: {} }, 'old-payload', { + nodeId: 'Inner', + inputsOutputs: { nodeId: 'Inner', inputs: lateInputs, outputs: {} }, + loopRepetition: repetition, + loopPayloadRevision: result.current.data?.loopPayloadRevision, + }); + const newLink = { ...oldExecution.inputsLink!, uri: 'https://example.invalid/inputs?sig=test-only' }; + act(() => refresh({ ...oldExecution, inputsLink: newLink })); + await waitFor(() => expect(result.current.data?.inputs.item).toBeUndefined()); + await waitFor(() => expect(service.getActionLinks).toHaveBeenCalledTimes(2)); + act(() => refresh({ ...oldExecution, inputsLink: { ...newLink, secureData: { properties: ['item'] } } })); + await waitFor(() => expect(result.current.data?.inputs.item).toBe('[redacted]')); + await act(async () => { + resolveChanged({ inputs: { item: 'late result' } }); + store.dispatch(lateBinding); + }); + expect(result.current.data?.inputs.item).toBe('[redacted]'); + expect(store.getState().workflow.nodesMetadata.Inner.runData?.inputs).toBeUndefined(); + const redactedInputs = { item: { displayName: 'Item', value: '[redacted]' } }; + act(() => + store.dispatch( + initializeInputsOutputsBinding.fulfilled({ nodeId: 'Inner', inputs: redactedInputs, outputs: {} }, 'redacted-payload', { + nodeId: 'Inner', + inputsOutputs: { nodeId: 'Inner', inputs: redactedInputs, outputs: {} }, + loopRepetition: repetition, + loopPayloadRevision: result.current.data?.loopPayloadRevision, + }) + ) + ); + expect(store.getState().workflow.nodesMetadata.Inner.runData?.inputs).toEqual(redactedInputs); + act(() => refresh({ ...oldExecution, inputsLink: undefined })); + await waitFor(() => expect(service.getActionLinks).toHaveBeenCalledTimes(4)); + expect(result.current.data?.inputs.item).toBeUndefined(); + expect(store.getState().workflow.nodesMetadata.Inner.runData?.inputs).toBeUndefined(); + expect( + JSON.stringify( + client + .getQueryCache() + .getAll() + .map(({ queryKey }) => queryKey) + ) + ).not.toContain('sig=test-only'); + }); + + it('does not expose the previous loop error, link, or content while the selected repetition loads', async () => { + const { store, wrapper, oldExecution } = setup(true, true); + const first = { runId: 'run', name: '000000' }; + const second = { runId: 'run', name: '000001' }; + const firstResult = setRepetitionRunData({ + nodeId: 'Inner', + runData: oldExecution, + loopRepetition: first, + loopPayloadRevision: 'first', + }); + store.dispatch(firstResult); + const { result } = renderHook(useDetails, { wrapper }); + await waitFor(() => expect(result.current.input).toBe('first-item')); + expect(result.current.error).toMatchObject({ message: 'Failure in the first item' }); + + act(() => store.dispatch(setRunIndex({ nodeId: 'Loop', page: 1 }))); + expect(result.current).toEqual({ error: undefined, rawLink: undefined, input: undefined }); + expect(service.getActionLinks).toHaveBeenCalledTimes(1); + + act(() => store.dispatch(firstResult)); + expect(result.current).toEqual({ error: undefined, rawLink: undefined, input: undefined }); + + act(() => + store.dispatch( + setRepetitionRunData({ + nodeId: 'Inner', + runData: getExecution('Succeeded', 'second-item'), + loopRepetition: second, + loopPayloadRevision: 'second', + }) + ) + ); + await waitFor(() => expect(result.current.input).toBe('second-item')); + expect(result.current).toEqual({ error: undefined, rawLink: 'second-item', input: 'second-item' }); + + const lateInputs = { item: { displayName: 'Item', value: 'first-item' } }; + act(() => + store.dispatch( + initializeInputsOutputsBinding.fulfilled({ nodeId: 'Inner', inputs: lateInputs, outputs: {} }, 'late', { + nodeId: 'Inner', + inputsOutputs: { nodeId: 'Inner', inputs: lateInputs, outputs: {} }, + loopRepetition: first, + loopPayloadRevision: 'first', + }) + ) + ); + expect(store.getState().workflow.nodesMetadata.Inner.runData?.inputs).toBeUndefined(); + }); + + it('leaves the existing flag-off selection behavior unchanged', async () => { + const { store, wrapper, oldExecution } = setup(false, true); + store.dispatch(setRepetitionRunData({ nodeId: 'Inner', runData: oldExecution })); + const { result } = renderHook(useDetails, { wrapper }); + await waitFor(() => expect(result.current.input).toBe('first-item')); + act(() => store.dispatch(setRunIndex({ nodeId: 'Loop', page: 1 }))); + expect(result.current).toMatchObject({ rawLink: 'first-item', input: 'first-item' }); + }); + + it('keeps a late input payload out of the selected nested iteration after its input request fails', async () => { + const { store, wrapper, oldExecution } = setup(true, true, true); + let resolveOldInputs!: (data: { inputs: { item: string } }) => void; + service.getActionLinks + .mockImplementationOnce(() => new Promise((resolve) => (resolveOldInputs = resolve))) + .mockRejectedValueOnce(new Error('Input link unavailable')); + + store.dispatch(setRunIndex({ nodeId: 'Nested', page: 1 })); + store.dispatch( + setRepetitionRunData({ + nodeId: 'Inner', + runData: oldExecution, + loopRepetition: { runId: 'run', name: '000000-000001' }, + loopPayloadRevision: 'first', + }) + ); + const { result } = renderHook(() => useRawInputsOutputs('Inner'), { wrapper }); + await waitFor(() => expect(service.getActionLinks).toHaveBeenCalledTimes(1)); + + act(() => { + store.dispatch(setRunIndex({ nodeId: 'Loop', page: 1 })); + store.dispatch( + setRepetitionRunData({ + nodeId: 'Inner', + runData: getExecution('Succeeded', 'second-item'), + loopRepetition: { runId: 'run', name: '000001-000000' }, + loopPayloadRevision: 'second', + }) + ); + }); + await waitFor(() => expect(result.current.isError).toBe(true)); + expect(service.getActionLinks).toHaveBeenLastCalledWith( + expect.objectContaining({ inputsLink: { uri: 'second-item', contentSize: 10 } }), + 'Inner' + ); + await act(async () => resolveOldInputs({ inputs: { item: 'first-item' } })); + expect(result.current.isError).toBe(true); + expect(result.current.data?.inputs.item).toBeUndefined(); + }); + + it('resets nested loop index on outer page change and suppresses child data when an inner loop has zero iterations', () => { + const { store, oldExecution } = setup(true, true, true); + store.dispatch(setRunIndex({ nodeId: 'Nested', page: 3 })); + store.dispatch( + setRepetitionRunData({ + nodeId: 'Inner', + runData: oldExecution, + loopRepetition: { runId: 'run', name: '000000-000003' }, + loopPayloadRevision: 'first', + }) + ); + expect(store.getState().workflow.nodesMetadata.Nested.runIndex).toBe(3); + + // Moving the outer loop resets descendant loop indices synchronously. + store.dispatch(setRunIndex({ nodeId: 'Loop', page: 1 })); + expect(store.getState().workflow.nodesMetadata.Nested.runIndex).toBe(0); + + // Admitting an inner loop repetition with zero iterations marks descendants empty and hides stale runData. + store.dispatch( + setRepetitionRunData({ + nodeId: 'Nested', + runData: { + status: 'Succeeded', + inputsLink: { uri: 'nested-empty', contentSize: 10, metadata: { foreachItemsCount: 0 } }, + } as any, + loopRepetition: { runId: 'run', name: '000001' }, + loopPayloadRevision: 'nested-empty', + }) + ); + const { result } = renderHook( + () => ({ + repetition: useSelectedLoopRepetition('Inner'), + runData: useRunData('Inner'), + }), + { wrapper: ({ children }: { children: ReactNode }) => {children} } + ); + expect(result.current.repetition).toEqual({ runId: 'run', name: '', isEmpty: true }); + expect(result.current.runData).toBeUndefined(); + }); + + it('preserves inline repetition outputs when getActionLinks returns {} for unlinked sides', async () => { + const { store, wrapper } = setup(true, true); + service.getActionLinks.mockResolvedValue({ inputs: { fromLink: 'yes' }, outputs: {} }); + + store.dispatch( + setRepetitionRunData({ + nodeId: 'Inner', + runData: { + status: 'Succeeded', + inputsLink: { uri: 'linked-inputs', contentSize: 10 }, + outputs: { inlineValue: 42 }, + } as any, + loopRepetition: { runId: 'run', name: '000000' }, + loopPayloadRevision: 'mixed', + }) + ); + + const { result } = renderHook(() => useRawInputsOutputs('Inner'), { wrapper }); + await waitFor(() => expect(result.current.data?.inputs).toEqual({ fromLink: 'yes' })); + expect(result.current.data?.outputs).toEqual({ inlineValue: 42 }); + }); + + it('uses the action ID to load error and raw content from an If/Scope outside loops', async () => { + const { wrapper } = setup(true, false); + const { result } = renderHook(useDetails, { wrapper }); + await waitFor(() => expect(result.current.input).toBe('first-item')); + expect(result.current.error).toMatchObject({ message: 'Failure in the first item' }); + expect(service.getActionLinks).toHaveBeenCalledWith(expect.objectContaining({ status: 'Failed' }), 'Inner'); + }); +}); diff --git a/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/__test__/usePanelNodeData.spec.ts b/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/__test__/usePanelNodeData.spec.tsx similarity index 61% rename from libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/__test__/usePanelNodeData.spec.ts rename to libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/__test__/usePanelNodeData.spec.tsx index a5d86d880a8..52bfefb3188 100644 --- a/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/__test__/usePanelNodeData.spec.ts +++ b/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/__test__/usePanelNodeData.spec.tsx @@ -19,6 +19,9 @@ vi.mock('../../../../core/state/operation/operationSelector', () => ({ useIconUri: vi.fn(), useOperationErrorInfo: vi.fn(), })); +vi.mock('../../../../core/state/designerOptions/designerOptionsSelectors', () => ({ + useSharedNodeUi: vi.fn(), +})); vi.mock('../../../../core/state/panel/panelSlice', () => ({ setPinnedPanelActiveTab: vi.fn((tabId: string) => ({ type: 'setPinnedPanelActiveTab', payload: tabId })), @@ -32,10 +35,12 @@ vi.mock('../../../../core/state/panel/panelSelectors', () => ({ })); vi.mock('../../../../core/state/selectors/actionMetadataSelector', () => ({ + useOperationInfo: vi.fn(), useOperationQuery: vi.fn(), })); vi.mock('../../../../core/state/workflow/workflowSelectors', () => ({ + useActionMetadata: vi.fn(), useNodeDescription: vi.fn(), useRunData: vi.fn(), })); @@ -47,11 +52,13 @@ vi.mock('../usePanelTabs', () => ({ import { usePanelNodeData } from '../usePanelNodeData'; import { useNodeDisplayName, useNodeMetadata } from '../../../../core'; import { useIconUri, useOperationErrorInfo } from '../../../../core/state/operation/operationSelector'; +import { useSharedNodeUi } from '../../../../core/state/designerOptions/designerOptionsSelectors'; import { useIsNodePinnedToOperationPanel } from '../../../../core/state/panel/panelSelectors'; -import { useOperationQuery } from '../../../../core/state/selectors/actionMetadataSelector'; -import { useRunData } from '../../../../core/state/workflow/workflowSelectors'; +import { useOperationInfo, useOperationQuery } from '../../../../core/state/selectors/actionMetadataSelector'; +import { useActionMetadata, useRunData } from '../../../../core/state/workflow/workflowSelectors'; import { usePanelTabs } from '../usePanelTabs'; -import { renderHook } from '@testing-library/react'; +import { renderHook, render } from '@testing-library/react'; +import { FluentProvider, webLightTheme } from '@fluentui/react-components'; describe('usePanelNodeData', () => { beforeEach(() => { @@ -60,8 +67,11 @@ describe('usePanelNodeData', () => { (useNodeMetadata as any).mockReturnValue({ subgraphType: undefined }); (useIconUri as any).mockReturnValue('https://example.com/icon.png'); (useOperationErrorInfo as any).mockReturnValue(undefined); + (useSharedNodeUi as any).mockReturnValue(false); (useIsNodePinnedToOperationPanel as any).mockReturnValue(false); - (useOperationQuery as any).mockReturnValue({ isLoading: false, isError: false, data: {} }); + vi.mocked(useOperationInfo, { partial: true }).mockReturnValue({ type: '' }); + vi.mocked(useOperationQuery, { partial: true }).mockReturnValue({ isLoading: false, isError: false }); + (useActionMetadata as any).mockReturnValue({ type: 'Http', kind: undefined }); (useRunData as any).mockReturnValue(undefined); (usePanelTabs as any).mockReturnValue([]); }); @@ -135,4 +145,47 @@ describe('usePanelNodeData', () => { const { result } = renderHook(() => usePanelNodeData('test-node')); expect(result.current?.runData).toEqual(mockRunData); }); + + it('prefers the resolved type and kind over the definition for a run node', () => { + vi.mocked(useSharedNodeUi).mockReturnValue(true); + vi.mocked(useOperationInfo, { partial: true }).mockReturnValue({ type: 'Expression', kind: 'CurrentTime' }); + vi.mocked(useActionMetadata, { partial: true }).mockReturnValue({ type: 'Compose' }); + (useRunData as any).mockReturnValue({ status: 'Succeeded' }); + + const { result } = renderHook(() => usePanelNodeData('run-node')); + const { container } = render({result.current?.operationIcon}); + expect(container.querySelector('[data-tone="blue"] [data-icon-name="CalendarClockRegular"]')).toBeInTheDocument(); + }); + + it('should keep the existing header icon path when shared-node UI is disabled', () => { + (useSharedNodeUi as any).mockReturnValue(false); + (useActionMetadata as any).mockReturnValue({ type: 'Compose', kind: undefined }); + + const { result } = renderHook(() => usePanelNodeData('compose-node')); + expect(result.current?.operationIcon).toBeUndefined(); + }); + + it('keeps legacy artwork while loading or errored and clears the glyph on connector selection', () => { + vi.mocked(useSharedNodeUi).mockReturnValue(true); + vi.mocked(useActionMetadata, { partial: true }).mockImplementation((id) => + id === 'compose-node' ? { type: 'Compose' } : { type: 'ApiConnection' } + ); + const query = vi.mocked(useOperationQuery, { partial: true }); + query.mockReturnValue({ isLoading: true, isError: false }); + + const { result, rerender } = renderHook(({ id }) => usePanelNodeData(id), { initialProps: { id: 'compose-node' } }); + expect(result.current).toMatchObject({ isLoading: true, operationIcon: undefined }); + + query.mockReturnValue({ isLoading: false, isError: true }); + rerender({ id: 'compose-node' }); + expect(result.current).toMatchObject({ isError: true, isLoading: false, operationIcon: undefined }); + + query.mockReturnValue({ isLoading: false, isError: false }); + rerender({ id: 'compose-node' }); + const { container } = render({result.current?.operationIcon}); + expect(container.querySelector('[data-tone="violet"] [data-icon-name="BracesRegular"]')).toBeInTheDocument(); + + rerender({ id: 'connector-node' }); + expect(result.current).toMatchObject({ iconUri: 'https://example.com/icon.png', operationIcon: undefined }); + }); }); diff --git a/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/nodeDetailsPanel.tsx b/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/nodeDetailsPanel.tsx index 19ec78ee7d7..f119ec24504 100644 --- a/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/nodeDetailsPanel.tsx +++ b/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/nodeDetailsPanel.tsx @@ -21,6 +21,7 @@ import { PinMenuItem } from '../../menuItems/pinMenuItem'; import { getChildRunNameFromOutputs, getChildWorkflowIdFromInputs } from './childWorkflowHelpers'; import { useRawInputsOutputs } from './useRawInputsOutputs'; import { usePanelNodeData } from './usePanelNodeData'; +import { PanelLoopRunData } from './PanelLoopRunData'; import type { CommonPanelProps, PageActionTelemetryData } from '@microsoft/designer-ui'; import { PanelContainer, PanelScope } from '@microsoft/designer-ui'; import { equals, getRecordEntry, HostService, isNullOrUndefined, SUBGRAPH_TYPES, WorkflowService } from '@microsoft/logic-apps-shared'; @@ -225,6 +226,7 @@ export const NodeDetailsPanel = (props: CommonPanelProps): JSX.Element => { nodeHeaderItems={getHeaderMenuItems(selectedNode)} alternateSelectedNode={alternateSelectedNodeData} alternateSelectedNodePersistence={alternateSelectedNodePersistence} + renderNodeObserver={(nodeId) => } alternateSelectedNodeHeaderItems={getHeaderMenuItems(alternateSelectedNodeId)} readOnlyMode={readOnly} canResubmit={(runData?.canResubmit ?? false) && runMode !== 'Draft'} diff --git a/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/tabs/monitoringTab/__test__/monitoringTab.spec.tsx b/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/tabs/monitoringTab/__test__/monitoringTab.spec.tsx index b5c4cdef3d9..2c835f38a7d 100644 --- a/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/tabs/monitoringTab/__test__/monitoringTab.spec.tsx +++ b/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/tabs/monitoringTab/__test__/monitoringTab.spec.tsx @@ -19,6 +19,12 @@ vi.mock('../../../../../../core/state/operation/operationSelector', () => ({ vi.mock('../../../../../../core/state/workflow/workflowSelectors', () => ({ useRunData: vi.fn(), + useNodeMetadata: () => undefined, + useSelectedLoopRepetition: () => undefined, +})); + +vi.mock('../../../../../../core/state/designerOptions/designerOptionsSelectors', () => ({ + useSharedNodeUi: vi.fn(() => false), })); const mockGetActionLinks = vi.fn(); @@ -68,11 +74,12 @@ vi.mock('../propertiesPanel', () => ({ import { MonitoringPanel } from '../monitoringTab'; import { useRunData } from '../../../../../../core/state/workflow/workflowSelectors'; -import { useQuery } from '@tanstack/react-query'; +import { useSharedNodeUi } from '../../../../../../core/state/designerOptions/designerOptionsSelectors'; describe('MonitoringPanel', () => { beforeEach(() => { vi.clearAllMocks(); + vi.mocked(useSharedNodeUi).mockReturnValue(false); (useRunData as any).mockReturnValue({ status: 'Succeeded', startTime: '2024-01-01T00:00:00Z', @@ -80,7 +87,8 @@ describe('MonitoringPanel', () => { }); }); - it('should render null when runMetaData is null', () => { + it.each([false, true])('renders nothing without run metadata (shared layout: %s)', (showComparison) => { + vi.mocked(useSharedNodeUi).mockReturnValue(showComparison); (useRunData as any).mockReturnValue(null); const { container } = render(); @@ -96,6 +104,32 @@ describe('MonitoringPanel', () => { expect(screen.getByTestId('properties-panel')).toBeDefined(); }); + it('keeps legacy composition when shared node UI is disabled', () => { + const { container } = render(); + + expect(Array.from(container.children)).toEqual([ + screen.getByTestId('error-section'), + screen.getByTestId('inputs-panel'), + screen.getByTestId('outputs-panel'), + screen.getByTestId('properties-panel'), + ]); + }); + + it('uses shared comparison layout only when shared node UI is enabled', () => { + vi.mocked(useSharedNodeUi).mockReturnValue(true); + const { container } = render(); + + const layout = container.querySelector('[data-monitoring-payload-comparison]'); + const grid = container.querySelector('[data-monitoring-payload-grid]'); + + expect(Array.from(container.children)).toEqual([screen.getByTestId('error-section'), layout]); + expect(Array.from(layout?.children ?? [])).toEqual([grid, screen.getByTestId('properties-panel')]); + expect(Array.from(grid?.children ?? [], (pane) => pane.firstElementChild)).toEqual([ + screen.getByTestId('inputs-panel'), + screen.getByTestId('outputs-panel'), + ]); + }); + it('should use cached data for built-in tools with existing inputs/outputs', () => { const cachedInputs = { code: { displayName: 'Code', value: 'print("hi")' } }; const cachedOutputs = { result: { displayName: 'Result', value: 'hi' } }; diff --git a/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/tabs/monitoringTab/monitoringTab.tsx b/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/tabs/monitoringTab/monitoringTab.tsx index 936b5054ea1..2b77d842ef4 100644 --- a/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/tabs/monitoringTab/monitoringTab.tsx +++ b/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/tabs/monitoringTab/monitoringTab.tsx @@ -1,7 +1,7 @@ import constants from '../../../../../common/constants'; import { getMonitoringTabError } from '../../../../../common/utilities/error'; import { useBrandColor } from '../../../../../core/state/operation/operationSelector'; -import { useRunData } from '../../../../../core/state/workflow/workflowSelectors'; +import { useRunData, useSelectedLoopRepetition } from '../../../../../core/state/workflow/workflowSelectors'; import { useRawInputsOutputs } from '../../useRawInputsOutputs'; import { InputsPanel } from './inputsPanel'; import { OutputsPanel } from './outputsPanel'; @@ -13,45 +13,116 @@ import { useEffect } from 'react'; import { useDispatch } from 'react-redux'; import type { AppDispatch } from '../../../../../core'; import { initializeInputsOutputsBinding } from '../../../../../core/actions/bjsworkflow/monitoring'; +import { useSharedNodeUi } from '../../../../../core/state/designerOptions/designerOptionsSelectors'; +import { makeStyles, tokens } from '@fluentui/react-components'; +import { MonitoringPayloadComparison } from '@microsoft/designer-ui-v2'; + +const useStyles = makeStyles({ + comparisonLayout: { + marginBlockStart: tokens.spacingVerticalL, + // The comparison grid owns section spacing instead of the old vertical margins. + '& .msla-trace-inputs-outputs': { + marginBlock: 0, + }, + // Allow long translated expand/raw labels to wrap without clipping their controls. + '& .msla-trace-inputs-outputs-header': { + flexWrap: 'wrap', + }, + '& .msla-trace-inputs-outputs-header > button': { + minInlineSize: 0, + maxInlineSize: '100%', + height: 'auto', + whiteSpace: 'normal', + overflowWrap: 'anywhere', + }, + '& .msla-trace-inputs-outputs-header > button .fui-Button__icon': { + flexShrink: 0, + }, + '& .msla-trace-inputs-outputs-header-text': { + minInlineSize: 0, + overflowWrap: 'anywhere', + }, + '& .msla-trace-download-link > a': { + whiteSpace: 'normal', + overflowWrap: 'anywhere', + }, + }, +}); export const MonitoringPanel: React.FC = (props) => { const { nodeId: selectedNodeId } = props; const brandColor = useBrandColor(selectedNodeId); const runMetaData = useRunData(selectedNodeId); + const loopRepetition = useSelectedLoopRepetition(selectedNodeId); const dispatch = useDispatch(); const { status: statusRun, error: errorRun, code: codeRun } = runMetaData ?? {}; const error = getMonitoringTabError(errorRun, statusRun, codeRun); - const { data: inputOutputs, isError, isFetching, isLoading } = useRawInputsOutputs(selectedNodeId); + const { data: inputOutputs, isError, isFetching, isLoading, isPlaceholderData } = useRawInputsOutputs(selectedNodeId); const actionTrackingId = runMetaData?.correlation?.actionTrackingId; const startTime = runMetaData?.startTime; const endTime = runMetaData?.endTime; + const hasCurrentInputsOutputs = !loopRepetition || (!!runMetaData && !isPlaceholderData && !!inputOutputs?.loopPayloadRevision); useEffect(() => { - if (!isLoading && inputOutputs) { - dispatch(initializeInputsOutputsBinding({ nodeId: selectedNodeId, inputsOutputs: inputOutputs as any })); + if (!isLoading && inputOutputs && hasCurrentInputsOutputs) { + dispatch( + initializeInputsOutputsBinding({ + nodeId: selectedNodeId, + inputsOutputs: inputOutputs as any, + ...(loopRepetition && { loopRepetition, loopPayloadRevision: inputOutputs.loopPayloadRevision }), + }) + ); } - }, [dispatch, inputOutputs, selectedNodeId, isLoading, actionTrackingId, startTime, endTime]); + }, [dispatch, inputOutputs, selectedNodeId, isLoading, actionTrackingId, startTime, endTime, loopRepetition, hasCurrentInputsOutputs]); + + const showPayloadComparison = useSharedNodeUi(); + const styles = useStyles(); + + if (isNullOrUndefined(runMetaData)) { + return null; + } + + const inputsSection = ( + + ); + + const outputsSection = ( + + ); + + const propertiesSection = ; - return isNullOrUndefined(runMetaData) ? null : ( + return ( <> - - - + {showPayloadComparison ? ( + + ) : ( + <> + {inputsSection} + {outputsSection} + {propertiesSection} + + )} ); }; diff --git a/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/usePanelNodeData.ts b/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/usePanelNodeData.ts index 626c646c1e3..f01dc0dfbd9 100644 --- a/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/usePanelNodeData.ts +++ b/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/usePanelNodeData.ts @@ -2,18 +2,20 @@ import type { AppDispatch } from '../../../core'; import { useNodeDisplayName, useNodeMetadata } from '../../../core'; import { ErrorLevel } from '../../../core/state/operation/operationMetadataSlice'; import { useIconUri, useOperationErrorInfo } from '../../../core/state/operation/operationSelector'; +import { useSharedNodeUi as useSharedNodeUiSelector } from '../../../core/state/designerOptions/designerOptionsSelectors'; import { setPinnedPanelActiveTab, setSelectedPanelActiveTab } from '../../../core/state/panel/panelSlice'; import { useIsNodePinnedToOperationPanel, useOperationPanelAlternateNodeActiveTabId, useOperationPanelSelectedNodeActiveTabId, } from '../../../core/state/panel/panelSelectors'; -import { useOperationQuery } from '../../../core/state/selectors/actionMetadataSelector'; -import { useNodeDescription, useRunData } from '../../../core/state/workflow/workflowSelectors'; +import { useOperationInfo, useOperationQuery } from '../../../core/state/selectors/actionMetadataSelector'; +import { useActionMetadata, useNodeDescription, useRunData } from '../../../core/state/workflow/workflowSelectors'; import { usePanelTabs } from './usePanelTabs'; import type { PanelNodeData } from '@microsoft/designer-ui'; import { isBuiltInAgentTool } from '@microsoft/logic-apps-shared'; import { useDispatch } from 'react-redux'; +import { getPanelOperationGlyph } from '../../sharedNodeGlyph'; // SVG icon for built-in agent tools (code brackets icon: ) const BUILT_IN_TOOL_ICON_URI = @@ -30,8 +32,11 @@ export const usePanelNodeData = (nodeId: string | undefined): PanelNodeData | un const errorInfo = useOperationErrorInfo(nonNullNodeId); const iconUri = useIconUri(nonNullNodeId); const nodeMetadata = useNodeMetadata(nonNullNodeId); + const operationInfo = useOperationInfo(nonNullNodeId); + const actionMetadata = useActionMetadata(nonNullNodeId); const runData = useRunData(nonNullNodeId); const tabs = usePanelTabs({ nodeId: nonNullNodeId }); + const sharedNodeUi = useSharedNodeUiSelector(); const opQuery = useOperationQuery(nonNullNodeId); @@ -54,14 +59,22 @@ export const usePanelNodeData = (nodeId: string | undefined): PanelNodeData | un // Check if this is a built-in agent tool (like code_interpreter) and provide a default icon const isBuiltInTool = isBuiltInAgentTool(nonNullNodeId); const effectiveIconUri = iconUri || (isBuiltInTool ? BUILT_IN_TOOL_ICON_URI : ''); + const isLoading = !isError && !subgraphType && !hasRunDataOnly ? opQuery.isLoading : false; + const operationType = operationInfo?.type || actionMetadata?.type; + const operationKind = operationInfo?.type ? operationInfo.kind : actionMetadata?.kind; + const operationIcon = + sharedNodeUi && !isError && !isLoading && !isBuiltInTool + ? getPanelOperationGlyph(operationType, operationKind, nodeMetadata?.isTrigger ? 'trigger' : 'action') + : undefined; return { comment, + operationIcon, displayName, errorMessage: errorInfo?.message, iconUri: effectiveIconUri, isError, - isLoading: !isError && !subgraphType && !hasRunDataOnly ? opQuery.isLoading : false, + isLoading, nodeId, onSelectTab: (tabId) => { dispatch(selectTab(tabId)); diff --git a/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/useRawInputsOutputs.ts b/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/useRawInputsOutputs.ts index ade4d1a98fd..e3710564788 100644 --- a/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/useRawInputsOutputs.ts +++ b/libs/designer-v2/src/lib/ui/panel/nodeDetailsPanel/useRawInputsOutputs.ts @@ -1,4 +1,4 @@ -import { useRunData } from '../../../core/state/workflow/workflowSelectors'; +import { useNodeMetadata, useRunData, useSelectedLoopRepetition } from '../../../core/state/workflow/workflowSelectors'; import { RunService } from '@microsoft/logic-apps-shared'; import { useQuery } from '@tanstack/react-query'; import { useCallback } from 'react'; @@ -6,6 +6,7 @@ import { useCallback } from 'react'; export interface RawInputsOutputs { inputs: Record; outputs: Record; + loopPayloadRevision?: string; } const emptyData: RawInputsOutputs = { inputs: {}, outputs: {} }; @@ -17,6 +18,11 @@ const emptyData: RawInputsOutputs = { inputs: {}, outputs: {} }; */ export const useRawInputsOutputs = (nodeId: string, options?: { enabled?: boolean }) => { const runData = useRunData(nodeId); + const loopRepetition = useSelectedLoopRepetition(nodeId); + const scopedMetadata = useNodeMetadata(loopRepetition && runData ? nodeId : undefined); + const loopPayloadRevision = scopedMetadata?.loopPayloadRevision; + // Binding mutates the display data, not the response used for raw I/O and inline fallback. + const payloadSource = loopRepetition ? scopedMetadata?.runDataRepetitionSource : runData; const actionTrackingId = runData?.correlation?.actionTrackingId; const startTime = runData?.startTime; @@ -24,15 +30,44 @@ export const useRawInputsOutputs = (nodeId: string, options?: { enabled?: boolea const getActionInputsOutputs = useCallback(async (): Promise => { const actionLinks = await RunService().getActionLinks(runData, nodeId); + const resolveSide = ( + linkedValue: Record | undefined, + inlineValue: Record | undefined, + hasContentLink: boolean + ) => { + if (hasContentLink) { + return linkedValue ?? {}; + } + // Production run services return `{}` when a side has no content link, which would mask + // inline repetition payloads if merged with `??`. Prefer raw inline repetition data when + // present on the unmutated repetition source. + if (loopRepetition && inlineValue !== undefined) { + return inlineValue; + } + return linkedValue ?? inlineValue ?? {}; + }; return { - inputs: actionLinks.inputs ?? runData?.inputs ?? {}, - outputs: actionLinks.outputs ?? runData?.outputs ?? {}, + inputs: resolveSide(actionLinks.inputs, payloadSource?.inputs, !!runData?.inputsLink?.uri), + outputs: resolveSide(actionLinks.outputs, payloadSource?.outputs, !!runData?.outputsLink?.uri), + ...(loopRepetition && { loopPayloadRevision }), }; - }, [nodeId, runData]); + }, [nodeId, runData, payloadSource, loopRepetition, loopPayloadRevision]); - return useQuery(['actionInputsOutputs', { nodeId, actionTrackingId, startTime, endTime }], getActionInputsOutputs, { - refetchOnWindowFocus: false, - placeholderData: emptyData, - ...(options?.enabled !== undefined ? { enabled: options.enabled } : {}), - }); + return useQuery( + [ + 'actionInputsOutputs', + loopRepetition ? { nodeId, loopRepetition, loopPayloadRevision } : { nodeId, actionTrackingId, startTime, endTime }, + ], + getActionInputsOutputs, + { + refetchOnWindowFocus: false, + placeholderData: emptyData, + ...(options?.enabled !== undefined ? { enabled: options.enabled } : {}), + ...(loopRepetition && { + enabled: !!payloadSource && !!loopPayloadRevision && options?.enabled !== false, + keepPreviousData: false, + refetchOnMount: false, + }), + } + ); }; diff --git a/libs/designer-v2/src/lib/ui/panel/recommendation/__test__/favorites.spec.tsx b/libs/designer-v2/src/lib/ui/panel/recommendation/__test__/favorites.spec.tsx new file mode 100644 index 00000000000..43c9ca135b3 --- /dev/null +++ b/libs/designer-v2/src/lib/ui/panel/recommendation/__test__/favorites.spec.tsx @@ -0,0 +1,154 @@ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, cleanup, fireEvent } from '@testing-library/react'; +import { IntlProvider } from 'react-intl'; +import { composeOperation, type Connector } from '@microsoft/logic-apps-shared'; +import { Favorites } from '../categories/Favorites'; + +const mockGrid = vi.fn((props: any) => ( +
+ {props.items.map((item: any) => ( +
+ {item.title ?? item.connectorName} +
+ ))} +
+)); + +vi.mock('@microsoft/designer-ui', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + Grid: (props: any) => mockGrid(props), + }; +}); + +vi.mock('../../../../core/state/panel/panelSelectors', () => ({ + useDiscoveryPanelFavoriteOperations: vi.fn(() => []), +})); + +vi.mock('../../../../core/queries/browse', () => ({ + useFavoriteOperations: vi.fn(), +})); + +vi.mock('../../../../core/state/designerView/designerViewSelectors', () => ({ + useIsAgenticWorkflow: vi.fn(() => false), +})); + +vi.mock('../../../../core/state/designerOptions/designerOptionsSelectors', () => ({ + useSharedNodeUi: vi.fn(() => false), +})); + +import { useFavoriteOperations } from '../../../../core/queries/browse'; +import { useIsAgenticWorkflow } from '../../../../core/state/designerView/designerViewSelectors'; +import { useSharedNodeUi } from '../../../../core/state/designerOptions/designerOptionsSelectors'; + +const mockUseFavoriteOperations = vi.mocked(useFavoriteOperations); +const mockUseIsAgenticWorkflow = vi.mocked(useIsAgenticWorkflow); +const mockUseSharedNodeUi = vi.mocked(useSharedNodeUi); + +const sampleConnector = { + id: 'connectionProviders/http', + name: 'http', + type: 'ServiceProvider', + properties: { + displayName: 'HTTP', + description: 'HTTP connector', + iconUri: 'https://example.test/http.png', + brandColor: '#0078d4', + }, +} as unknown as Connector; + +const agentConnector = { + id: 'connectionProviders/agent', + name: 'agent', + type: 'ServiceProvider', + properties: { + displayName: 'Agent', + description: 'Agent connector', + iconUri: 'https://example.test/agent.png', + brandColor: '#0078d4', + }, +} as unknown as Connector; + +const renderFavorites = () => + render( + + + + ); + +describe('Favorites', () => { + const fetchNextPage = vi.fn(); + + beforeEach(() => { + vi.clearAllMocks(); + mockUseIsAgenticWorkflow.mockReturnValue(false); + mockUseSharedNodeUi.mockReturnValue(false); + mockUseFavoriteOperations.mockReturnValue({ + favoriteConnectorsData: [sampleConnector, agentConnector], + isLoadingFavoriteConnectors: false, + favoriteActionsData: [composeOperation], + favoriteActionsFetchNextPage: fetchNextPage, + favoriteActionsHasNextPage: false, + favoriteActionsIsFetching: false, + favoriteActionsIsFetchingNextPage: false, + }); + }); + + afterEach(() => { + cleanup(); + }); + + test('threads shared built-in glyph icons only when useSharedNodeUi is enabled and filters agent connectors outside agentic workflows', () => { + const { rerender } = renderFavorites(); + + expect(screen.getByTestId(`favorite-item-${composeOperation.id}`)).toHaveAttribute('data-has-icon', 'false'); + expect(screen.getByTestId('favorite-item-connectionProviders/http')).toHaveAttribute('data-has-icon', 'false'); + expect(screen.queryByTestId('favorite-item-connectionProviders/agent')).not.toBeInTheDocument(); + + mockUseSharedNodeUi.mockReturnValue(true); + mockUseIsAgenticWorkflow.mockReturnValue(true); + rerender( + + + + ); + + expect(screen.getByTestId(`favorite-item-${composeOperation.id}`)).toHaveAttribute('data-has-icon', 'true'); + expect(screen.getByTestId('favorite-item-connectionProviders/http')).toHaveAttribute('data-has-icon', 'false'); + expect(screen.getByTestId('favorite-item-connectionProviders/agent')).toBeInTheDocument(); + }); + + test('renders Load more / Loading more link and triggers pagination', () => { + mockUseFavoriteOperations.mockReturnValue({ + favoriteConnectorsData: [], + isLoadingFavoriteConnectors: false, + favoriteActionsData: [composeOperation], + favoriteActionsFetchNextPage: fetchNextPage, + favoriteActionsHasNextPage: true, + favoriteActionsIsFetching: false, + favoriteActionsIsFetchingNextPage: false, + }); + + const { rerender } = renderFavorites(); + const loadMore = screen.getByText('Load more'); + fireEvent.click(loadMore); + expect(fetchNextPage).toHaveBeenCalledTimes(1); + + mockUseFavoriteOperations.mockReturnValue({ + favoriteConnectorsData: [], + isLoadingFavoriteConnectors: false, + favoriteActionsData: [composeOperation], + favoriteActionsFetchNextPage: fetchNextPage, + favoriteActionsHasNextPage: true, + favoriteActionsIsFetching: false, + favoriteActionsIsFetchingNextPage: true, + }); + rerender( + + + + ); + expect(screen.getByText('Loading more...')).toBeInTheDocument(); + }); +}); diff --git a/libs/designer-v2/src/lib/ui/panel/recommendation/__test__/operationsAccordion.spec.tsx b/libs/designer-v2/src/lib/ui/panel/recommendation/__test__/operationsAccordion.spec.tsx new file mode 100644 index 00000000000..5f3ee6cd4d4 --- /dev/null +++ b/libs/designer-v2/src/lib/ui/panel/recommendation/__test__/operationsAccordion.spec.tsx @@ -0,0 +1,179 @@ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, cleanup, fireEvent } from '@testing-library/react'; +import { IntlProvider } from 'react-intl'; +import { Provider } from 'react-redux'; +import { configureStore } from '@reduxjs/toolkit'; +import { FluentProvider, webLightTheme } from '@fluentui/react-components'; +import { recurrenceOperation, requestOperation } from '@microsoft/logic-apps-shared'; +import type { OperationActionData } from '@microsoft/designer-ui'; +import { OperationsAccordion } from '../details/operationsAccordion'; + +const mockAddOperation = vi.fn((payload: unknown) => ({ type: 'mock/addOperation', payload })); + +vi.mock('../../../../core', () => ({ + addOperation: (payload: unknown) => mockAddOperation(payload), +})); + +vi.mock('../../../../core/state/panel/panelSelectors', () => ({ + useDiscoveryPanelRelationshipIds: vi.fn(() => ({ + graphId: 'root', + parentId: undefined, + childId: undefined, + })), +})); + +vi.mock('../../../../core/state/designerOptions/designerOptionsSelectors', () => ({ + useSharedNodeUi: vi.fn(() => false), +})); + +vi.mock('../details/operationAccordionItem', () => ({ + OperationAccordionItem: ({ value, title, items, onOperationClick }: any) => ( +
+ {title} + {items.map((item: OperationActionData) => ( + + ))} +
+ ), +})); + +import { useSharedNodeUi } from '../../../../core/state/designerOptions/designerOptionsSelectors'; + +const mockUseSharedNodeUi = vi.mocked(useSharedNodeUi); + +const sampleAction: OperationActionData = { + id: 'compose', + title: 'Compose', + isTrigger: false, + apiId: 'connectionProviders/dataOperationNew', +}; + +const sampleTrigger: OperationActionData = { + id: 'custom-trigger', + title: 'Custom Trigger', + isTrigger: true, + apiId: 'connectionProviders/http', +}; + +const renderAccordion = (props: Partial[0]> = {}) => { + const store = configureStore({ reducer: { dummy: (state = {}) => state } }); + const dispatchSpy = vi.spyOn(store, 'dispatch'); + const rendered = render( + + + + + + + + ); + return { ...rendered, dispatchSpy }; +}; + +describe('OperationsAccordion', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockUseSharedNodeUi.mockReturnValue(false); + }); + + afterEach(() => { + cleanup(); + }); + + test('threads shared built-in glyphs to suggested triggers when useSharedNodeUi is enabled and dispatches addOperation on click', () => { + mockUseSharedNodeUi.mockReturnValue(false); + const { rerender, dispatchSpy } = renderAccordion({ triggers: [], actions: [sampleAction], isTrigger: true }); + + expect(screen.getByTestId(`accordion-item-${recurrenceOperation.id}`)).toHaveAttribute('data-has-icon', 'false'); + expect(screen.getByTestId(`accordion-item-${requestOperation.id}`)).toHaveAttribute('data-has-icon', 'false'); + + mockUseSharedNodeUi.mockReturnValue(true); + const store = configureStore({ reducer: { dummy: (state = {}) => state } }); + const sharedDispatchSpy = vi.spyOn(store, 'dispatch'); + rerender( + + + + + + + + ); + + expect(screen.getByTestId(`accordion-item-${recurrenceOperation.id}`)).toHaveAttribute('data-has-icon', 'true'); + expect(screen.getByTestId(`accordion-item-${requestOperation.id}`)).toHaveAttribute('data-has-icon', 'true'); + + fireEvent.click(screen.getByTestId(`accordion-item-${recurrenceOperation.id}`)); + expect(mockAddOperation).toHaveBeenCalledWith( + expect.objectContaining({ + operation: recurrenceOperation, + isTrigger: true, + isParallelBranch: false, + }) + ); + expect(sharedDispatchSpy).toHaveBeenCalled(); + + fireEvent.click(screen.getByTestId(`accordion-item-${requestOperation.id}`)); + expect(mockAddOperation).toHaveBeenLastCalledWith( + expect.objectContaining({ + operation: requestOperation, + isTrigger: true, + }) + ); + expect(dispatchSpy).not.toHaveBeenCalled(); + }); + + test('renders triggers and actions sections in both trigger mode and action mode', () => { + const onTriggerClick = vi.fn(); + const onActionClick = vi.fn(); + const { unmount } = renderAccordion({ + triggers: [sampleTrigger], + actions: [sampleAction], + isTrigger: true, + onTriggerClick, + onActionClick, + }); + + expect(screen.getByTestId('accordion-section-triggers')).toBeInTheDocument(); + expect(screen.queryByTestId('accordion-section-suggested-triggers')).not.toBeInTheDocument(); + expect(screen.getByTestId('accordion-section-actions')).toBeInTheDocument(); + fireEvent.click(screen.getByTestId('accordion-item-custom-trigger')); + expect(onTriggerClick).toHaveBeenCalledWith('custom-trigger', 'connectionProviders/http'); + unmount(); + + renderAccordion({ + triggers: [sampleTrigger], + actions: [sampleAction], + isTrigger: false, + onTriggerClick, + onActionClick, + }); + expect(screen.getByTestId('accordion-section-actions')).toBeInTheDocument(); + expect(screen.getByTestId('accordion-section-triggers')).toBeInTheDocument(); + fireEvent.click(screen.getByTestId('accordion-item-compose')); + expect(onActionClick).toHaveBeenCalledWith('compose', 'connectionProviders/dataOperationNew'); + }); +}); diff --git a/libs/designer-v2/src/lib/ui/panel/recommendation/__test__/recommendationPanelContext.spec.tsx b/libs/designer-v2/src/lib/ui/panel/recommendation/__test__/recommendationPanelContext.spec.tsx index 2991ce7f00b..aefb216a4c0 100644 --- a/libs/designer-v2/src/lib/ui/panel/recommendation/__test__/recommendationPanelContext.spec.tsx +++ b/libs/designer-v2/src/lib/ui/panel/recommendation/__test__/recommendationPanelContext.spec.tsx @@ -32,6 +32,7 @@ vi.mock('../../../../core/state/panel/panelSelectors', () => ({ vi.mock('../../../../core/state/designerOptions/designerOptionsSelectors', () => ({ useHostOptions: vi.fn(() => ({ displayRuntimeInfo: true })), + useSharedNodeUi: vi.fn(() => false), })); vi.mock('../../../../core/state/workflow/workflowSelectors', () => ({ diff --git a/libs/designer-v2/src/lib/ui/panel/recommendation/__test__/searchView.spec.tsx b/libs/designer-v2/src/lib/ui/panel/recommendation/__test__/searchView.spec.tsx index 1e14410374d..b2a3d96da0d 100644 --- a/libs/designer-v2/src/lib/ui/panel/recommendation/__test__/searchView.spec.tsx +++ b/libs/designer-v2/src/lib/ui/panel/recommendation/__test__/searchView.spec.tsx @@ -1,12 +1,16 @@ import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, cleanup, waitFor } from '@testing-library/react'; +import { render, screen, cleanup, waitFor, fireEvent } from '@testing-library/react'; import { Provider } from 'react-redux'; import { configureStore } from '@reduxjs/toolkit'; import { IntlProvider } from 'react-intl'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import type { DiscoveryOpArray } from '@microsoft/logic-apps-shared'; +import { composeOperation, FavoriteContext, type DiscoveryOpArray } from '@microsoft/logic-apps-shared'; +import { FluentProvider, webLightTheme } from '@fluentui/react-components'; +import { builtinMcpServerOperation } from '../helpers'; import { SearchView } from '../searchView'; +let renderRealGrid = false; + // Mock the selectors vi.mock('../../../../core/state/panel/panelSelectors', () => ({ useDiscoveryPanelIsAddingTrigger: vi.fn(() => false), @@ -29,6 +33,7 @@ vi.mock('../../../../core/state/designerView/designerViewSelectors', () => ({ vi.mock('../../../../core/state/designerOptions/designerOptionsSelectors', () => ({ useEnableNestedAgentLoops: vi.fn(() => false), + useSharedNodeUi: vi.fn(() => false), })); vi.mock('../../../../core/state/panel/panelSlice', () => ({ @@ -46,21 +51,28 @@ vi.mock('@microsoft/designer-ui', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, - SearchResultsGridV2: vi.fn(({ searchTerm, operationSearchResults, isLoadingSearch, onOperationClick, onConnectorClick }) => ( -
- {searchTerm} - {isLoadingSearch ? 'loading' : 'loaded'} - {operationSearchResults?.length ?? 0} - {operationSearchResults?.map((op: any) => ( - + ))} + - ))} - -
- )), +
+ ); + }), }; }); @@ -88,7 +100,7 @@ import { } from '../../../../core/state/panel/panelSelectors'; import { useIsWithinAgenticLoop } from '../../../../core/state/workflow/workflowSelectors'; import { useIsAgenticWorkflow, useIsA2AWorkflow } from '../../../../core/state/designerView/designerViewSelectors'; -import { useEnableNestedAgentLoops } from '../../../../core/state/designerOptions/designerOptionsSelectors'; +import { useEnableNestedAgentLoops, useSharedNodeUi } from '../../../../core/state/designerOptions/designerOptionsSelectors'; import { selectOperationGroupId } from '../../../../core/state/panel/panelSlice'; import { useMcpServersQuery } from '../../../../core/queries/browse'; @@ -98,6 +110,7 @@ const mockUseIsWithinAgenticLoop = vi.mocked(useIsWithinAgenticLoop); const mockUseIsAgenticWorkflow = vi.mocked(useIsAgenticWorkflow); const mockUseIsA2AWorkflow = vi.mocked(useIsA2AWorkflow); const mockUseEnableNestedAgentLoops = vi.mocked(useEnableNestedAgentLoops); +const mockUseSharedNodeUi = vi.mocked(useSharedNodeUi); const mockSelectOperationGroupId = vi.mocked(selectOperationGroupId); const mockUseMcpServersQuery = vi.mocked(useMcpServersQuery); @@ -132,6 +145,8 @@ const createWrapper = () => { ); }; +const favoriteContext = { isOperationFavorited: () => false, onFavoriteClick: vi.fn() }; + describe('SearchView', () => { const mockOnOperationClick = vi.fn(); const mockSetGroupByConnector = vi.fn(); @@ -163,6 +178,7 @@ describe('SearchView', () => { beforeEach(() => { vi.clearAllMocks(); + renderRealGrid = false; vi.mocked(useDiscoveryPanelIsAddingTrigger).mockReturnValue(false); mockUseDiscoveryPanelRelationshipIds.mockReturnValue({ graphId: 'root', @@ -174,6 +190,7 @@ describe('SearchView', () => { mockUseIsAgenticWorkflow.mockReturnValue(false); mockUseIsA2AWorkflow.mockReturnValue(false); mockUseEnableNestedAgentLoops.mockReturnValue(false); + mockUseSharedNodeUi.mockReturnValue(false); mockUseMcpServersQuery.mockReturnValue({ data: { data: [] }, isLoading: false, @@ -182,6 +199,73 @@ describe('SearchView', () => { afterEach(() => { cleanup(); + vi.unstubAllGlobals(); + }); + + test.each([ + { mode: 'flat', groupByConnector: false, mcpName: 'MCP server', mcpIcon: /^data:image\/svg\+xml/ }, + { mode: 'grouped', groupByConnector: true, mcpName: 'MCP server (MCP)', mcpIcon: 'https://example.com/mcp.svg' }, + ])('gates a built-in tile without changing the $mode MCP row', async ({ groupByConnector, mcpName, mcpIcon }) => { + renderRealGrid = true; + vi.stubGlobal( + 'ResizeObserver', + class { + observe() {} + disconnect() {} + } + ); + const allOperations: DiscoveryOpArray = [ + { ...composeOperation, name: 'match-compose' }, + { + ...builtinMcpServerOperation, + id: 'mcp-connection', + name: 'match-mcp', + type: 'builtinMcpClientToolConnection', + properties: { + ...builtinMcpServerOperation.properties, + summary: 'MCP server', + api: { ...builtinMcpServerOperation.properties.api, iconUri: 'https://example.com/mcp.svg' }, + }, + }, + ]; + const search = () => ( + + + + + + ); + const { rerender } = render(search(), { wrapper: createWrapper() }); + const expectMcpArtwork = () => { + const row = screen.getByRole('button', { name: mcpName }); + expect(row.querySelector('[data-node-glyph]')).not.toBeInTheDocument(); + expect(row.querySelector('img')).toHaveAttribute('src', expect.stringMatching(mcpIcon)); + }; + + const composeRow = await screen.findByRole('button', { name: 'Compose' }); + expect(composeRow.querySelector('img')).toHaveAttribute('src', composeOperation.properties.api.iconUri); + expectMcpArtwork(); + + mockUseSharedNodeUi.mockReturnValue(true); + rerender(search()); + const row = screen.getByRole('button', { name: 'Compose' }); + const glyph = row.querySelector('[data-tone="violet"] [data-icon-name="BracesRegular"]'); + expect(glyph).toBeInTheDocument(); + expect(glyph?.closest('[aria-hidden]')).toHaveAttribute('aria-hidden', 'true'); + expect(row).toHaveAttribute('tabindex', '0'); + expect(row.querySelector('img')).not.toBeInTheDocument(); + fireEvent.keyDown(row, { key: 'Enter' }); + expect(mockOnOperationClick).toHaveBeenCalledWith(composeOperation.id, composeOperation.properties.api.id); + + expectMcpArtwork(); }); describe('Rendering', () => { diff --git a/libs/designer-v2/src/lib/ui/panel/recommendation/browse/mcpServersBrowse.tsx b/libs/designer-v2/src/lib/ui/panel/recommendation/browse/mcpServersBrowse.tsx index 3b1e8abc335..d3b6a551d24 100644 --- a/libs/designer-v2/src/lib/ui/panel/recommendation/browse/mcpServersBrowse.tsx +++ b/libs/designer-v2/src/lib/ui/panel/recommendation/browse/mcpServersBrowse.tsx @@ -229,7 +229,7 @@ export const McpServersBrowse = ({ onOperationClick: _onOperationClick, searchTe
) : ( getOperationCardDataFromOperation(operation))} onOperationSelected={(operationId) => { const server = filteredAndSortedServers.find((s) => s.id === operationId); if (server) { diff --git a/libs/designer-v2/src/lib/ui/panel/recommendation/categories/Favorites.tsx b/libs/designer-v2/src/lib/ui/panel/recommendation/categories/Favorites.tsx index feea7312534..f87e4397e94 100644 --- a/libs/designer-v2/src/lib/ui/panel/recommendation/categories/Favorites.tsx +++ b/libs/designer-v2/src/lib/ui/panel/recommendation/categories/Favorites.tsx @@ -7,6 +7,7 @@ import { useFavoritesStyles } from './styles/Favorites.styles'; import { useIntl } from 'react-intl'; import { useIsAgenticWorkflow } from '../../../../core/state/designerView/designerViewSelectors'; import { Grid } from '@microsoft/designer-ui'; +import { useSharedNodeUi } from '../../../../core/state/designerOptions/designerOptionsSelectors'; export interface FavoritesProps { onConnectorSelected: (connectorId: string, origin?: string) => void; @@ -17,6 +18,7 @@ export const Favorites = ({ onConnectorSelected, onOperationSelected }: Favorite const intl = useIntl(); const classes = useFavoritesStyles(); const isAgenticWorkflow = useIsAgenticWorkflow(); + const sharedNodeUi = useSharedNodeUi(); const favoriteOperationIds = useDiscoveryPanelFavoriteOperations(); const { @@ -32,10 +34,10 @@ export const Favorites = ({ onConnectorSelected, onOperationSelected }: Favorite const favoriteOperations = useMemo(() => { const favorites = [ ...favoriteConnectorsData.map(getOperationGroupCardDataFromConnector), - ...favoriteActionsData.map(getOperationCardDataFromOperation), + ...favoriteActionsData.map((operation) => getOperationCardDataFromOperation(operation, sharedNodeUi)), ]; return isAgenticWorkflow ? favorites : favorites.filter((f) => f.apiId !== 'connectionProviders/agent'); - }, [favoriteConnectorsData, favoriteActionsData, isAgenticWorkflow]); + }, [favoriteConnectorsData, favoriteActionsData, isAgenticWorkflow, sharedNodeUi]); const loadingMoreText = intl.formatMessage({ defaultMessage: 'Loading more...', diff --git a/libs/designer-v2/src/lib/ui/panel/recommendation/details/connectorDetailsView.tsx b/libs/designer-v2/src/lib/ui/panel/recommendation/details/connectorDetailsView.tsx index 8c6c0bb303c..ec1bf0c68eb 100644 --- a/libs/designer-v2/src/lib/ui/panel/recommendation/details/connectorDetailsView.tsx +++ b/libs/designer-v2/src/lib/ui/panel/recommendation/details/connectorDetailsView.tsx @@ -1,7 +1,7 @@ import { useMemo } from 'react'; import { Text, Spinner } from '@fluentui/react-components'; import type { OperationActionData } from '@microsoft/designer-ui'; -import { OperationActionDataFromOperation, FavoriteButton } from '@microsoft/designer-ui'; +import { FavoriteButton, OperationActionDataFromOperation } from '@microsoft/designer-ui'; import { isNullOrUndefined, type Connector } from '@microsoft/logic-apps-shared'; import { useDiscoveryPanelIsAddingTrigger, useIsAddingAgentTool } from '../../../../core/state/panel/panelSelectors'; import { useIsWithinAgenticLoop } from '../../../../core/state/workflow/workflowSelectors'; @@ -9,6 +9,8 @@ import { useOperationsByConnector } from '../../../../core/queries/browse'; import constants from '../../../../common/constants'; import { useConnectorDetailsViewStyles } from './styles/ConnectorDetailsView.styles'; import { OperationsAccordion } from './operationsAccordion'; +import { getPickerOperationGlyph } from '../../../sharedNodeGlyph'; +import { useSharedNodeUi } from '../../../../core/state/designerOptions/designerOptionsSelectors'; type ConnectorDetailsViewProps = { connector?: Connector; @@ -20,6 +22,7 @@ export const ConnectorDetailsView = ({ connector, onOperationClick, showActions const classes = useConnectorDetailsViewStyles(); const isTrigger = useDiscoveryPanelIsAddingTrigger(); const isAgentTool = useIsAddingAgentTool(); + const sharedNodeUi = useSharedNodeUi(); // Fetch operations for this connector const connectorId = connector?.id || ''; @@ -65,14 +68,17 @@ export const ConnectorDetailsView = ({ connector, onOperationClick, showActions } return groupOperations - .map((operation) => OperationActionDataFromOperation(operation)) + .map((operation) => ({ + ...OperationActionDataFromOperation(operation), + icon: sharedNodeUi ? getPickerOperationGlyph(operation) : undefined, + })) .filter(filterItems) .sort((a, b) => { const aTitle = a.title ?? ''; const bTitle = b.title ?? ''; return aTitle.localeCompare(bTitle); }); - }, [groupOperations, filterItems]); + }, [groupOperations, filterItems, sharedNodeUi]); const triggers = useMemo(() => allOperations.filter((op) => op.isTrigger), [allOperations]); const actions = useMemo(() => (showActions ? allOperations.filter((op) => !op.isTrigger) : []), [allOperations, showActions]); diff --git a/libs/designer-v2/src/lib/ui/panel/recommendation/details/operationsAccordion.tsx b/libs/designer-v2/src/lib/ui/panel/recommendation/details/operationsAccordion.tsx index 26950befc52..c32f6eace2b 100644 --- a/libs/designer-v2/src/lib/ui/panel/recommendation/details/operationsAccordion.tsx +++ b/libs/designer-v2/src/lib/ui/panel/recommendation/details/operationsAccordion.tsx @@ -8,6 +8,8 @@ import { useOperationsAccordionStyles } from './styles/OperationsAccordion.style import { recurrenceOperation, requestOperation } from '@microsoft/logic-apps-shared'; import { OperationAccordionItem } from './operationAccordionItem'; import type { OperationActionData } from '@microsoft/designer-ui'; +import { getPickerOperationGlyph } from '../../../sharedNodeGlyph'; +import { useSharedNodeUi } from '../../../../core/state/designerOptions/designerOptionsSelectors'; export interface OperationsAccordionProps { triggers: OperationActionData[]; @@ -30,6 +32,7 @@ export const OperationsAccordion = ({ const dispatch = useDispatch(); const relationshipIds = useDiscoveryPanelRelationshipIds(); const intl = useIntl(); + const sharedNodeUi = useSharedNodeUi(); const handleSuggestedTriggerClick = useCallback( (operation: any) => { @@ -79,26 +82,20 @@ export const OperationsAccordion = ({ }); // Suggested triggers as OperationActionData for Grid component - const suggestedTriggers = [ - { - id: recurrenceOperation.id, - title: recurrenceOperation.properties.summary, - description: recurrenceOperation.properties.description, - iconUri: recurrenceOperation.properties.iconUri, - brandColor: recurrenceOperation.properties.brandColor, - isTrigger: true, - apiId: recurrenceOperation.properties?.api?.id, - }, - { - id: requestOperation.id, - title: requestOperation.properties.summary, - description: requestOperation.properties.description, - iconUri: requestOperation.properties.iconUri, - brandColor: requestOperation.properties.brandColor, - isTrigger: true, - apiId: requestOperation.properties?.api?.id, - }, - ]; + const suggestedTriggers = useMemo( + () => + [recurrenceOperation, requestOperation].map((operation) => ({ + id: operation.id, + title: operation.properties.summary, + description: operation.properties.description, + iconUri: operation.properties.iconUri, + brandColor: operation.properties.brandColor, + isTrigger: true, + apiId: operation.properties.api.id, + icon: sharedNodeUi ? getPickerOperationGlyph(operation) : undefined, + })), + [sharedNodeUi] + ); const handleSuggestedTriggerGridClick = useCallback( (operationId: string) => { diff --git a/libs/designer-v2/src/lib/ui/panel/recommendation/helpers.ts b/libs/designer-v2/src/lib/ui/panel/recommendation/helpers.ts index f873a7973ff..1733d10e3fc 100644 --- a/libs/designer-v2/src/lib/ui/panel/recommendation/helpers.ts +++ b/libs/designer-v2/src/lib/ui/panel/recommendation/helpers.ts @@ -15,6 +15,8 @@ import { getIconUriFromConnector, } from '@microsoft/logic-apps-shared'; +import { getPickerOperationGlyph } from '../../sharedNodeGlyph'; + export const MCP_CLIENT_CONNECTOR_ID = 'connectionProviders/mcpclient'; const MCP_CLIENT_BRAND_COLOR = '#000000'; const BUILTIN_MCP_ADD_ICON_URI = @@ -82,7 +84,10 @@ export const connectionToOperation = (connection: Connection): DiscoveryOperatio }; }; -export const getOperationCardDataFromOperation = (operation: DiscoveryOperation): OperationActionData => { +export const getOperationCardDataFromOperation = ( + operation: DiscoveryOperation, + sharedNodeUi = false +): OperationActionData => { const isMcpClientTool = operation.properties.operationType === 'McpClientTool' && operation.id !== 'nativemcpclient'; return { id: operation.id, @@ -90,6 +95,7 @@ export const getOperationCardDataFromOperation = (operation: DiscoveryOperation< description: operation.properties.description, brandColor: operation.properties.api.brandColor, iconUri: operation.properties.api.iconUri, + icon: sharedNodeUi ? getPickerOperationGlyph(operation) : undefined, connectorName: operation.properties.api.displayName, category: getConnectorCategoryString(operation.properties.api), isTrigger: !!operation.properties?.trigger, diff --git a/libs/designer-v2/src/lib/ui/panel/recommendation/searchView.tsx b/libs/designer-v2/src/lib/ui/panel/recommendation/searchView.tsx index 6c8a71befd2..a4ba127f2d7 100644 --- a/libs/designer-v2/src/lib/ui/panel/recommendation/searchView.tsx +++ b/libs/designer-v2/src/lib/ui/panel/recommendation/searchView.tsx @@ -13,11 +13,12 @@ import { useIsAddingAgentTool, } from '../../../core/state/panel/panelSelectors'; import { useIsA2AWorkflow, useIsAgenticWorkflow } from '../../../core/state/designerView/designerViewSelectors'; -import { useEnableNestedAgentLoops } from '../../../core/state/designerOptions/designerOptionsSelectors'; +import { useEnableNestedAgentLoops, useSharedNodeUi } from '../../../core/state/designerOptions/designerOptionsSelectors'; import { DefaultSearchOperationsService } from './SearchOpeationsService'; import constants from '../../../common/constants'; import { ALLOWED_A2A_CONNECTOR_NAMES } from './helpers'; import { useMcpServersQuery } from '../../../core/queries/browse'; +import { getPickerOperationGlyph } from '../../sharedNodeGlyph'; type SearchViewProps = { searchTerm: string; @@ -47,6 +48,7 @@ export const SearchView: FC = ({ const isRoot = useMemo(() => parentGraphId === 'root', [parentGraphId]); const isA2AWorkflow = useIsA2AWorkflow(); const enableNestedAgentLoops = useEnableNestedAgentLoops(); + const sharedNodeUi = useSharedNodeUi(); const dispatch = useDispatch(); @@ -175,6 +177,7 @@ export const SearchView: FC = ({ groupByConnector={groupByConnector} setGroupByConnector={setGroupByConnector} displayRuntimeInfo={displayRuntimeInfo} + renderOperationIcon={sharedNodeUi ? getPickerOperationGlyph : undefined} /> ); }; diff --git a/libs/designer-v2/src/lib/ui/sharedNodeGlyph.tsx b/libs/designer-v2/src/lib/ui/sharedNodeGlyph.tsx new file mode 100644 index 00000000000..f5d544103a5 --- /dev/null +++ b/libs/designer-v2/src/lib/ui/sharedNodeGlyph.tsx @@ -0,0 +1,127 @@ +import { makeStyles } from '@fluentui/react-components'; +import { NodeIconTile, type NodeCategory } from '@microsoft/designer-ui-v2'; +import { + a2aRequestOperation, + composeOperation, + getBuiltInOperationInfo, + getClientBuiltInOperations, + inlinePythonCodeOperation, + slidingWindowOperation, + UnsupportedException, + type DiscoveryOperation, + type DiscoveryResultTypes, +} from '@microsoft/logic-apps-shared'; +import { getControlOperationGlyph, getOperationNodeGlyph } from './CustomNodes/components/card/operationNodeGlyphs'; + +const normalize = (value?: string) => value?.trim().toLowerCase() || undefined; +// Strip leading slashes so Standard (`connectionProviders/workflow`) and Consumption (`/connectionProviders/workflow`) share one key. +const operationKey = (apiId: string, id: string) => `${apiId.trim().replace(/^\/+/, '').toLowerCase()}\0${id.trim().toLowerCase()}`; +type DiscoveryRow = DiscoveryOperation; + +interface KnownOperationIdentity { + type: string | undefined; + kind: string | undefined; + isTrigger: boolean; +} + +// Discovery already distinguishes variants such as CSV/HTML Table and plain/Swagger HTTP. +// The workflow-definition resolver alone cannot distinguish them without inputs or metadata. +// Built lazily on first lookup so importing helpers does not eagerly evaluate built-in operation manifests. +let knownOperationsCache: Map | undefined; +const getKnownOperations = () => { + if (!knownOperationsCache) { + const builtInRows: DiscoveryRow[] = [ + ...getClientBuiltInOperations(), + composeOperation, + slidingWindowOperation, + inlinePythonCodeOperation as DiscoveryRow, + a2aRequestOperation, + ]; + knownOperationsCache = new Map([ + ...builtInRows.map((row): [string, KnownOperationIdentity] => [ + operationKey(row.properties.api.id, row.id), + { + type: normalize(row.properties.operationType), + kind: normalize(row.properties.operationKind), + isTrigger: !!row.properties.trigger, + }, + ]), + // Additional verified Standard and Consumption built-in discovery identities not present in getClientBuiltInOperations(). + [operationKey('connectionProviders/workflow', 'invokenestedagent'), { type: 'nestedagent', kind: undefined, isTrigger: false }], + [operationKey('connectionProviders/workflow', 'invokeworkflow'), { type: 'workflow', kind: undefined, isTrigger: false }], + [operationKey('connectionProviders/a2aconsumption', 'a2arequest'), { type: 'request', kind: 'agent', isTrigger: true }], + [operationKey('connectionProviders/inlineCode', 'csharpcode'), { type: 'csharpcode', kind: undefined, isTrigger: false }], + ]); + } + return knownOperationsCache; +}; + +const useStyles = makeStyles({ + pickerTile: { width: '24px', height: '24px', fontSize: '16px' }, +}); + +const resolveGlyph = (type: string, kind: string | undefined, category: NodeCategory) => { + const controlGlyph = getControlOperationGlyph(type); + const glyph = controlGlyph ?? getOperationNodeGlyph(type, kind); + const tileCategory = controlGlyph && type !== 'scope' ? 'control' : type === 'agent' || type === 'nestedagent' ? 'agent' : category; + return glyph ? { ...glyph, category: tileCategory } : undefined; +}; + +const matchesKnownOperation = (key: string, type: string, kind: string | undefined, isTrigger: boolean) => { + const known = getKnownOperations().get(key); + if (known) { + return type === known.type && kind === known.kind && isTrigger === known.isTrigger; + } + + // Standard can also return server-only operations. Check their exact manifest identity. + try { + const { connectorId, operationId } = getBuiltInOperationInfo({ type, kind }, isTrigger); + return key === operationKey(connectorId, operationId); + } catch (error) { + if (error instanceof UnsupportedException) { + return false; + } + throw error; + } +}; + +type Glyph = NonNullable>; + +const OperationGlyphTile = ({ glyph, picker }: { glyph: Glyph; picker?: boolean }) => { + const styles = useStyles(); + return ( + + ); +}; + +export const getPanelOperationGlyph = (type: string | undefined, kind: string | undefined, category: NodeCategory) => { + const glyph = type && resolveGlyph(type.toLowerCase(), kind, category); + return glyph ? : undefined; +}; + +export const getPickerOperationGlyph = (operation: DiscoveryRow) => { + const { properties, id } = operation; + const apiId = properties.api?.id; + // Use the same type/kind pair as addOperation. A contradictory raw pair cannot authorize a replacement, + // while allowing Consumption payloads whose raw `type` echoes `id` (e.g. `invokeworkflow` with `operationType: Workflow`). + const type = normalize(properties.operationType); + const kind = normalize(properties.operationKind); + const rawType = normalize(operation.type); + const rawKind = normalize(operation.kind); + const normalizedId = normalize(id); + const rawTypeMatches = !rawType || rawType === type || rawType === normalizedId; + if (!apiId || !id || !type || !rawTypeMatches || (rawKind && rawKind !== kind) || properties.isCustomApi) { + return undefined; + } + const isTrigger = !!properties.trigger; + const glyph = resolveGlyph(type, kind, isTrigger ? 'trigger' : 'action'); + return glyph && matchesKnownOperation(operationKey(apiId, id), type, kind, isTrigger) ? ( + + ) : undefined; +};