fix(editor): #1025 analyse scripted-alarm predicates as bool Run(AlarmPredicateContext) — predicate mode on the analysis endpoints, Monaco and the ScriptEdit page

This commit is contained in:
Joseph Doherty
2026-12-03 15:03:17 -05:00
parent 29c44d1f04
commit 16c8b7ffad
9 changed files with 371 additions and 55 deletions
@@ -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;
/// <summary>
/// lmxopcua#1025 — the editor used to analyse EVERY script as a VirtualTag body (<c>object Run(VirtualTagContext)</c>),
/// but the deploy gate compiles a scripted-alarm predicate as <c>bool Run(AlarmPredicateContext)</c>. 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.
/// </summary>
public sealed class PredicateModeTests
{
private static readonly ScriptAnalysisService Svc = new();
private static readonly RoslynDeployScriptChecker Gate = new();
private static IReadOnlyList<DiagnosticMarker> 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");
}
}
@@ -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;
/// <summary>#1025 — the script editor opens in predicate mode only when scripted alarms are the script's sole users.</summary>
public sealed class ScriptUsageClassifyTests
{
private static async Task<ScriptUsage.SeamUsage> Classify(Action<ZB.MOM.WW.OtOpcUa.Configuration.OtOpcUaConfigDbContext> 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();
}
}