diff --git a/src/constants/UserMessages.ts b/src/constants/UserMessages.ts index 9858475..d6a5707 100644 --- a/src/constants/UserMessages.ts +++ b/src/constants/UserMessages.ts @@ -473,10 +473,6 @@ export class UserPrompts { return format('Failed to open conversion: {0}', errorMsg); } - static failedToExecute(errorMsg: string): string { - return format('Failed to execute: {0}', errorMsg); - } - static readonly NO_PROJECT_FOLDER = 'No project folder found.'; static readonly NO_CODE_WORKSPACE_FILE = 'No .code-workspace file found. Run Execute first to generate the project.'; diff --git a/src/copilot/MigrationLMTools.ts b/src/copilot/MigrationLMTools.ts index 4a86034..048cfe8 100644 --- a/src/copilot/MigrationLMTools.ts +++ b/src/copilot/MigrationLMTools.ts @@ -4897,8 +4897,17 @@ class ConversionStoreTaskOutputTool implements vscode.LanguageModelTool t.id === taskId); const actualStatus = updatedTask?.status || 'completed'; + // Finalize once the last required task is stored, so the flow shows as converted + // ("Open in VS Code" enables) even when tasks are executed one at a time and the + // agent never calls migration_conversion_finalize. + let flowFinalized = false; + if (taskPlan2 && conversionService.areRequiredTasksComplete(flowId)) { + await completeFlowConversion(flowId, taskPlan2, logger); + flowFinalized = true; + } + logger.debug( - `[LMTool] migration_conversion_storeTaskOutput: stored output for task "${taskId}" in flow "${flowId}" (status: ${actualStatus})` + `[LMTool] migration_conversion_storeTaskOutput: stored output for task "${taskId}" in flow "${flowId}" (status: ${actualStatus}${flowFinalized ? ', flow finalized' : ''})` ); TelemetryService.getInstance().logStep('conversion.task.completed', { flowId, @@ -4915,7 +4924,11 @@ class ConversionStoreTaskOutputTool implements vscode.LanguageModelTool { + // Deterministically stamp MigrationMetadata into every generated workflow.json. + // Machine-generated data — no agent involvement, no rejection/retry loop. + const stampedCount = await applyWorkflowMigrationMetadata(plan, logger); + + // Mark the flow as completed + const flow = ConversionService.getInstance() + .getFlows() + .find((f) => f.id === flowId); + if (flow) { + flow.status = 'completed'; + } + + // Mark flow as fully converted in DiscoveryCacheService + try { + const { DiscoveryCacheService } = await import('../stages/discovery/DiscoveryCacheService'); + await DiscoveryCacheService.getInstance().markFlowConverted(flowId); + } catch { + // Non-critical + } + + // Clear executing flag and refresh flow group selector + try { + const { SourceFlowVisualizer } = await import('../views/discovery/SourceFlowVisualizer'); + SourceFlowVisualizer.executingGroupIds.delete(flowId); + if (SourceFlowVisualizer.currentPanel) { + SourceFlowVisualizer.showFlowGroupSelector( + SourceFlowVisualizer.currentPanel.extensionUri + ); + } + } catch { + // Non-critical + } + + return stampedCount; +} + class ConversionFinalizeTool implements vscode.LanguageModelTool { async invoke( options: vscode.LanguageModelToolInvocationOptions, @@ -5110,38 +5169,7 @@ class ConversionFinalizeTool implements vscode.LanguageModelTool f.id === flowId); - if (flow) { - flow.status = 'completed'; - } - - // Mark flow as fully converted in DiscoveryCacheService - try { - const { DiscoveryCacheService } = - await import('../stages/discovery/DiscoveryCacheService'); - await DiscoveryCacheService.getInstance().markFlowConverted(flowId); - } catch { - // Non-critical - } - - // Clear executing flag and refresh flow group selector - try { - const { SourceFlowVisualizer } = - await import('../views/discovery/SourceFlowVisualizer'); - SourceFlowVisualizer.executingGroupIds.delete(flowId); - if (SourceFlowVisualizer.currentPanel) { - SourceFlowVisualizer.showFlowGroupSelector( - SourceFlowVisualizer.currentPanel.extensionUri - ); - } - } catch { - // Non-critical - } + const stampedCount = await completeFlowConversion(flowId, plan, logger); // Open conversion webview void vscode.commands.executeCommand('logicAppsMigrationAgent.openConversionView'); diff --git a/src/stages/conversion/ConversionService.ts b/src/stages/conversion/ConversionService.ts index 5f2c53b..68a4b7c 100644 --- a/src/stages/conversion/ConversionService.ts +++ b/src/stages/conversion/ConversionService.ts @@ -325,6 +325,20 @@ export class ConversionService implements vscode.Disposable { return this.state?.taskPlans[flowId]; } + /** + * Whether every required (non-optional) task in the flow's plan is completed + * or skipped, so the flow's conversion can be finalized. + */ + public areRequiredTasksComplete(flowId: string): boolean { + const tasks = this.getTaskPlan(flowId)?.tasks ?? []; + return ( + tasks.length > 0 && + tasks.every( + (task) => task.optional || task.status === 'completed' || task.status === 'skipped' + ) + ); + } + /** * Set Execute All orchestration mode for a flow. */ diff --git a/src/test/unit/conversion-step-button.test.ts b/src/test/unit/conversion-step-button.test.ts new file mode 100644 index 0000000..8002117 --- /dev/null +++ b/src/test/unit/conversion-step-button.test.ts @@ -0,0 +1,98 @@ +import * as assert from 'assert/strict'; +import { + ConversionStepState, + renderConversionStepButton, +} from '../../views/discovery/ConversionStepButton'; + +const planned: ConversionStepState = { + flowId: 'order-flow', + isPlanned: true, + isTasksCreated: false, + isConverted: false, + isCreatingTasks: false, + isExecuting: false, + isBlockedByOtherFlow: false, +}; + +function step(overrides: Partial): { + label: string; + action?: string; + disabled: boolean; +} { + const html = renderConversionStepButton({ ...planned, ...overrides }); + return { + label: /([^<]*)<\/strong>/.exec(html)?.[1] ?? '', + action: /onclick="event\.stopPropagation\(\); (\w+)\('order-flow'\)"/.exec(html)?.[1], + disabled: /\sdisabled[\s>]/.test(html), + }; +} + +describe('Home Execute step', () => { + it('is named Execute and generates the conversion tasks once the flow is planned', () => { + assert.deepEqual(step({ isPlanned: false }), { + label: 'Execute', + action: undefined, + disabled: true, + }); + assert.deepEqual(step({}), { label: 'Execute', action: 'convertFlow', disabled: false }); + assert.deepEqual(step({ isCreatingTasks: true }), { + label: 'Executing...', + action: undefined, + disabled: true, + }); + }); + + it('opens the generated tasks so they are executed from the task list', () => { + assert.deepEqual(step({ isTasksCreated: true }), { + label: 'Execute', + action: 'viewConversion', + disabled: false, + }); + assert.deepEqual(step({ isTasksCreated: true, isExecuting: true }), { + label: 'Executing...', + action: undefined, + disabled: true, + }); + assert.deepEqual(step({ isTasksCreated: true, isConverted: true }), { + label: '✓ Executed', + action: 'viewConversion', + disabled: false, + }); + }); + + it('only blocks starting a flow while another flow is busy', () => { + assert.deepEqual(step({ isBlockedByOtherFlow: true }), { + label: 'Execute', + action: undefined, + disabled: true, + }); + assert.deepEqual(step({ isBlockedByOtherFlow: true, isTasksCreated: true }), { + label: 'Execute', + action: 'viewConversion', + disabled: false, + }); + }); + + it('never shows Create in any state', () => { + const flags = [ + 'isPlanned', + 'isTasksCreated', + 'isConverted', + 'isCreatingTasks', + 'isExecuting', + 'isBlockedByOtherFlow', + ] as const; + for (let mask = 0; mask < 2 ** flags.length; mask++) { + const overrides: Partial> = {}; + flags.forEach((flag, i) => { + overrides[flag] = Math.floor(mask / 2 ** i) % 2 === 1; + }); + const html = renderConversionStepButton({ ...planned, ...overrides }); + assert.doesNotMatch(html, /creat/i, JSON.stringify(overrides)); + assert.ok( + ['Execute', 'Executing...', '✓ Executed'].includes(step(overrides).label), + JSON.stringify(overrides) + ); + } + }); +}); diff --git a/src/test/unit/conversion.test.ts b/src/test/unit/conversion.test.ts index 1360264..bd92268 100644 --- a/src/test/unit/conversion.test.ts +++ b/src/test/unit/conversion.test.ts @@ -115,6 +115,27 @@ describe('BizTalk Conversion stage', () => { assert.deepEqual(completedFlows, [flow.id]); }); + it('is ready to finalize once every required task is done, even with optional tasks pending', async () => { + const flow = await prepareConversion(); + const conversion = ConversionService.getInstance(); + assert.equal(conversion.areRequiredTasksComplete(flow.id), false); + await conversion.storeTaskOutput(flow.id, 'convert-schemas-and-map', { + completedAt: generatedAt, + summary: 'convert-schemas-and-map completed.', + }); + await conversion.updateTask(flow.id, 'generate-workflow', { status: 'failed' }); + assert.equal(conversion.areRequiredTasksComplete(flow.id), false); + for (const taskId of ['generate-workflow', 'test-workflows']) { + await conversion.storeTaskOutput(flow.id, taskId, { + completedAt: generatedAt, + summary: `${taskId} completed.`, + }); + } + assert.equal(conversion.getTaskPlan(flow.id)?.tasks[3].status, 'pending'); + assert.equal(conversion.areRequiredTasksComplete(flow.id), true); + assert.equal(conversion.areRequiredTasksComplete('flow-without-tasks'), false); + }); + it('stops interrupted execution without losing previously completed tasks', async () => { const flow = await prepareConversion(); const conversion = ConversionService.getInstance(); diff --git a/src/views/discovery/ConversionStepButton.ts b/src/views/discovery/ConversionStepButton.ts new file mode 100644 index 0000000..82e7a47 --- /dev/null +++ b/src/views/discovery/ConversionStepButton.ts @@ -0,0 +1,79 @@ +/** + * Execute step on the Home flow cards. + * + * A single Execute step covers conversion: on a planned flow it generates the + * conversion tasks and opens the task list, where each task (or Execute All) + * is executed. + * + * @module views/discovery/ConversionStepButton + */ + +export interface ConversionStepState { + readonly flowId: string; + readonly isPlanned: boolean; + readonly isTasksCreated: boolean; + readonly isConverted: boolean; + readonly isCreatingTasks: boolean; + readonly isExecuting: boolean; + readonly isBlockedByOtherFlow: boolean; +} + +function stepLabel(text: string): string { + return `${text}Conversion Tasks`; +} + +function disabledStep(text: string, title?: string): string { + const titleAttr = title ? ` title="${title}"` : ''; + return ``; +} + +function actionStep( + text: string, + style: 'btn-primary' | 'btn-done', + action: 'convertFlow' | 'viewConversion', + flowId: string, + title: string +): string { + return ``; +} + +/** + * Render the Execute step. It keeps the Execute name in every state, like + * Analyse → ✓ Analysed and Plan → ✓ Planned. + */ +export function renderConversionStepButton(state: ConversionStepState): string { + if (!state.isPlanned) { + return disabledStep('Execute', 'Plan first'); + } + if (state.isCreatingTasks || state.isExecuting) { + return disabledStep('Executing...'); + } + if (state.isConverted) { + return actionStep( + '✓ Executed', + 'btn-done', + 'viewConversion', + state.flowId, + 'View conversion tasks' + ); + } + if (state.isTasksCreated) { + return actionStep( + 'Execute', + 'btn-primary', + 'viewConversion', + state.flowId, + 'Open the conversion tasks to execute them' + ); + } + if (state.isBlockedByOtherFlow) { + return disabledStep('Execute', 'Another flow is in progress'); + } + return actionStep( + 'Execute', + 'btn-primary', + 'convertFlow', + state.flowId, + 'Generate the conversion tasks, then execute them from the task list' + ); +} diff --git a/src/views/discovery/SourceFlowVisualizer.ts b/src/views/discovery/SourceFlowVisualizer.ts index 2dcad80..7a750fd 100644 --- a/src/views/discovery/SourceFlowVisualizer.ts +++ b/src/views/discovery/SourceFlowVisualizer.ts @@ -23,6 +23,7 @@ import { GeneratedFlowResult, FlowGroupsResult } from '../../services/LLMFlowGen import { UserPrompts } from '../../constants/UserMessages'; import { ChatPrompts } from '../../constants/ChatPrompts'; import { ConfigurationService } from '../../services/ConfigurationService'; +import { renderConversionStepButton } from './ConversionStepButton'; // ============================================================================= // Source Flow Visualizer @@ -295,39 +296,16 @@ export class SourceFlowVisualizer implements vscode.Disposable { planBtn = ``; } - // ── Create button ── - let createBtn: string; - if (!isPlanned) { - createBtn = - ''; - } else if (isConverting) { - createBtn = - ''; - } else if (isTasksCreated) { - createBtn = ``; - } else if (isBlockedByOtherFlow) { - createBtn = - ''; - } else { - createBtn = ``; - } - - // ── Execute button ── - let executeBtn: string; - if (!isTasksCreated) { - executeBtn = - ''; - } else if (isExecuting) { - executeBtn = - ''; - } else if (isConverted) { - executeBtn = ``; - } else if (isBlockedByOtherFlow) { - executeBtn = - ''; - } else { - executeBtn = ``; - } + // ── Execute step: generate the conversion tasks, then open them to execute ── + const conversionBtn = renderConversionStepButton({ + flowId: g.id, + isPlanned, + isTasksCreated, + isConverted, + isCreatingTasks: isConverting, + isExecuting, + isBlockedByOtherFlow, + }); // ── Open in VS Code button ── let openBtn: string; @@ -369,7 +347,7 @@ export class SourceFlowVisualizer implements vscode.Disposable { ${escapeHtml(g.category)}
- ${analyseBtn}${stepArrow}${planBtn}${stepArrow}${createBtn}${stepArrow}${executeBtn}${stepArrow}${openBtn} + ${analyseBtn}${stepArrow}${planBtn}${stepArrow}${conversionBtn}${stepArrow}${openBtn}
`; }) @@ -664,9 +642,6 @@ export class SourceFlowVisualizer implements vscode.Disposable { function viewConversion(flowId) { vscode.postMessage({ command: 'viewConversionFromSelector', data: flowId }); } - function executeFlow(flowId) { - vscode.postMessage({ command: 'executeFlowFromSelector', data: flowId }); - } function stopFlow(flowId) { vscode.postMessage({ command: 'stopFlowFromSelector', data: flowId }); } @@ -1385,11 +1360,12 @@ export class SourceFlowVisualizer implements vscode.Disposable { } case 'convertFlowFromSelector': { - // User clicked Convert button — mark as converting and start agent chat + // User clicked Execute on a flow without tasks — generate them; the task + // list opens once the agent stores them const flowId = message.data as string; this.logger.debug(`[FlowViz] User requested conversion for flow: ${flowId}`); - // Mark as converting and refresh UI to show Converting... state + // Mark as converting and refresh UI to show the Executing... state SourceFlowVisualizer.convertingGroupIds.add(flowId); SourceFlowVisualizer.showFlowGroupSelector(this.extensionUri); @@ -1417,7 +1393,7 @@ export class SourceFlowVisualizer implements vscode.Disposable { } case 'viewConversionFromSelector': { - // User clicked "✓ Converted" — open Conversion webview for this flow + // User clicked Execute / ✓ Executed on a flow with tasks — open the task list const flowId = message.data as string; this.logger.debug(`[FlowViz] User viewing conversion for flow: ${flowId}`); void (async () => { @@ -1443,48 +1419,6 @@ export class SourceFlowVisualizer implements vscode.Disposable { break; } - case 'executeFlowFromSelector': { - // User clicked Execute button — mark as executing, open Conversion webview, trigger Execute All - const flowId = message.data as string; - this.logger.debug(`[FlowViz] User requested execute all for flow: ${flowId}`); - - // Mark as executing and refresh UI - SourceFlowVisualizer.executingGroupIds.add(flowId); - SourceFlowVisualizer.showFlowGroupSelector(this.extensionUri); - - void (async () => { - try { - // Ensure conversion service is initialized and has the flow - const { ConversionService } = await import('../../stages/conversion'); - const conversionService = ConversionService.getInstance(); - await conversionService.initialize(); - if (conversionService.getFlows().length === 0) { - conversionService.buildFlowsFromPlanning(); - } - await conversionService.selectFlow(flowId); - - // Open conversion webview - const { ConversionWebviewPanel } = await import('../conversion'); - ConversionWebviewPanel.createOrShow(this.extensionUri); - - // Trigger Execute All after a short delay to let the webview render - setTimeout(() => { - void vscode.commands.executeCommand( - 'logicAppsMigrationAgent.executeAllConversionTasks', - flowId - ); - }, 500); - } catch (err) { - vscode.window.showErrorMessage( - UserPrompts.failedToExecute( - err instanceof Error ? err.message : String(err) - ) - ); - } - })(); - break; - } - case 'openProjectFromSelector': { // User clicked Open in VS Code — open the generated project workspace const flowId = message.data as string;