diff --git a/docs/ScriptEditor.md b/docs/ScriptEditor.md index 8c382e090..b1a780d86 100644 --- a/docs/ScriptEditor.md +++ b/docs/ScriptEditor.md @@ -190,8 +190,16 @@ the runtime would refuse rejects the deploy with `ScriptCompileFailed`, naming t script, the seam it was compiled for and the entities using it — so an error the editor showed can no longer be deployed silently. Two differences from the editor to know: the gate compiles each script **as the seam that uses it** (a predicate -must return `bool`; the editor analyses every script as a VirtualTag body), and it -only checks scripts something enabled uses. See `docs/VirtualTags.md` +must return `bool`), and it only checks scripts something enabled uses. The editor +matches the gate's seam since #1025: the analysis endpoints take an optional `mode` +(`value` default | `alarmPredicate`), the editor wraps the source as +`bool Run(ScriptGlobals)` in predicate mode, and the ScriptEdit +page has an **Analyse as** selector that defaults to *predicate* when scripted alarms +are the script's only users (a script also used as a VirtualTag/Calculation defaults to +value; pick whichever seam you are authoring for). The per-equipment VirtualTag and +Calculation editors are always value mode. Known remaining gap: a body that lacks a +`return` on some path (CS0161) is not flagged while you type (a deliberate +no-phantom-marker rule) but is refused at deploy. See `docs/VirtualTags.md` §"Deploy-time script compile gate" for modes, caching and the upgrade note. ### Runtime safety (what happens after publish) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ScriptEdit.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ScriptEdit.razor index 815db2549..fe555eac0 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ScriptEdit.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ScriptEdit.razor @@ -75,8 +75,19 @@ else

Source

+ @* #1025: the editor analyses the script as the seam that runs it — the deploy gate compiles a scripted-alarm + predicate as `bool Run(AlarmPredicateContext)`, a VirtualTag/Calculation script as a value script. + Defaults from the script's current users; the author can switch for a not-yet-used script. *@ +
+ + +
+ AriaLabel="Script source code" ReadOnly="@_busy" Mode="@_mode" MarkersChanged="report => OnMarkersChanged(report, presentation)" />
SHA-256 hash is computed automatically on save.
@@ -114,6 +125,7 @@ else private string _deleteMessage = ""; private DeleteIntent? _deleteIntent; private MonacoEditor? _editor; + private string _mode = ScriptAnalysisModes.Value; private ScriptProblemReport _markers = ScriptProblemReport.Empty; private sealed record DeleteIntent(string Id, byte[] RowVersion); @@ -126,6 +138,10 @@ else { if (Current(generation) && !_busy && ReferenceEquals(form, _form)) form.SourceCode = value; } + private void ChangeMode(string? value, long generation) + { + if (Current(generation)) _mode = ScriptAnalysisModes.IsPredicate(value) ? ScriptAnalysisModes.AlarmPredicate : ScriptAnalysisModes.Value; + } private void OnMarkersChanged(ScriptProblemReport report, long generation) { if (Current(generation)) _markers = report; @@ -143,7 +159,7 @@ else ++_confirmationEpoch; _loaded = _busy = _confirmDeleteVisible = false; _existing = null; _editor = null; _deleteIntent = null; - _form = new(); _markers = ScriptProblemReport.Empty; _error = _loadError = null; + _form = new(); _mode = ScriptAnalysisModes.Value; _markers = ScriptProblemReport.Empty; _error = _loadError = null; try { if (!string.IsNullOrEmpty(id)) @@ -153,6 +169,12 @@ else var existing = await db.Scripts.AsNoTracking().FirstOrDefaultAsync(s => s.ScriptId == id); if (!Current(generation)) return; _existing = existing; + if (existing is not null) + { + var usage = await ZB.MOM.WW.OtOpcUa.AdminUI.Uns.ScriptUsage.ClassifyAsync(db, id); + if (!Current(generation)) return; + _mode = usage.DefaultMode; + } if (existing is not null) _form = new FormModel { ScriptId = existing.ScriptId, Name = existing.Name, SourceCode = existing.SourceCode, RowVersion = existing.RowVersion.ToArray() }; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/MonacoEditor.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/MonacoEditor.razor index dc917ca90..f6edeedb9 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/MonacoEditor.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/MonacoEditor.razor @@ -53,6 +53,13 @@ /// [Parameter] public string? EquipmentId { get; set; } + /// + /// Which seam the script is analysed as (; lmxopcua#1025): null/value for a + /// VirtualTag / Calculation script, alarmPredicate for a scripted-alarm predicate (must return bool). + /// Changing it re-analyses the live editor. + /// + [Parameter] public string? Mode { get; set; } + /// /// Fires whenever Monaco's diagnostic marker set updates (after the 500 ms debounce, and only for the response /// to the CURRENT text — superseded responses are dropped in the JS). Feeds ScriptProblemsList; the @@ -67,6 +74,7 @@ private readonly string _id = Guid.NewGuid().ToString("N"); private string _lastSentValue = ""; private string _lastSentAriaLabel = ""; + private string? _lastSentMode; private bool _lastSentReadOnly; private string AccessibleLabel => string.IsNullOrWhiteSpace(AriaLabel) ? "Code editor" : AriaLabel; private bool _disposed; @@ -86,6 +94,7 @@ _lastSentValue = Value ?? ""; var createdLabel = AccessibleLabel; var createdReadOnly = ReadOnly; + var createdMode = Mode; _initializing = true; try { @@ -100,6 +109,7 @@ language = Language, readOnly = createdReadOnly, equipmentId = EquipmentId, + mode = Mode, maxSyncBytes = ScriptEditorLimits.MaxEditorSyncBytes, reportMarkers = MarkersChanged.HasDelegate, maxReportedMarkers = ScriptEditorLimits.MaxReportedMarkers, @@ -110,6 +120,7 @@ _initialized = true; _lastSentAriaLabel = createdLabel; _lastSentReadOnly = createdReadOnly; + _lastSentMode = createdMode; } catch (InvalidOperationException) { @@ -137,6 +148,11 @@ _lastSentReadOnly = ReadOnly; await SafeInvokeAsync("MonacoBlazor.setEditorOption", "set editor read-only state", _id, "readOnly", _lastSentReadOnly); } + if (!_disposed && _initialized && !string.Equals(Mode, _lastSentMode, StringComparison.Ordinal)) + { + _lastSentMode = Mode; + await SafeInvokeAsync("MonacoBlazor.setMode", "set script analysis mode", _id, _lastSentMode); + } if (!_disposed && _initialized && AccessibleLabel != _lastSentAriaLabel) { _lastSentAriaLabel = AccessibleLabel; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisContracts.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisContracts.cs index 1227957a8..ccfc3d445 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisContracts.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisContracts.cs @@ -1,22 +1,43 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis; +/// +/// Which seam the editor analyses a script as (lmxopcua#1025). The deploy gate compiles each script as the seam that +/// uses it, so the editor has to wrap the source the same way: a value script is +/// object Run(ScriptGlobals<VirtualTagContext>) (VirtualTag and Calculation share it); a scripted-alarm +/// predicate is bool Run(ScriptGlobals<AlarmPredicateContext>). Carried as a string on the wire; null, +/// blank or anything unrecognised means . +/// +public static class ScriptAnalysisModes +{ + /// A VirtualTag / Calculation value script (the default). + public const string Value = "value"; + + /// A scripted-alarm predicate: must return bool. + public const string AlarmPredicate = "alarmPredicate"; + + /// True when selects the predicate shape. + /// The wire value. + /// Whether it names . + public static bool IsPredicate(string? mode) => string.Equals(mode, AlarmPredicate, StringComparison.OrdinalIgnoreCase); +} + // EquipmentId (optional) carries the owning-equipment context the {{equip}}/ completion + // diagnostic need to resolve reference effective names. Null on the shared ScriptEdit page (no single // equipment) — the equip-ref features are then inert, matching the deploy gate (which only resolves per -// owning equipment). -public record DiagnoseRequest(string Code, string? EquipmentId = null); +// owning equipment). Mode (optional) selects the seam the script is analysed as — see ScriptAnalysisModes. +public record DiagnoseRequest(string Code, string? EquipmentId = null, string? Mode = null); public record DiagnoseResponse(IReadOnlyList Markers); public record DiagnosticMarker(int Severity, int StartLineNumber, int StartColumn, int EndLineNumber, int EndColumn, string Message, string Code); -public record CompletionsRequest(string CodeText, int Line, int Column, string? EquipmentId = null); +public record CompletionsRequest(string CodeText, int Line, int Column, string? EquipmentId = null, string? Mode = null); public record CompletionsResponse(IReadOnlyList Items); public record CompletionItem(string Label, string InsertText, string Detail, string Kind, int InsertTextRules = 0); -public record HoverRequest(string CodeText, int Line, int Column, string? EquipmentId = null); +public record HoverRequest(string CodeText, int Line, int Column, string? EquipmentId = null, string? Mode = null); public record HoverResponse(string? Markdown); -public record SignatureHelpRequest(string CodeText, int Line, int Column); +public record SignatureHelpRequest(string CodeText, int Line, int Column, string? Mode = null); public record SignatureHelpResponse(string? Label, IReadOnlyList? Parameters, int ActiveParameter); public record SignatureHelpParameter(string Label, string? Documentation); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs index c0402fb88..9831c791f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs @@ -3,6 +3,7 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Extensions.Logging; using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms; using ZB.MOM.WW.OtOpcUa.Core.Scripting; using ZB.MOM.WW.OtOpcUa.Core.VirtualTags; @@ -27,8 +28,6 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis; /// public sealed class ScriptAnalysisService { - private static readonly SandboxConfig Sandbox = ScriptSandbox.Build(typeof(VirtualTagContext)); - private static readonly string Preamble = BuildPreamble(); private static readonly CSharpCompilationOptions CompileOptions = new( OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release, allowUnsafe: false, warningLevel: 4, nullableContextOptions: NullableContextOptions.Enable); @@ -44,52 +43,66 @@ public sealed class ScriptAnalysisService _logger = logger; } - // Mirrors ScriptEvaluator's wrapper EXACTLY (usings from the sandbox + the - // Run(ScriptGlobals) shape), except the analysis return type is - // `object` so a shared script stays valid regardless of any virtual tag's DataType. - private static string BuildPreamble() - { - var usings = string.Join("\n", Sandbox.Imports.Select(i => $"using {i};")); - var globalsType = $"global::{typeof(ScriptGlobals<>).Namespace}.ScriptGlobals"; - return usings + "\n\n" - + "namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Compiled;\n" - + "public static class CompiledScript\n{\n" - + $" public static object Run({globalsType} globals)\n {{\n" - + " var ctx = globals.ctx;\n#line 1\n"; - } - - private static SyntaxTree WrapAndParse(string userSource, CancellationToken ct) - => CSharpSyntaxTree.ParseText(Preamble + (userSource ?? "") + "\n }\n}\n", cancellationToken: ct); - /// - /// The process-wide compilation every analysis derives from. Its sandbox reference set is bound ONCE - /// (forced here by resolving System.Object); keeps - /// that binding, so a request only re-binds the user's tree instead of the whole reference set. It is - /// immutable, so sharing it across circuits and requests is thread-safe. + /// One analysis shape (lmxopcua#1025): the sandbox + wrapper the deploy gate compiles a seam's script with, and + /// the process-wide every analysis of that seam derives from. Its sandbox reference + /// set is bound ONCE (forced by resolving System.Object); + /// keeps that binding, so a request only re-binds the user's tree. Immutable, so shared across circuits/requests. /// - internal static readonly CSharpCompilation BaseCompilation = CreateBaseCompilation(); - - private static CSharpCompilation CreateBaseCompilation() + private sealed class Shape { - var compilation = CSharpCompilation.Create( - "ScriptAnalysis", new[] { WrapAndParse("", CancellationToken.None) }, Sandbox.References, CompileOptions); - _ = compilation.GetSpecialType(SpecialType.System_Object); - return compilation; + public Shape(Type contextType, string returnType) + { + Sandbox = ScriptSandbox.Build(contextType); + // Mirrors ScriptEvaluator's wrapper EXACTLY (usings from the sandbox + the Run(ScriptGlobals) + // shape). The value shape's return type is `object` so a shared script stays valid regardless of any + // virtual tag's DataType; the predicate shape is `bool`, exactly as the alarm engine compiles it. + var usings = string.Join("\n", Sandbox.Imports.Select(i => $"using {i};")); + var globalsType = $"global::{typeof(ScriptGlobals<>).Namespace}.ScriptGlobals"; + Preamble = usings + "\n\n" + + "namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Compiled;\n" + + "public static class CompiledScript\n{\n" + + $" public static {returnType} Run({globalsType} globals)\n {{\n" + + " var ctx = globals.ctx;\n#line 1\n"; + var compilation = CSharpCompilation.Create( + "ScriptAnalysis", new[] { Parse("", CancellationToken.None) }, Sandbox.References, CompileOptions); + _ = compilation.GetSpecialType(SpecialType.System_Object); + BaseCompilation = compilation; + } + + public SandboxConfig Sandbox { get; } + public string Preamble { get; } + public CSharpCompilation BaseCompilation { get; } + + public SyntaxTree Parse(string userSource, CancellationToken ct) + => CSharpSyntaxTree.ParseText(Preamble + (userSource ?? "") + "\n }\n}\n", cancellationToken: ct); } + private static readonly Shape ValueShape = new(typeof(VirtualTagContext), "object"); + private static readonly Shape PredicateShape = new(typeof(AlarmPredicateContext), "bool"); + + private static Shape ShapeFor(string? mode) => ScriptAnalysisModes.IsPredicate(mode) ? PredicateShape : ValueShape; + + /// The process-wide value-shape compilation (test seam; the predicate shape has its own). + internal static CSharpCompilation BaseCompilation => ValueShape.BaseCompilation; + // userSource is appended after Preamble, then the method/class are closed. Every analysis derives straight // from the shared BaseCompilation: the analysis endpoints are minimal-API handlers, so a scoped service lives // for one HTTP request and a per-instance lineage would never be more than one step long. private static (SyntaxTree Tree, CSharpCompilation Compilation, SemanticModel Model, int PreambleLength) Analyze( - string userSource, CancellationToken ct) + string userSource, string? mode, CancellationToken ct) { - var tree = WrapAndParse(userSource, ct); - var compilation = BaseCompilation.ReplaceSyntaxTree(BaseCompilation.SyntaxTrees[0], tree); - return (tree, compilation, compilation.GetSemanticModel(tree), Preamble.Length); + var shape = ShapeFor(mode); + var tree = shape.Parse(userSource, ct); + var compilation = shape.BaseCompilation.ReplaceSyntaxTree(shape.BaseCompilation.SyntaxTrees[0], tree); + return (tree, compilation, compilation.GetSemanticModel(tree), shape.Preamble.Length); } /// Test seam: the compilation one analysis of runs against. - internal CSharpCompilation CompilationFor(string userSource) => Analyze(Normalize(userSource), CancellationToken.None).Compilation; + /// The script source. + /// The analysis mode (); null = value. + internal CSharpCompilation CompilationFor(string userSource, string? mode = null) + => Analyze(Normalize(userSource), mode, CancellationToken.None).Compilation; // editor (line,col) in USER-source coords -> physical offset in the wrapped document private static int OffsetInWrapped(string userSource, int line, int column, int preambleLength) @@ -121,7 +134,7 @@ public sealed class ScriptAnalysisService { ct.ThrowIfCancellationRequested(); var code = Normalize(req.Code); - var (tree, compilation, _, preambleLength) = Analyze(code, ct); + var (tree, compilation, _, preambleLength) = Analyze(code, req.Mode, ct); var markers = new List(); // (1) Roslyn — surface ONLY compile errors, the same severity that actually blocks a @@ -152,7 +165,9 @@ public sealed class ScriptAnalysisService // (4) ctx.SetVirtualTag(...) is inert at runtime — a WARNING (severity 4), never an error: publish // accepts the script, so the editor must too; the marker just puts the hover's caveat in the Problems list. foreach (var inv in SetVirtualTagCalls(tree.GetRoot(ct), preambleLength)) - markers.Add(ToMarker(tree.GetMappedLineSpan(inv.Span), 4, SetVirtualTagInertMessage, "OTSCRIPT_SETVTAG_INERT")); + markers.Add(ToMarker(tree.GetMappedLineSpan(inv.Span), 4, + ScriptAnalysisModes.IsPredicate(req.Mode) ? SetVirtualTagPredicateMessage : SetVirtualTagInertMessage, + "OTSCRIPT_SETVTAG_INERT")); return new DiagnoseResponse(Bound(markers)); } @@ -228,6 +243,10 @@ public sealed class ScriptAnalysisService : m with { Message = ScriptProblems.Truncate(m.Message, ScriptEditorLimits.MaxDiagnosticMessageChars) }) .ToList(); + private const string SetVirtualTagPredicateMessage = + "ctx.SetVirtualTag(...) throws in a scripted-alarm predicate: predicates must be side-effect free. The script " + + "compiles and publishes, but every evaluation fails — move the write into a virtual tag the predicate reads."; + private const string SetVirtualTagInertMessage = "ctx.SetVirtualTag(...) has no effect at runtime: cross-tag writes are dropped in single-tag mode (the " + "cascade engine is not wired into the host). The script compiles and publishes, but this write will not " + @@ -282,7 +301,7 @@ public sealed class ScriptAnalysisService { ct.ThrowIfCancellationRequested(); var code = Normalize(req.CodeText); - var (tree, _, model, preambleLength) = Analyze(code, ct); + var (tree, _, model, preambleLength) = Analyze(code, req.Mode, ct); var position = OffsetInWrapped(code, req.Line, req.Column, preambleLength); var root = await tree.GetRootAsync(ct); // position is the offset just AFTER the caret; -1 finds the token the caret sits at/just-after (e.g. the dot in "ctx."). @@ -402,7 +421,7 @@ public sealed class ScriptAnalysisService { ct.ThrowIfCancellationRequested(); var code = Normalize(req.CodeText); - var (tree, _, model, preambleLength) = Analyze(code, ct); + var (tree, _, model, preambleLength) = Analyze(code, req.Mode, ct); var position = OffsetInWrapped(code, req.Line, req.Column, preambleLength); var token = tree.GetRoot(ct).FindToken(Math.Max(0, position - 1)); @@ -504,7 +523,7 @@ public sealed class ScriptAnalysisService { ct.ThrowIfCancellationRequested(); var code = Normalize(req.CodeText); - var (tree, _, model, preambleLength) = Analyze(code, ct); + var (tree, _, model, preambleLength) = Analyze(code, req.Mode, ct); var position = OffsetInWrapped(code, req.Line, req.Column, preambleLength); var token = tree.GetRoot(ct).FindToken(Math.Max(0, position - 1)); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/ScriptUsage.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/ScriptUsage.cs index a1d1709cb..423e7c2bb 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/ScriptUsage.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/ScriptUsage.cs @@ -21,6 +21,42 @@ public static class ScriptUsage /// How many using rows are named in the refusal before it summarises the rest. private const int NamedLimit = 5; + /// Which seams use a script. + /// An (any) VirtualTag or Calculation tag runs it as a value script. + /// An (any) scripted alarm runs it as its predicate. + public readonly record struct SeamUsage(bool UsedAsValue, bool UsedAsPredicate) + { + /// + /// The editor analysis mode (ScriptAnalysisModes) a script should open in (lmxopcua#1025): the predicate + /// shape only when scripted alarms are its sole users — a script also run as a value script stays a value + /// script (the author can switch), and an unused script is a value script. + /// + public string DefaultMode => + UsedAsPredicate && !UsedAsValue ? ScriptAnalysis.ScriptAnalysisModes.AlarmPredicate : ScriptAnalysis.ScriptAnalysisModes.Value; + } + + /// Classifies which seams use (same rows, same Calculation parser as the delete check). + /// The config context. + /// The script. + /// Cancellation token. + /// Where the script is used. + public static async Task ClassifyAsync(OtOpcUaConfigDbContext db, string scriptId, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(db); + ArgumentException.ThrowIfNullOrEmpty(scriptId); + var predicate = await db.ScriptedAlarms.AsNoTracking().AnyAsync(a => a.PredicateScriptId == scriptId, ct); + var value = await db.VirtualTags.AsNoTracking().AnyAsync(v => v.ScriptId == scriptId, ct); + if (!value) + { + var calcCandidates = await db.Tags.AsNoTracking() + .Where(t => t.TagConfig.Contains(scriptId)) + .Select(t => t.TagConfig) + .ToListAsync(ct); + value = calcCandidates.Any(c => string.Equals(DraftValidator.ParseScriptId(c), scriptId, StringComparison.Ordinal)); + } + return new SeamUsage(value, predicate); + } + /// /// Describes every row that references , or returns when /// nothing does and the script may be deleted. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/wwwroot/js/monaco-init.js b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/wwwroot/js/monaco-init.js index 3d35a9ca2..9545b266f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/wwwroot/js/monaco-init.js +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/wwwroot/js/monaco-init.js @@ -52,6 +52,9 @@ // registered csharp providers (which only receive the model) can thread it into the {{equip}}/ // completion + diagnostics. Null on the shared ScriptEdit page (equip-ref features inert there). function equipmentIdOf(model) { return (model && model.__otEquipmentId) || null; } + // The analysis mode (#1025): "alarmPredicate" analyses the script as a scripted-alarm predicate (bool Run), anything + // else as a value script. Stamped on the model like the equipment id; changeable later via setMode. + function modeOf(model) { return (model && model.__otMode) || null; } function registerCSharpProviders() { monaco.languages.registerCompletionItemProvider("csharp", { @@ -59,7 +62,7 @@ provideCompletionItems: async function (model, position, context, token) { try { const data = await postAnalysis("completions", - { codeText: model.getValue(), line: position.lineNumber, column: position.column, equipmentId: equipmentIdOf(model) }, + { codeText: model.getValue(), line: position.lineNumber, column: position.column, equipmentId: equipmentIdOf(model), mode: modeOf(model) }, token); if (!data) return { suggestions: [] }; const word = model.getWordUntilPosition(position); @@ -97,7 +100,7 @@ provideHover: async function (model, position, token) { try { const data = await postAnalysis("hover", - { codeText: model.getValue(), line: position.lineNumber, column: position.column, equipmentId: equipmentIdOf(model) }, + { codeText: model.getValue(), line: position.lineNumber, column: position.column, equipmentId: equipmentIdOf(model), mode: modeOf(model) }, token); if (!data || !data.markdown) return null; return { contents: [{ value: data.markdown }] }; @@ -119,7 +122,7 @@ provideSignatureHelp: async function (model, position, token) { try { const data = await postAnalysis("signature-help", - { codeText: model.getValue(), line: position.lineNumber, column: position.column }, + { codeText: model.getValue(), line: position.lineNumber, column: position.column, mode: modeOf(model) }, token); if (!data || !data.label) return null; return { @@ -145,7 +148,7 @@ const resp = await fetch("/api/script-analysis/diagnostics", { method: "POST", credentials: "same-origin", signal: signal, headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ code: model.getValue(), equipmentId: equipmentIdOf(model) }) + body: JSON.stringify({ code: model.getValue(), equipmentId: equipmentIdOf(model), mode: modeOf(model) }) }); if (!resp.ok) return []; const data = await resp.json(); @@ -257,7 +260,7 @@ }); // Stamp the owning-equipment id on the model so the global csharp providers can thread it into the // {{equip}}/ completion + diagnostics (null on the shared ScriptEdit page). - try { const m0 = editor.getModel(); if (m0) m0.__otEquipmentId = options.equipmentId || null; } catch (x) {} + try { const m0 = editor.getModel(); if (m0) { m0.__otEquipmentId = options.equipmentId || null; m0.__otMode = options.mode || null; } } catch (x) {} const e = { editor: editor, dotNetRef: dotNetRef, dirty: false, maxSyncBytes: options.maxSyncBytes || 0, reportMarkers: !!options.reportMarkers, @@ -296,6 +299,13 @@ editors[id] = e; if (options.language === "csharp") e.scheduleDiagnostics(); } + // Switches the analysis mode of a live editor (#1025) and re-runs diagnostics so the markers match the new seam. + function setMode(id, mode) { + const e = editors[id]; if (!e) return; + const model = e.editor.getModel(); if (!model) return; + model.__otMode = mode || null; + if (e.scheduleDiagnostics) e.scheduleDiagnostics(); + } function setEditorOption(id, name, value) { const e = editors[id]; if (!e) return; // Note: monaco.editor.setTheme is global — it re-themes every editor on the page, not just this id. @@ -331,5 +341,5 @@ delete editors[id]; } - window.MonacoBlazor = { createEditor, setValue, getValue, setMarkers, setEditorOption, format, revealLine, dispose }; + window.MonacoBlazor = { createEditor, setMode, setValue, getValue, setMarkers, setEditorOption, format, revealLine, dispose }; })(); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/PredicateModeTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/PredicateModeTests.cs new file mode 100644 index 000000000..8ce36d091 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/PredicateModeTests.cs @@ -0,0 +1,117 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis; +using ZB.MOM.WW.OtOpcUa.Core.Scripting; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.ScriptAnalysis; + +/// +/// lmxopcua#1025 — the editor used to analyse EVERY script as a VirtualTag body (object Run(VirtualTagContext)), +/// but the deploy gate compiles a scripted-alarm predicate as bool Run(AlarmPredicateContext). A predicate +/// returning a non-bool was clean in the editor and refused at deploy. The predicate mode closes that: the editor +/// wraps the source exactly as the gate does, so editor accepts ⇔ publish accepts. +/// +public sealed class PredicateModeTests +{ + private static readonly ScriptAnalysisService Svc = new(); + private static readonly RoslynDeployScriptChecker Gate = new(); + + private static IReadOnlyList Diag(string code, string? mode) => + Svc.Diagnose(new DiagnoseRequest(code, Mode: mode)).Markers; + + [Fact] + public void A_non_bool_return_is_clean_as_a_value_script_but_an_error_as_a_predicate() + { + const string code = """return ctx.GetTag("A").Value;"""; + Diag(code, null).ShouldBeEmpty(); + Diag(code, ScriptAnalysisModes.Value).ShouldBeEmpty(); + var predicate = Diag(code, ScriptAnalysisModes.AlarmPredicate); + predicate.ShouldContain(m => m.Severity == 8); + predicate.First(m => m.Severity == 8).StartLineNumber.ShouldBe(1); + } + + [Fact] + public void A_bool_predicate_is_clean_in_both_modes_positive_control() + { + const string code = """return Convert.ToDouble(ctx.GetTag("A").Value ?? 0.0) > 5;"""; + Diag(code, ScriptAnalysisModes.AlarmPredicate).ShouldBeEmpty(); + Diag(code, ScriptAnalysisModes.Value).ShouldBeEmpty(); + } + + [Fact] + public void Predicate_mode_still_runs_the_sandbox_and_dependency_checks() + { + Diag("""var c = new System.Net.Http.HttpClient(); return true;""", ScriptAnalysisModes.AlarmPredicate) + .ShouldContain(m => m.Severity == 8); + Diag("""var p = "A"; return ctx.GetTag(p).Value is not null;""", ScriptAnalysisModes.AlarmPredicate) + .ShouldContain(m => m.Code == "OTSCRIPT_DYNPATH"); + } + + [Fact] + public void An_unknown_mode_falls_back_to_the_value_shape() + => Diag("""return ctx.GetTag("A").Value;""", "nonsense").ShouldBeEmpty(); + + [Theory] + [InlineData("""return ctx.GetTag("A").Value;""")] + [InlineData("""return 1;""")] + [InlineData("""return true;""")] + [InlineData("""return Convert.ToDouble(ctx.GetTag("A").Value ?? 0.0) > 5;""")] + [InlineData("""var x = ; return true;""")] + [InlineData("""return ctx.Nope();""")] + [InlineData("""return;""")] + [InlineData("""return null;""")] + [InlineData("""var f = new System.IO.FileInfo("/x"); return true;""")] + public void Editor_predicate_verdict_matches_the_deploy_gate(string code) + { + var editorRejects = Diag(code, ScriptAnalysisModes.AlarmPredicate).Any(m => m.Severity == 8); + var gateRejects = !Gate.Check([new DeployScriptCheckRequest(ScriptContextKind.AlarmPredicate, code)], TestContext.Current.CancellationToken)[0].Passed; + editorRejects.ShouldBe(gateRejects, $"editor/gate disagree on: {code}"); + } + + [Fact] + public void SetVirtualTag_in_a_predicate_is_flagged_as_throwing_not_inert() + { + var markers = Diag("""ctx.SetVirtualTag("X", 1); return true;""", ScriptAnalysisModes.AlarmPredicate); + var m = markers.Single(x => x.Code == "OTSCRIPT_SETVTAG_INERT"); + m.Severity.ShouldBe(4); + m.Message.ShouldContain("throws"); + } + + [Fact] + public async Task Hover_over_ctx_in_predicate_mode_resolves_the_alarm_predicate_context() + { + const string code = "return ctx.GetTag(\"A\").Value is not null;"; + var hover = await Svc.Hover(new HoverRequest(code, 1, 9, Mode: ScriptAnalysisModes.AlarmPredicate), CancellationToken.None); + hover.Markdown.ShouldNotBeNull().ShouldContain("AlarmPredicateContext"); + var valueHover = await Svc.Hover(new HoverRequest(code, 1, 9), CancellationToken.None); + valueHover.Markdown.ShouldNotBeNull().ShouldContain("VirtualTagContext"); + } + + [Fact] + public async Task Completion_in_predicate_mode_offers_ctx_members() + { + var resp = await Svc.CompleteAsync(new CompletionsRequest("return ctx.", 1, 12, Mode: ScriptAnalysisModes.AlarmPredicate), CancellationToken.None); + resp.Items.ShouldContain(i => i.Label == "GetTag"); + } + + [Fact] + public void Predicate_analysis_derives_from_its_own_shared_base_compilation() + { + var c1 = Svc.CompilationFor("return true;", ScriptAnalysisModes.AlarmPredicate); + var c2 = Svc.CompilationFor("return false;", ScriptAnalysisModes.AlarmPredicate); + c1.GetSpecialType(Microsoft.CodeAnalysis.SpecialType.System_Object) + .ShouldBeSameAs(c2.GetSpecialType(Microsoft.CodeAnalysis.SpecialType.System_Object)); + } + + [Fact] + public void The_monaco_interop_threads_the_mode_into_every_analysis_request() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "ZB.MOM.WW.OtOpcUa.slnx"))) dir = dir.Parent; + var js = File.ReadAllText(Path.Combine(dir!.FullName, "src", "Server", "ZB.MOM.WW.OtOpcUa.AdminUI", "wwwroot", "js", "monaco-init.js")); + js.ShouldContain("__otMode"); + // completions, hover, signature-help and diagnostics each carry it + System.Text.RegularExpressions.Regex.Matches(js, @"mode: modeOf\(model\)").Count.ShouldBeGreaterThanOrEqualTo(4); + js.ShouldContain("setMode"); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/ScriptUsageClassifyTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/ScriptUsageClassifyTests.cs new file mode 100644 index 000000000..9747fddce --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/ScriptUsageClassifyTests.cs @@ -0,0 +1,67 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis; +using ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Acls; +using ZB.MOM.WW.OtOpcUa.AdminUI.Uns; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.ScriptAnalysis; + +/// #1025 — the script editor opens in predicate mode only when scripted alarms are the script's sole users. +public sealed class ScriptUsageClassifyTests +{ + private static async Task Classify(Action seed) + { + var factory = AclScopeTestDb.Factory($"script-usage-{Guid.NewGuid():N}"); + await using var db = await factory.CreateDbContextAsync(TestContext.Current.CancellationToken); + seed(db); + await db.SaveChangesAsync(TestContext.Current.CancellationToken); + return await ScriptUsage.ClassifyAsync(db, "s-1", TestContext.Current.CancellationToken); + } + + [Fact] + public async Task An_unused_script_is_a_value_script() + { + var u = await Classify(_ => { }); + u.DefaultMode.ShouldBe(ScriptAnalysisModes.Value); + } + + [Fact] + public async Task A_script_used_only_as_a_predicate_opens_in_predicate_mode() + { + var u = await Classify(db => db.ScriptedAlarms.Add(new ScriptedAlarm + { + ScriptedAlarmId = "al-1", EquipmentId = "eq", Name = "a", AlarmType = "LimitAlarm", MessageTemplate = "m", PredicateScriptId = "s-1", + })); + u.UsedAsPredicate.ShouldBeTrue(); + u.UsedAsValue.ShouldBeFalse(); + u.DefaultMode.ShouldBe(ScriptAnalysisModes.AlarmPredicate); + } + + [Fact] + public async Task A_script_also_used_as_a_virtual_tag_stays_a_value_script() + { + var u = await Classify(db => + { + db.ScriptedAlarms.Add(new ScriptedAlarm + { + ScriptedAlarmId = "al-1", EquipmentId = "eq", Name = "a", AlarmType = "LimitAlarm", MessageTemplate = "m", PredicateScriptId = "s-1", + }); + db.VirtualTags.Add(new VirtualTag { VirtualTagId = "vt-1", EquipmentId = "eq", Name = "v", DataType = "Double", ScriptId = "s-1" }); + }); + u.UsedAsPredicate.ShouldBeTrue(); + u.UsedAsValue.ShouldBeTrue(); + u.DefaultMode.ShouldBe(ScriptAnalysisModes.Value); + } + + [Fact] + public async Task A_calculation_tag_counts_as_a_value_use() + { + var u = await Classify(db => db.Tags.Add(new Tag + { + TagId = "t-1", DeviceId = "d", Name = "calc", DataType = "Double", AccessLevel = ZB.MOM.WW.OtOpcUa.Configuration.Enums.TagAccessLevel.Read, TagConfig = "{\"scriptId\":\"s-1\"}", + })); + u.UsedAsValue.ShouldBeTrue(); + u.UsedAsPredicate.ShouldBeFalse(); + } +}