diff --git a/.github/workflows/linux-tests.yml b/.github/workflows/linux-tests.yml index 0109f60..ae4ed9b 100644 --- a/.github/workflows/linux-tests.yml +++ b/.github/workflows/linux-tests.yml @@ -42,7 +42,7 @@ jobs: $installDirectory | Out-File -FilePath $env:GITHUB_PATH -Append -Encoding utf8 - name: Test encoders, executable formats, and Linux runtime - run: dotnet test source/Zero.slnx --configuration Release --disable-build-servers --maxcpucount:1 + run: dotnet test source/Zero.slnx --configuration Release --disable-build-servers --maxcpucount:1 --blame-hang-timeout 2m --logger "console;verbosity=normal" --logger trx --results-directory output/test-results - name: Validate all samples run: ./validate-samples.ps1 diff --git a/docs/building.md b/docs/building.md index 7adc664..4b8f78d 100644 --- a/docs/building.md +++ b/docs/building.md @@ -76,6 +76,15 @@ Native Linux x86-64 runtime tests run under Linux/WSL and skip other hosts. The PowerShell-only Linux CI workflow runs the tests, validates all sample formats, and inspects/executes `linux64-cli-01-hello` on Ubuntu. See [Linux x64](linux64.md). +### Warning - LinuxRuntimeTests + +`LinuxRuntimeTests` runs without test parallelization. Concurrent fork/exec calls +can briefly inherit another test's open executable writer, causing Linux to +reject an otherwise complete output with `ETXTBSY` ("Text file busy"). See the +[.NET runtime investigation](https://github.com/dotnet/runtime/issues/58964). +The Linux workflow also captures TRX results and aborts a test host after two +minutes without test progress, so a real hang produces diagnostics. + ## IDE runtime targets `Zero.Ide` builds for `win-x64`, `linux-x64`, `linux-arm64`, `linux-arm`, diff --git a/docs/ide-execution.md b/docs/ide-execution.md index 733f7a4..b6cd841 100644 --- a/docs/ide-execution.md +++ b/docs/ide-execution.md @@ -43,6 +43,55 @@ separate `IDebugSession` owns execution, pause, step, and stop state. `Built` is a progress notification emitted inside `CompileState`, not a separate registered state, so it does not appear as a node. +## Event notifications + +The singleton `IIdeEventService` uses Lite.EventIPC for local notifications. +It publishes these immutable records from `Zero.Ide.Events`: + +| Event | Published when | +| --- | --- | +| `ExecutionStateChangedEvent` | A workflow stage is entered, including the `Built` progress notification and terminal outcomes. | +| `BuildStartedEvent` | Validation and saving succeeded and the compiler is about to run. | +| `BuildCompletedEvent` | A compiler attempt finishes, fails, or throws, before launching the output. | +| `WorkspaceOpenedEvent` | A folder is selected and its explorer root is initialized; children load lazily. | +| `DebugStoppedEvent` | Debugging pauses at entry, a breakpoint, a step, or an exception; includes a copied register snapshot. | +| `DebugSessionEndedEvent` | A debug session exits or faults. | + +All events include a UTC `Timestamp`. Execution and build notifications share an +`ExecutionId`, source path, mode, and configuration. A canceled save or validation +failure has a terminal state notification but no compiler-attempt events. +`BuildCompletedEvent.Succeeded` describes compilation; a later launch can still +fail. Native debugger notifications come from `IDebugSession`, which owns the +running/paused lifecycle after the build workflow finishes. + +Inject `IIdeEventService` into subscribers and retain the subscription token: + +```csharp +IDisposable subscription = events.Subscribe(notification => +{ + Dispatcher.UIThread.Post(() => + Status = notification.Succeeded ? "Build succeeded" : "Build failed"); +}); + +// When the subscriber is closed or unloaded: +subscription.Dispose(); +``` + +Handlers run in the background and must marshal UI work onto Avalonia's +dispatcher. An overload accepts `Func` for asynchronous handlers; +use that overload instead of `async void`. Exceptions are traced and isolated. +Delivery is ordered within each subscription, with no ordering guarantee across +event types or subscriptions. Use `ExecutionId` to correlate build notifications. + +These are best-effort observational signals. Each subscription has a bounded +256-event queue that drops its oldest pending item when full. A blocked or slow +subscriber therefore cannot stall the UI, state machine, or another subscriber, +and pending events cannot consume unbounded memory. Disposing a token detaches +it and stops queued delivery; an already executing handler may finish afterward. +Application shutdown disposes the hub without waiting for handlers. Use direct +service calls for commands or operations that require guaranteed completion. +This registers local delivery only; no named-pipe or network endpoint is opened. + ## Regenerating From the repository root, export all three DOT files without executing the diff --git a/source/Zero.Ide.Tests/EditorExecutionCoordinatorTests.cs b/source/Zero.Ide.Tests/EditorExecutionCoordinatorTests.cs index 20b3da7..c20e628 100644 --- a/source/Zero.Ide.Tests/EditorExecutionCoordinatorTests.cs +++ b/source/Zero.Ide.Tests/EditorExecutionCoordinatorTests.cs @@ -19,10 +19,10 @@ namespace Zero.Ide.Tests; public class EditorExecutionCoordinatorTests { [TestMethod] - [DataRow(EditorExecutionMode.Build)] - [DataRow(EditorExecutionMode.Run)] - [DataRow(EditorExecutionMode.Debug)] - public void DiagramExportUsesModeSpecificRegisteredTransitions(EditorExecutionMode mode) + [DataRow(BuildExecutionMode.Build)] + [DataRow(BuildExecutionMode.Run)] + [DataRow(BuildExecutionMode.Debug)] + public void DiagramExportUsesModeSpecificRegisteredTransitions(BuildExecutionMode mode) { var dot = EditorExecutionCoordinator.ExportStateDiagram(mode); Assert.Contains("1. ValidateCompilerState", dot); @@ -30,7 +30,7 @@ public void DiagramExportUsesModeSpecificRegisteredTransitions(EditorExecutionMo Assert.Contains("\"Save\" -> \"Canceled\"", dot); Assert.Contains("\"Build\" -> \"Failed\"", dot); Assert.DoesNotContain("\"Built\" [", dot); // Built is a notification, not a registered state. - if (mode == EditorExecutionMode.Build) + if (mode == BuildExecutionMode.Build) { Assert.Contains("\"Build\" -> \"Completed\"", dot); Assert.DoesNotContain("LaunchState", dot); @@ -38,10 +38,10 @@ public void DiagramExportUsesModeSpecificRegisteredTransitions(EditorExecutionMo else { Assert.Contains("\"Build\" -> \"Launch\"", dot); - Assert.Contains(mode == EditorExecutionMode.Run ? "\"Launch\" -> \"RunFailed\"" : "\"Launch\" -> \"Failed\"", dot); + Assert.Contains(mode == BuildExecutionMode.Run ? "\"Launch\" -> \"RunFailed\"" : "\"Launch\" -> \"Failed\"", dot); } - if (mode != EditorExecutionMode.Run) Assert.DoesNotContain("RunFailedState", dot); + if (mode != BuildExecutionMode.Run) Assert.DoesNotContain("RunFailedState", dot); } private static string SourcePath => Path.Combine(Path.GetTempPath(), "program" + SourceFileExtensions.Assembly); @@ -51,16 +51,16 @@ public async Task CancelingSaveNeverValidatesBuildsOrLaunchesAsync() { var compiler = new Mock(MockBehavior.Strict); var runner = new Mock(MockBehavior.Strict); - var stages = new List(); + var stages = new List(); var result = await new EditorExecutionCoordinator(compiler.Object, runner.Object).ExecuteAsync( - Request(EditorExecutionMode.Run) with + Request(BuildExecutionMode.Run) with { SaveSourceAsync = () => Task.FromResult(null) }, update => stages.Add(update.Stage)); - Assert.AreEqual(EditorExecutionStage.Canceled, result.Stage); - Assert.AreSequenceEqual(new[] { EditorExecutionStage.ValidateCompiler, EditorExecutionStage.Save, EditorExecutionStage.Canceled }, stages); + Assert.AreEqual(BuildExecutionStage.Canceled, result.Stage); + Assert.AreSequenceEqual(new[] { BuildExecutionStage.ValidateCompiler, BuildExecutionStage.Save, BuildExecutionStage.Canceled }, stages); compiler.VerifyNoOtherCalls(); runner.VerifyNoOtherCalls(); @@ -78,14 +78,14 @@ public async Task ConcurrentExecutionIsRejectedWithoutASecondCompilerProcessAsyn .Callback(() => entered.SetResult()).Returns(finished.Task); var coordinator = new EditorExecutionCoordinator(compiler.Object); - var first = coordinator.ExecuteAsync(Request(EditorExecutionMode.Build), _ => { }); + var first = coordinator.ExecuteAsync(Request(BuildExecutionMode.Build), _ => { }); await entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); try { await Assert.ThrowsExactlyAsync( - () => coordinator.ExecuteAsync(Request(EditorExecutionMode.Build), _ => { })); + () => coordinator.ExecuteAsync(Request(BuildExecutionMode.Build), _ => { })); } finally { @@ -118,7 +118,7 @@ public async Task FailuresStopTheWorkflowBeforeLaunchingAsync(string failure) .ThrowsAsync(new IOException("Unable to start")); var runner = new Mock(MockBehavior.Strict); - var request = Request(EditorExecutionMode.Run); + var request = Request(BuildExecutionMode.Run); if (failure == "missing-compiler") request = request with { CompilerPath = "" }; @@ -130,7 +130,7 @@ public async Task FailuresStopTheWorkflowBeforeLaunchingAsync(string failure) request = request with { SaveSourceAsync = () => throw new IOException("Disk full") }; var result = await new EditorExecutionCoordinator(compiler.Object, runner.Object).ExecuteAsync(request, _ => { }); - Assert.AreEqual(EditorExecutionStage.Failed, result.Stage); + Assert.AreEqual(BuildExecutionStage.Failed, result.Stage); if (failure == "compiler-error") Assert.AreSame(compilation, result.Compilation); @@ -144,9 +144,9 @@ public async Task FailuresStopTheWorkflowBeforeLaunchingAsync(string failure) } [TestMethod] - [DataRow(EditorExecutionMode.Run, EditorExecutionStage.RunFailed)] - [DataRow(EditorExecutionMode.Debug, EditorExecutionStage.Failed)] - public async Task LaunchFailuresPreserveCompilerOutputAndPermitRetryAsync(EditorExecutionMode mode, EditorExecutionStage expected) + [DataRow(BuildExecutionMode.Run, BuildExecutionStage.RunFailed)] + [DataRow(BuildExecutionMode.Debug, BuildExecutionStage.Failed)] + public async Task LaunchFailuresPreserveCompilerOutputAndPermitRetryAsync(BuildExecutionMode mode, BuildExecutionStage expected) { var compiler = new Mock(); @@ -163,18 +163,18 @@ public async Task LaunchFailuresPreserveCompilerOutputAndPermitRetryAsync(Editor Assert.AreEqual(expected, result.Stage); Assert.AreEqual("compiled successfully", result.Compilation!.Output); Assert.IsNotNull(result.Error); - Assert.AreEqual(EditorExecutionStage.Completed, (await coordinator.ExecuteAsync(Request(EditorExecutionMode.Build), _ => { })).Stage); + Assert.AreEqual(BuildExecutionStage.Completed, (await coordinator.ExecuteAsync(Request(BuildExecutionMode.Build), _ => { })).Stage); } [TestMethod] - [DataRow(EditorExecutionMode.Build)] - [DataRow(EditorExecutionMode.Run)] - [DataRow(EditorExecutionMode.Debug)] - public async Task SuccessfulWorkflowSavesBuildsThenUsesOnlyRequestedLauncherAsync(EditorExecutionMode mode) + [DataRow(BuildExecutionMode.Build)] + [DataRow(BuildExecutionMode.Run)] + [DataRow(BuildExecutionMode.Debug)] + public async Task SuccessfulWorkflowSavesBuildsThenUsesOnlyRequestedLauncherAsync(BuildExecutionMode mode) { var calls = new List(); var compiler = new Mock(); - var configuration = mode == EditorExecutionMode.Debug ? BuildConstants.DebugConfiguration : BuildConstants.ReleaseConfiguration; + var configuration = mode == BuildExecutionMode.Debug ? BuildConstants.DebugConfiguration : BuildConstants.ReleaseConfiguration; compiler .Setup(c => c.BuildAsync("compiler", SourcePath, configuration, true)) @@ -206,14 +206,14 @@ public async Task SuccessfulWorkflowSavesBuildsThenUsesOnlyRequestedLauncherAsyn var updates = new List(); var result = await new EditorExecutionCoordinator(compiler.Object, runner.Object).ExecuteAsync(request, updates.Add); - Assert.AreEqual(EditorExecutionStage.Completed, result.Stage); + Assert.AreEqual(BuildExecutionStage.Completed, result.Stage); Assert.AreSequenceEqual( - mode == EditorExecutionMode.Build + mode == BuildExecutionMode.Build ? new[] { "save", "compile" } - : new[] { "save", "compile", mode == EditorExecutionMode.Run ? "run" : "debug" }, calls); + : new[] { "save", "compile", mode == BuildExecutionMode.Run ? "run" : "debug" }, calls); - Assert.AreEqual(EditorExecutionStage.ValidateCompiler, updates[0].Stage); - Assert.IsGreaterThan(updates.FindIndex(update => update.Stage == EditorExecutionStage.Build), updates.FindIndex(update => update.Stage == EditorExecutionStage.Built)); + Assert.AreEqual(BuildExecutionStage.ValidateCompiler, updates[0].Stage); + Assert.IsGreaterThan(updates.FindIndex(update => update.Stage == BuildExecutionStage.Build), updates.FindIndex(update => update.Stage == BuildExecutionStage.Built)); } [TestMethod] @@ -233,7 +233,7 @@ await session.Dispatch(async () => }); var coordinator = new EditorExecutionCoordinator(compiler.Object); - var result = await coordinator.ExecuteAsync(Request(EditorExecutionMode.Debug) with + var result = await coordinator.ExecuteAsync(Request(BuildExecutionMode.Debug) with { SaveSourceAsync = async () => { @@ -252,14 +252,14 @@ await session.Dispatch(async () => updates.Add(update); }); - Assert.AreEqual(EditorExecutionStage.Completed, result.Stage); - Assert.Contains(update => update.Stage == EditorExecutionStage.Launch, updates); + Assert.AreEqual(BuildExecutionStage.Completed, result.Stage); + Assert.Contains(update => update.Stage == BuildExecutionStage.Launch, updates); return 0; }, CancellationToken.None); } - private static EditorExecutionRequest Request(EditorExecutionMode mode) => + private static EditorExecutionRequest Request(BuildExecutionMode mode) => new( "compiler", BuildConstants.DebugConfiguration, diff --git a/source/Zero.Ide.Tests/IdeEventTests.cs b/source/Zero.Ide.Tests/IdeEventTests.cs new file mode 100644 index 0000000..028dabc --- /dev/null +++ b/source/Zero.Ide.Tests/IdeEventTests.cs @@ -0,0 +1,328 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Moq; +using Prism.Commands; +using Zero.Dbg; +using Zero.Ide.Events; +using Zero.Ide.Models; +using Zero.Ide.Services; +using Zero.Ide.ViewModels; + +namespace Zero.Ide.Tests; + +/// Verifies event delivery isolation and notifications emitted by execution, workspace, and debugger workflows. +[TestClass] +public class IdeEventTests +{ + /// Gets the absolute assembly source path used by mock compilation requests. + private static string SourcePath => Path.Combine(Path.GetTempPath(), "event-program" + SourceFileExtensions.Assembly); + + /// Verifies that a blocked subscriber cannot delay state-machine completion or another subscriber's notifications. + [TestMethod] + public async Task BlockedSubscriberDoesNotStallStateMachineOrOtherSubscribersAsync() + { + using var events = new IdeEventService(); + var blocked = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var completed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + using var slowSubscription = events.Subscribe(async _ => + { + blocked.TrySetResult(); + await release.Task; + }); + + using var fastSubscription = events.Subscribe(notification => + { + if (notification.Stage == BuildExecutionStage.Completed) + completed.TrySetResult(); + }); + + try + { + var compiler = CreateCompiler(); + var outcome = await new EditorExecutionCoordinator(compiler.Object, events: events) + .ExecuteAsync(Request(), _ => { }) + .WaitAsync(TimeSpan.FromSeconds(5)); + + await Task.WhenAll(blocked.Task, completed.Task).WaitAsync(TimeSpan.FromSeconds(5)); + Assert.AreEqual(BuildExecutionStage.Completed, outcome.Stage); + Assert.IsFalse(release.Task.IsCompleted); + } + finally + { + release.TrySetResult(); + } + } + + /// Verifies debugger pauses publish copied register values and session exits publish a separate notification. + [TestMethod] + public void DebuggerPausePublishesCopiedValuesAndSessionExitIsDistinct() + { + var session = new Mock(); + var events = new Mock(); + var pauses = new List(); + var ends = new List(); + + events.Setup(service => service.Publish(It.IsAny())).Callback(pauses.Add); + events.Setup(service => service.Publish(It.IsAny())).Callback(ends.Add); + + _ = new MainWindowViewModel(new EditorViewModel(), Mock.Of(), debugSession: session.Object, events: events.Object); + var registers = new List { new("EAX", 42) }; + + session.Raise( + s => s.Changed += null, + session.Object, + new DebugSnapshot(DebugState.Paused, "Breakpoint", ThreadId: 7, Registers: registers)); + + registers[0] = new RegisterValue("EAX", 99); + + Assert.HasCount(1, pauses); + Assert.AreEqual(7u, pauses[0].ThreadId); + Assert.AreEqual(42u, pauses[0].Registers[0].Value); + + session.Raise(s => s.Changed += null, session.Object, new DebugSnapshot(DebugState.Running, "Continuing")); + + Assert.HasCount(1, pauses); + + session.Raise(s => s.Changed += null, session.Object, new DebugSnapshot(DebugState.Exited, "Exited", ExitCode: 0)); + + Assert.HasCount(1, ends); + Assert.AreEqual(0u, ends[0].ExitCode); + } + + /// Verifies bounded buffering drops oldest pending notifications and service disposal disables further publication and subscriptions. + [TestMethod] + public async Task LaggingSubscriptionHasBoundedBufferAndDisposalStopsQueuedDeliveryAsync() + { + using var events = new IdeEventService(); + + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var received = new ConcurrentQueue(); + var finished = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var last = IdeEventService.SubscriptionBufferCapacity + 20; + + using var subscription = events.Subscribe(async notification => + { + received.Enqueue(notification.Number); + if (notification.Number == 0) + { + entered.TrySetResult(); + await release.Task; + } + + if (notification.Number == last) + finished.TrySetResult(); + }); + + events.Publish(new TestEvent(0)); + await entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); + + for (var index = 1; index <= last; index++) + events.Publish(new TestEvent(index)); + + release.TrySetResult(); + + await finished.Task.WaitAsync(TimeSpan.FromSeconds(5)); + + Assert.HasCount(IdeEventService.SubscriptionBufferCapacity + 1, received); + Assert.AreSequenceEqual( + new[] { 0 } + .Concat( + Enumerable.Range(last - IdeEventService.SubscriptionBufferCapacity + 1, + IdeEventService.SubscriptionBufferCapacity)) + .ToArray(), + received.ToArray()); + + subscription.Dispose(); + events.Dispose(); + events.Publish(new TestEvent(last + 1)); // Shutdown drops notifications without invoking code or waiting. + Assert.ThrowsExactly(() => events.Subscribe(_ => { })); + } + + /// Verifies per-subscription ordering and continued delivery when another subscriber throws. + [TestMethod] + public async Task SubscribersReceiveOrderedNotificationsAndExceptionsAreIsolatedAsync() + { + using var events = new IdeEventService(); + var received = new ConcurrentQueue(); + var healthy = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var faulty = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + using var healthySubscription = events.Subscribe(notification => + { + received.Enqueue(notification.Number); + if (notification.Number == 3) + healthy.TrySetResult(); + }); + + using var faultySubscription = events.Subscribe(async notification => + { + await Task.Yield(); + if (notification.Number == 3) + faulty.TrySetResult(); + + throw new InvalidOperationException("Extension failed"); + }); + + for (var index = 0; index < 4; index++) + events.Publish(new TestEvent(index)); + + await Task.WhenAll(healthy.Task, faulty.Task).WaitAsync(TimeSpan.FromSeconds(5)); + Assert.AreSequenceEqual(new[] { 0, 1, 2, 3 }, received.ToArray()); + } + + /// Verifies correlated state and compiler notifications across successful, failed, canceled, and invalid execution requests. + /// The execution outcome or failure path to simulate. + [TestMethod] + [DataRow("success")] + [DataRow("compiler-failure")] + [DataRow("compiler-exception")] + [DataRow("cancel")] + [DataRow("validation")] + [DataRow("run-failure")] + public async Task WorkflowPublishesCorrelatedBuildEventsAtCompilerBoundariesAsync(string scenario) + { + var events = new Mock(); + var started = new List(); + var builds = new List(); + var states = new List(); + + events.Setup(service => service.Publish(It.IsAny())).Callback(started.Add); + events.Setup(service => service.Publish(It.IsAny())).Callback(builds.Add); + events.Setup(service => service.Publish(It.IsAny())).Callback(states.Add); + + var compiler = CreateCompiler(scenario == "compiler-failure" ? 2 : 0); + + if (scenario == "compiler-exception") + { + compiler + .Setup(c => c.BuildAsync(It.IsAny(), It.IsAny(), It.IsAny(), false)) + .ThrowsAsync(new IOException("Compiler missing")); + } + + var runner = new Mock(); + + runner + .Setup(r => r.Run(It.IsAny(), It.IsAny())) + .Callback(() => + { + Assert.HasCount(1, builds, "Compilation notification must precede launch."); + throw new InvalidOperationException("Cannot run"); + }); + + var request = Request() with { Mode = scenario == "run-failure" ? BuildExecutionMode.Run : BuildExecutionMode.Build }; + + if (scenario == "cancel") + request = request with { SaveSourceAsync = () => Task.FromResult(null) }; + + if (scenario == "validation") + request = request with { CompilerPath = "" }; + + var outcome = await new EditorExecutionCoordinator(compiler.Object, runner.Object, events.Object).ExecuteAsync(request, _ => { }); + Assert.AreEqual(outcome.Stage, states.Last().Stage); + Assert.IsTrue(states.All(notification => notification.ExecutionId == states[0].ExecutionId)); + + if (scenario is "cancel" or "validation") + { + Assert.IsEmpty(started); + Assert.IsEmpty(builds); + compiler.VerifyNoOtherCalls(); + return; + } + + Assert.HasCount(1, started); + Assert.HasCount(1, builds); + Assert.AreEqual(started[0].ExecutionId, builds[0].ExecutionId); + Assert.AreEqual(states[0].ExecutionId, builds[0].ExecutionId); + Assert.AreEqual(SourcePath, builds[0].SourcePath); + Assert.AreEqual(BuildConstants.DebugConfiguration, builds[0].Configuration); + Assert.AreEqual(scenario is "success" or "run-failure", builds[0].Succeeded); + + if (scenario == "compiler-exception") + Assert.AreEqual("Compiler missing", builds[0].ErrorMessage); + } + + /// Verifies workspace notifications follow explorer initialization and are omitted when folder selection is canceled. + [TestMethod] + public async Task WorkspaceEventIsPublishedAfterExplorerInitializationAndNotOnCancelAsync() + { + var folder = Directory.CreateTempSubdirectory("zero-workspace-events-"); + try + { + var events = new Mock(); + var dialogs = new Mock(); + + dialogs.SetupSequence(d => d.OpenFolderAsync()).ReturnsAsync(folder.FullName).ReturnsAsync((string?)null); + + var shell = new MainWindowViewModel(new EditorViewModel(), dialogs.Object, events: events.Object); + + events.Setup(service => service.Publish(It.IsAny())).Callback(notification => + { + Assert.AreEqual(folder.FullName, notification.RootPath); + Assert.AreEqual(folder.FullName, shell.SolutionExplorer.Roots.Single().Path); + }); + + await ExecuteAsync(shell, shell.CmdOpenFolder); + await ExecuteAsync(shell, shell.CmdOpenFolder); + + events.Verify(service => service.Publish(It.IsAny()), Times.Once); + } + finally + { + folder.Delete(); + } + } + + /// Creates a mock compiler that returns a completed compilation with the specified exit code. + /// The compiler exit code to report. + /// A compiler mock configured for non-clean build requests. + private static Mock CreateCompiler(int exitCode = 0) + { + var compiler = new Mock(); + compiler + .Setup(c => c.BuildAsync(It.IsAny(), It.IsAny(), It.IsAny(), false)) + .ReturnsAsync(new CompilerResult(exitCode, "compiler output", "program.exe")); + return compiler; + } + + /// Executes a shell command and waits for its busy state to clear within the test timeout. + /// The shell that reports command progress. + /// The command to execute. + /// A task that completes when the command finishes. + private static async Task ExecuteAsync(MainWindowViewModel shell, DelegateCommand command) + { + var completed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + shell.PropertyChanged += (_, e) => + { + if (e.PropertyName == nameof(shell.IsBusy) && !shell.IsBusy) + completed.TrySetResult(); + }; + + command.Execute(); + + await completed.Task.WaitAsync(TimeSpan.FromSeconds(5)); + } + + /// Creates a build-only Debug request whose save callback returns the test source path. + /// The execution request used to exercise workflow notifications. + private static EditorExecutionRequest Request() => + new( + "compiler", + BuildConstants.DebugConfiguration, + false, + BuildExecutionMode.Build, + () => Task.FromResult(SourcePath)); + + /// Carries a sequence number for event ordering and buffer-capacity assertions. + /// The sequence number used to identify delivery order and dropped notifications. + private sealed record TestEvent(int Number) : IdeEvent; +} diff --git a/source/Zero.Ide/App.axaml.cs b/source/Zero.Ide/App.axaml.cs index 45ae989..8fd45ea 100644 --- a/source/Zero.Ide/App.axaml.cs +++ b/source/Zero.Ide/App.axaml.cs @@ -2,6 +2,7 @@ // See the LICENSE file in the project root for more information. using Avalonia; +using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Markup.Xaml; using Prism.DryIoc; using Prism.Ioc; @@ -25,11 +26,21 @@ public override void Initialize() base.Initialize(); } + /// Registers event-service cleanup on desktop application exit and completes Prism framework initialization. + public override void OnFrameworkInitializationCompleted() + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + desktop.Exit += (_, _) => Container.Resolve().Dispose(); + + base.OnFrameworkInitializationCompleted(); + } + protected override AvaloniaObject CreateShell() => Container.Resolve(); protected override void RegisterTypes(IContainerRegistry containerRegistry) { // Services + containerRegistry.RegisterSingleton(); containerRegistry.RegisterSingleton(); containerRegistry.RegisterSingleton(); containerRegistry.RegisterSingleton(); diff --git a/source/Zero.Ide/Events/DebuggerEvents.cs b/source/Zero.Ide/Events/DebuggerEvents.cs new file mode 100644 index 0000000..364c220 --- /dev/null +++ b/source/Zero.Ide/Events/DebuggerEvents.cs @@ -0,0 +1,28 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; +using Zero.Dbg; + +namespace Zero.Ide.Events; + +/// Signals a debugger pause at entry, a breakpoint, a step, or an exception so subscribers can inspect values. +/// The native identifier of the thread that paused. +/// The paused thread's instruction address in the debugged process. +/// The debugger's description of why execution paused. +/// The mapped source file path, or null when no source location is available. +/// The one-based mapped source line, or null when no source location is available. +/// A read-only copy of the register names and values captured at the pause; empty when unavailable. +public sealed record DebugStoppedEvent( + uint ThreadId, + uint InstructionPointer, + string Reason, + string? SourcePath, + int? SourceLine, + IReadOnlyList Registers) : IdeEvent; + +/// Signals that a debug session exited or faulted, rather than merely pausing for inspection. +/// The terminal debugger state, either Exited or Faulted. +/// The debugger's description of the process exit or session failure. +/// The debugged process's exit code, or null when no exit code is available. +public sealed record DebugSessionEndedEvent(DebugState State, string Reason, uint? ExitCode) : IdeEvent; diff --git a/source/Zero.Ide/Events/ExecutionEvents.cs b/source/Zero.Ide/Events/ExecutionEvents.cs new file mode 100644 index 0000000..48b6e34 --- /dev/null +++ b/source/Zero.Ide/Events/ExecutionEvents.cs @@ -0,0 +1,56 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System; +using Zero.Ide.Services; + +namespace Zero.Ide.Events; + +/// Signals entry into a workflow state or its Built progress notification; ExecutionId correlates one request. +/// The identifier shared by all execution and build notifications for this workflow request. +/// Whether the request builds only, builds and runs, or builds and starts debugging. +/// The effective build configuration; debug requests always use Debug. +/// The workflow stage being entered, including Built progress and terminal outcomes. +/// The source path returned by saving, or null before a source path is available. +/// The captured exception message, or null when no exception was recorded; inspect build results for compiler diagnostics. +public sealed record ExecutionStateChangedEvent( + Guid ExecutionId, + BuildExecutionMode Mode, + string Configuration, + BuildExecutionStage Stage, + string? SourcePath, + string? ErrorMessage) : IdeEvent; + +/// Signals that validated source is about to be compiled, including clean-and-build requests. +/// The identifier correlating this compiler attempt with its workflow and completion notification. +/// The fully qualified path of the saved and validated source file being compiled. +/// The effective Debug or Release configuration passed to the compiler service. +/// The workflow's requested action after compilation: build only, run, or debug. +/// Whether existing build output should be cleaned before compilation. +public sealed record BuildStartedEvent( + Guid ExecutionId, + string SourcePath, + string Configuration, + BuildExecutionMode Mode, + bool CleanFirst) : IdeEvent; + +/// Signals completion of a compiler attempt before any launch; validation failures and canceled saves do not emit this event. +/// The identifier shared with this attempt's start notification and execution-state notifications. +/// The fully qualified source path supplied to the compiler service. +/// The effective Debug or Release configuration used for this compiler attempt. +/// The workflow's requested action after compilation: build only, run, or debug. +/// Whether this attempt requested cleaning existing output before compilation. +/// The compiler result containing its exit code, diagnostics, and output path, or null if compilation threw an exception. +/// The compilation exception message, or null when the compiler returned a result, including a nonzero exit code. +public sealed record BuildCompletedEvent( + Guid ExecutionId, + string SourcePath, + string Configuration, + BuildExecutionMode Mode, + bool CleanFirst, + CompilerResult? Compilation, + string? ErrorMessage) : IdeEvent +{ + /// Gets whether the compiler completed successfully without an exception, independently of any later launch outcome. + public bool Succeeded => Compilation?.Succeeded == true && ErrorMessage is null; +} diff --git a/source/Zero.Ide/Events/IdeEvent.cs b/source/Zero.Ide/Events/IdeEvent.cs new file mode 100644 index 0000000..8c6a985 --- /dev/null +++ b/source/Zero.Ide/Events/IdeEvent.cs @@ -0,0 +1,13 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System; + +namespace Zero.Ide.Events; + +/// An immutable notification; subscribers observe work without controlling its outcome. +public abstract record IdeEvent +{ + /// Gets the UTC time at which this notification was created. + public DateTimeOffset Timestamp { get; } = DateTimeOffset.UtcNow; +} diff --git a/source/Zero.Ide/Events/WorkspaceOpenedEvent.cs b/source/Zero.Ide/Events/WorkspaceOpenedEvent.cs new file mode 100644 index 0000000..1c51847 --- /dev/null +++ b/source/Zero.Ide/Events/WorkspaceOpenedEvent.cs @@ -0,0 +1,8 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +namespace Zero.Ide.Events; + +/// Signals that the IDE selected a folder workspace and initialized its explorer root; children load lazily. +/// The fully qualified path of the selected workspace folder shown as the explorer root. +public sealed record WorkspaceOpenedEvent(string RootPath) : IdeEvent; diff --git a/source/Zero.Ide/Services/EditorExecutionCoordinator.cs b/source/Zero.Ide/Services/EditorExecutionCoordinator.cs index 1ba9b90..63de569 100644 --- a/source/Zero.Ide/Services/EditorExecutionCoordinator.cs +++ b/source/Zero.Ide/Services/EditorExecutionCoordinator.cs @@ -7,14 +7,21 @@ using System.Threading; using System.Threading.Tasks; using Lite.StateMachine; +using Zero.Ide.Events; using Zero.Ide.Models; namespace Zero.Ide.Services; -public enum EditorExecutionMode -{ Build, Run, Debug } +/// Compiler build execution modes. +public enum BuildExecutionMode +{ + Build, + Run, + Debug +} -public enum EditorExecutionStage +/// Build execution state machine states. +public enum BuildExecutionStage { ValidateCompiler, Save, @@ -28,67 +35,74 @@ public enum EditorExecutionStage RunFailed, } +/// Describes one save, build, and optional launch workflow. +/// The configured Zero CLI executable path, validated by the compiler service before compilation. +/// The requested Debug or Release configuration; debug mode overrides this with Debug. +/// Whether the compiler service should remove existing output before building. +/// Whether to build only, build and run, or build and start debugging. +/// The callback that saves the active document and returns its absolute path, or null when saving is canceled. +/// The callback receiving the compiled executable path and source path to start debugging; required only in debug mode. public sealed record EditorExecutionRequest( - string CompilerPath, string Configuration, bool CleanFirst, EditorExecutionMode Mode, - Func> SaveSourceAsync, Func? StartDebuggerAsync = null); - -public sealed record EditorExecutionUpdate(EditorExecutionStage Stage, CompilerResult? Compilation = null, Exception? Error = null); + string CompilerPath, + string Configuration, + bool CleanFirst, + BuildExecutionMode Mode, + Func> SaveSourceAsync, + Func? StartDebuggerAsync = null); + +/// Reports workflow progress or its terminal outcome together with available compilation diagnostics. +/// The current workflow stage or terminal outcome. +/// The completed compiler result, or null before a result is available. +/// The exception captured during workflow execution, or null when no exception occurred. +public sealed record EditorExecutionUpdate(BuildExecutionStage Stage, CompilerResult? Compilation = null, Exception? Error = null); /// Coordinates save, validation, compilation, and optional launch through explicit state transitions. -public sealed class EditorExecutionCoordinator(ICompilerService compiler, IProgramRunner? runner = null) +/// The service that compiles saved source files and optionally cleans existing output. +/// The service used to launch output without debugging; required only for run mode. +/// The optional service that publishes observational execution and compiler notifications. +/// +/// Considering renaming to BuildExecutionService and calling the state machine, a build execution coordinator. +/// +public sealed class EditorExecutionCoordinator( + ICompilerService compiler, + IProgramRunner? runner = null, + IIdeEventService? events = null) { private int _executing; /// Exports the registered workflow for the requested mode as Graphviz DOT without executing any states. - public static string ExportStateDiagram(EditorExecutionMode mode) => CreateMachine(mode).ExportUml( - initialStateIds: [EditorExecutionStage.ValidateCompiler], - includeLegend: false, - transitionColors: new Dictionary - { - [Result.Success] = "#2563EB", [Result.Error] = "#B91C1C", [Result.Failure] = "#B45309", - }, - graphName: $"Zero IDE — {mode}", - rankLeftToRight: false, - nodeLabelSelector: stage => stage switch - { - EditorExecutionStage.ValidateCompiler => $"1. {nameof(ValidateCompilerState)}", - EditorExecutionStage.Save => $"2. {nameof(SaveSourceState)}", - EditorExecutionStage.ValidateSource => $"3. {nameof(ValidateSourceState)}", - EditorExecutionStage.Build => $"4. {nameof(CompileState)}", - EditorExecutionStage.Launch => $"5. {nameof(LaunchState)}", - EditorExecutionStage.Completed => $"6. {nameof(CompletedState)}", - EditorExecutionStage.Canceled => $"2a. {nameof(CanceledState)}", - EditorExecutionStage.Failed => nameof(FailedState), - EditorExecutionStage.RunFailed => $"5a. {nameof(RunFailedState)}", - _ => stage.ToString(), - }); - - /// Shares one transition definition between execution and diagram export, omitting states unused by the selected mode. - private static StateMachine CreateMachine(EditorExecutionMode mode, Func? factory = null) - { - if (mode is not (EditorExecutionMode.Build or EditorExecutionMode.Run or EditorExecutionMode.Debug)) - throw new ArgumentOutOfRangeException(nameof(mode)); - - var machine = new StateMachine(containerFactory: factory) - .RegisterState(EditorExecutionStage.ValidateCompiler, EditorExecutionStage.Save, EditorExecutionStage.Failed) - .RegisterState(EditorExecutionStage.Save, EditorExecutionStage.ValidateSource, EditorExecutionStage.Failed, EditorExecutionStage.Canceled, parentStateId: null) - .RegisterState(EditorExecutionStage.ValidateSource, EditorExecutionStage.Build, EditorExecutionStage.Failed) - .RegisterState(EditorExecutionStage.Build, - mode == EditorExecutionMode.Build ? EditorExecutionStage.Completed : EditorExecutionStage.Launch, EditorExecutionStage.Failed) - .RegisterState(EditorExecutionStage.Completed) - .RegisterState(EditorExecutionStage.Canceled) - .RegisterState(EditorExecutionStage.Failed); - - if (mode != EditorExecutionMode.Build) - machine.RegisterState(EditorExecutionStage.Launch, EditorExecutionStage.Completed, - mode == EditorExecutionMode.Run ? EditorExecutionStage.RunFailed : EditorExecutionStage.Failed); - - if (mode == EditorExecutionMode.Run) - machine.RegisterState(EditorExecutionStage.RunFailed); - - return machine; - } - + /// The build, run, or debug workflow whose transitions should be exported. + /// The Graphviz DOT representation of the selected workflow. + public static string ExportStateDiagram(BuildExecutionMode mode) => + CreateMachine(mode).ExportUml( + initialStateIds: [BuildExecutionStage.ValidateCompiler], + includeLegend: false, + transitionColors: new Dictionary + { + [Result.Success] = "#2563EB", + [Result.Error] = "#B91C1C", + [Result.Failure] = "#B45309", + }, + graphName: $"Zero IDE — {mode}", + rankLeftToRight: false, + nodeLabelSelector: stage => stage switch + { + BuildExecutionStage.ValidateCompiler => $"1. {nameof(ValidateCompilerState)}", + BuildExecutionStage.Save => $"2. {nameof(SaveSourceState)}", + BuildExecutionStage.ValidateSource => $"3. {nameof(ValidateSourceState)}", + BuildExecutionStage.Build => $"4. {nameof(CompileState)}", + BuildExecutionStage.Launch => $"5. {nameof(LaunchState)}", + BuildExecutionStage.Completed => $"6. {nameof(CompletedState)}", + BuildExecutionStage.Canceled => $"2a. {nameof(CanceledState)}", + BuildExecutionStage.Failed => nameof(FailedState), + BuildExecutionStage.RunFailed => $"5a. {nameof(RunFailedState)}", + _ => stage.ToString(), + }); + + /// Executes one workflow at a time, reporting progress on the caller's captured synchronization context. + /// The configuration and callbacks for saving, compiling, and optionally launching the active document. + /// The progress callback invoked as stages are entered; terminal updates include available results and errors. + /// The terminal workflow update, distinguishing completion, cancellation, build failure, and run failure. public async Task ExecuteAsync(EditorExecutionRequest request, Action report) { if (Interlocked.CompareExchange(ref _executing, 1, 0) != 0) @@ -96,10 +110,10 @@ public async Task ExecuteAsync(EditorExecutionRequest req try { - var run = new ExecutionRun(request, compiler, runner, report, SynchronizationContext.Current); + var run = new ExecutionRun(request, compiler, runner, report, SynchronizationContext.Current, events); // Build state instances for each execution stage. - var states = new Dictionary> + var states = new Dictionary> { [typeof(ValidateCompilerState)] = new ValidateCompilerState(run), [typeof(SaveSourceState)] = new SaveSourceState(run), @@ -114,7 +128,7 @@ public async Task ExecuteAsync(EditorExecutionRequest req var machine = CreateMachine(request.Mode, type => states[type]); - await machine.RunAsync(EditorExecutionStage.ValidateCompiler); + await machine.RunAsync(BuildExecutionStage.ValidateCompiler); return run.Update; } finally @@ -123,25 +137,78 @@ public async Task ExecuteAsync(EditorExecutionRequest req } } + /// Shares one transition definition between execution and diagram export, omitting states unused by the selected mode. + /// The workflow mode that determines launch states and failure transitions. + /// The optional state-instance resolver used during execution; omitted when exporting transitions only. + /// A state machine configured with the selected workflow's transitions. + private static StateMachine CreateMachine(BuildExecutionMode mode, Func? factory = null) + { + if (mode is not (BuildExecutionMode.Build or BuildExecutionMode.Run or BuildExecutionMode.Debug)) + throw new ArgumentOutOfRangeException(nameof(mode)); + + var machine = new StateMachine(containerFactory: factory) + .RegisterState(BuildExecutionStage.ValidateCompiler, BuildExecutionStage.Save, BuildExecutionStage.Failed) + .RegisterState(BuildExecutionStage.Save, BuildExecutionStage.ValidateSource, BuildExecutionStage.Failed, BuildExecutionStage.Canceled, parentStateId: null) + .RegisterState(BuildExecutionStage.ValidateSource, BuildExecutionStage.Build, BuildExecutionStage.Failed) + .RegisterState(BuildExecutionStage.Build, + mode == BuildExecutionMode.Build ? BuildExecutionStage.Completed : BuildExecutionStage.Launch, BuildExecutionStage.Failed) + .RegisterState(BuildExecutionStage.Completed) + .RegisterState(BuildExecutionStage.Canceled) + .RegisterState(BuildExecutionStage.Failed); + + if (mode != BuildExecutionMode.Build) + { + machine.RegisterState( + stateId: BuildExecutionStage.Launch, + onSuccess: BuildExecutionStage.Completed, + onError: (mode == BuildExecutionMode.Run) ? BuildExecutionStage.RunFailed : BuildExecutionStage.Failed); + } + + if (mode == BuildExecutionMode.Run) + machine.RegisterState(BuildExecutionStage.RunFailed); + + return machine; + } + /// 2a. Alternate terminal path: reports cancellation when the save step returns no source path, without compiling or launching. + /// The current workflow's saved source, results, callbacks, and notification context. private sealed class CanceledState(ExecutionRun run) : ExecutionState(run); /// 4. Invokes the compiler with the selected configuration and clean option, retaining diagnostics and checking success before launch. + /// The current workflow's compiler request, results, and notification context. private sealed class CompileState(ExecutionRun run) : ExecutionState(run); /// 6. Reports successful completion after launch, or directly after step 4 for a build-only request. + /// The current workflow's completed results and notification context. private sealed class CompletedState(ExecutionRun run) : ExecutionState(run); - private sealed class ExecutionRun(EditorExecutionRequest request, ICompilerService compiler, IProgramRunner? runner, - Action report, SynchronizationContext? uiContext) + /// Holds one workflow's mutable results and executes stage actions on its captured synchronization context. + /// The workflow's configuration and save/debug-launch callbacks. + /// The compiler service invoked by the build stage. + /// The optional service that launches output in run mode. + /// The callback receiving stage progress and terminal results. + /// The caller's captured synchronization context, or null to execute without context marshaling. + /// The optional event publisher used to notify subscribers about this execution. + private sealed class ExecutionRun( + EditorExecutionRequest request, + ICompilerService compiler, + IProgramRunner? runner, + Action report, + SynchronizationContext? uiContext, + IIdeEventService? events) { - private readonly string _configuration = request.Mode == EditorExecutionMode.Debug ? BuildConstants.DebugConfiguration : request.Configuration; + private readonly string _configuration = request.Mode == BuildExecutionMode.Debug ? BuildConstants.DebugConfiguration : request.Configuration; + private readonly Guid _executionId = Guid.NewGuid(); private CompilerResult? _compilation; private string? _sourcePath; public Exception? Error { get; set; } - public EditorExecutionUpdate Update { get; private set; } = new(EditorExecutionStage.ValidateCompiler); + public EditorExecutionUpdate Update { get; private set; } = new(BuildExecutionStage.ValidateCompiler); + + /// Invokes a stage action on the captured synchronization context when marshaling is required. + /// The asynchronous stage operation to invoke. + /// A task carrying the stage transition result or the action's exception. public Task InvokeAsync(Func> action) { // Lite.StateMachine uses ConfigureAwait(false); UI operations must retain the caller's context. @@ -158,12 +225,17 @@ public Task InvokeAsync(Func> action) return completed.Task; } - public async Task StepAsync(EditorExecutionStage stage) + /// Reports the entered stage, performs its workflow operation, and selects the transition result. + /// The workflow stage whose operation should execute. + /// The transition result indicating success, compiler failure, or save cancellation. + public async Task StepAsync(BuildExecutionStage stage) { - Notify(stage); + // Sent notification of a build execution-state change to the IDE and any subscribers. + EventNotify(stage); + switch (stage) { - case EditorExecutionStage.ValidateCompiler: + case BuildExecutionStage.ValidateCompiler: if (string.IsNullOrWhiteSpace(request.CompilerPath)) throw new InvalidOperationException("Select the Zero CLI executable in Tools > Options > Compiler before building."); @@ -172,12 +244,14 @@ public async Task StepAsync(EditorExecutionStage stage) break; - case EditorExecutionStage.Save: + case BuildExecutionStage.Save: _sourcePath = await request.SaveSourceAsync(); - if (_sourcePath is null) return Result.Failure; + if (_sourcePath is null) + return Result.Failure; + break; - case EditorExecutionStage.ValidateSource: + case BuildExecutionStage.ValidateSource: if (!Path.IsPathFullyQualified(_sourcePath!)) throw new InvalidOperationException($"Building requires a local {SourceFileExtensions.Assembly} file."); @@ -186,16 +260,30 @@ public async Task StepAsync(EditorExecutionStage stage) break; - case EditorExecutionStage.Build: - _compilation = await compiler.BuildAsync(request.CompilerPath, _sourcePath!, _configuration, request.CleanFirst); + case BuildExecutionStage.Build: + // Notify of Build Started + events?.Publish(new BuildStartedEvent(_executionId, _sourcePath!, _configuration, request.Mode, request.CleanFirst)); + + try + { + _compilation = await compiler.BuildAsync(request.CompilerPath, _sourcePath!, _configuration, request.CleanFirst); + } + catch (Exception ex) + { + // Notify of a build failure + events?.Publish(new BuildCompletedEvent(_executionId, _sourcePath!, _configuration, request.Mode, request.CleanFirst, null, ex.Message)); + throw; + } + + events?.Publish(new BuildCompletedEvent(_executionId, _sourcePath!, _configuration, request.Mode, request.CleanFirst, _compilation, null)); if (!_compilation.Succeeded) return Result.Error; - Notify(EditorExecutionStage.Built); + EventNotify(BuildExecutionStage.Built); break; - case EditorExecutionStage.Launch: - if (request.Mode == EditorExecutionMode.Debug) + case BuildExecutionStage.Launch: + if (request.Mode == BuildExecutionMode.Debug) await (request.StartDebuggerAsync ?? throw new InvalidOperationException("The debugger is unavailable."))(_compilation!.OutputPath, _sourcePath!); else (runner ?? throw new InvalidOperationException("The program runner is unavailable.")).Run(_compilation!.OutputPath, Path.GetDirectoryName(_sourcePath)!); @@ -205,17 +293,26 @@ public async Task StepAsync(EditorExecutionStage stage) return Result.Success; } - private void Notify(EditorExecutionStage stage) + /// Publish event of updates to workflow progress, publishing a correlated execution-state notification. + /// The entered stage or progress notification to report to the UI and subscribers. + private void EventNotify(BuildExecutionStage stage) { Update = new EditorExecutionUpdate(stage, _compilation, Error); report(Update); + + // Inform system of a build execution-state change + events?.Publish(new ExecutionStateChangedEvent(_executionId, request.Mode, _configuration, stage, _sourcePath, Error?.Message)); } } /// Shared base for steps 1–6 and alternate exits; runs state actions on the caller's UI context and routes exceptions to error transitions. - private abstract class ExecutionState(ExecutionRun run) : IState + /// The current workflow's stage executor, results, and captured synchronization context. + private abstract class ExecutionState(ExecutionRun run) : IState { - public async Task OnEnter(Context context) + /// Executes the entered stage and selects its next transition, capturing exceptions as workflow errors. + /// The state-machine context identifying the entered stage and accepting the next transition result. + /// A task that completes when the stage action and transition selection finish. + public async Task OnEnter(Context context) { try { @@ -228,26 +325,38 @@ public async Task OnEnter(Context context) } } - public Task OnEntering(Context context) => Task.CompletedTask; + /// Completes the pre-entry hook without additional work. + /// The state-machine context for the stage about to be entered. + /// An already completed task. + public Task OnEntering(Context context) => Task.CompletedTask; - public Task OnExit(Context context) => Task.CompletedTask; + /// Completes the exit hook without additional work. + /// The state-machine context for the stage being exited. + /// An already completed task. + public Task OnExit(Context context) => Task.CompletedTask; } /// 1–5, alternate terminal path. Reports validation, save, compilation, or debugger-startup failure instead of continuing to subsequent steps. + /// The current workflow's error, compilation results, and notification context. private sealed class FailedState(ExecutionRun run) : ExecutionState(run); /// 5. After successful compilation, launches the executable normally or starts a debug session; skipped for build-only requests. + /// The current workflow's compiled output, launch services, and mode. private sealed class LaunchState(ExecutionRun run) : ExecutionState(run); /// 5a. Alternate terminal path: reports a normal program-launch failure while preserving successful compiler output. + /// The current workflow's launch error, successful compilation result, and notification context. private sealed class RunFailedState(ExecutionRun run) : ExecutionState(run); /// 2. Runs the source-saving callback and captures its resulting path; cancellation branches to step 2a. + /// The current workflow's save callback, source path, and notification context. private sealed class SaveSourceState(ExecutionRun run) : ExecutionState(run); /// 1. Checks that a compiler is configured and that the effective Debug or Release configuration is supported before requesting a save. + /// The current workflow's compiler settings, effective configuration, and notification context. private sealed class ValidateCompilerState(ExecutionRun run) : ExecutionState(run); /// 3. Verifies that the saved source path is fully qualified and has the supported ZASM extension before compilation. + /// The current workflow's saved source path and notification context. private sealed class ValidateSourceState(ExecutionRun run) : ExecutionState(run); } diff --git a/source/Zero.Ide/Services/IIdeEventService.cs b/source/Zero.Ide/Services/IIdeEventService.cs new file mode 100644 index 0000000..4dcbdfa --- /dev/null +++ b/source/Zero.Ide/Services/IIdeEventService.cs @@ -0,0 +1,29 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System; +using System.Threading.Tasks; +using Zero.Ide.Events; + +namespace Zero.Ide.Services; + +/// Publishes local Lite.EventIPC notifications without executing subscriber code on the publisher's thread. +public interface IIdeEventService : IDisposable +{ + /// Queues a notification for each subscriber without waiting for handlers; notifications after disposal are ignored. + /// The concrete notification type to publish. + /// The notification to deliver to matching subscriptions. + void Publish(TEvent notification) where TEvent : IdeEvent; + + /// Subscribes a background handler; dispose the returned token to detach it. Marshal UI updates onto Avalonia's dispatcher. + /// The concrete notification type to receive. + /// The handler invoked sequentially for this subscription. + /// A token that detaches the handler and stops queued delivery when disposed. + IDisposable Subscribe(Action handler) where TEvent : IdeEvent; + + /// Subscribes an awaited background handler with per-subscription ordering and exception isolation. + /// The concrete notification type to receive. + /// The asynchronous handler awaited before processing the next notification. + /// A token that detaches the handler and stops queued delivery when disposed. + IDisposable Subscribe(Func handler) where TEvent : IdeEvent; +} diff --git a/source/Zero.Ide/Services/IdeEventService.cs b/source/Zero.Ide/Services/IdeEventService.cs new file mode 100644 index 0000000..a426ce1 --- /dev/null +++ b/source/Zero.Ide/Services/IdeEventService.cs @@ -0,0 +1,176 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; +using Lite.EventIpc; +using Zero.Ide.Events; + +namespace Zero.Ide.Services; + +/// Isolates Lite.EventIPC subscribers with bounded, ordered queues so extensions cannot stall UI or workflow transitions. +public sealed class IdeEventService : IIdeEventService +{ + /// The maximum number of pending notifications per subscription before the oldest pending notification is dropped. + public const int SubscriptionBufferCapacity = 256; + private readonly object _gate = new(); + private readonly EventAggregator _aggregator = new(); + private readonly HashSet _subscriptions = []; + private bool _disposed; + + /// Queues a notification through Lite.EventIPC without invoking subscriber code on the publisher's thread. + /// The concrete notification type to publish. + /// The notification to enqueue; ignored after service disposal. + public void Publish(TEvent notification) where TEvent : IdeEvent + { + ArgumentNullException.ThrowIfNull(notification); + lock (_gate) + { + if (!_disposed) + _aggregator.Publish(notification); + } + } + + /// Registers a synchronous handler for ordered background delivery with exception isolation. + /// The concrete notification type to receive. + /// The handler to invoke on the subscription's background worker. + /// A disposable token that detaches the subscription. + public IDisposable Subscribe(Action handler) where TEvent : IdeEvent + { + ArgumentNullException.ThrowIfNull(handler); + + return Subscribe(notification => + { + handler(notification); + return Task.CompletedTask; + }); + } + + /// Registers an asynchronous handler with a bounded queue and one sequential background worker. + /// The concrete notification type to receive. + /// The handler awaited for each notification before processing the next one. + /// A disposable token that detaches the subscription. + public IDisposable Subscribe(Func handler) where TEvent : IdeEvent + { + ArgumentNullException.ThrowIfNull(handler); + lock (_gate) + { + ObjectDisposedException.ThrowIf(_disposed, this); + var subscription = new Subscription(handler, Remove); + + _subscriptions.Add(subscription); // Keep Lite.EventIPC's weak handler alive until explicit disposal. + _aggregator.Subscribe(subscription.Enqueue); + + return subscription; + } + } + + /// Stops accepting notifications and detaches all subscriptions without waiting for active handlers. + public void Dispose() + { + ISubscription[] subscriptions; + lock (_gate) + { + if (_disposed) + return; + + _disposed = true; + subscriptions = new ISubscription[_subscriptions.Count]; + _subscriptions.CopyTo(subscriptions); + } + + foreach (var subscription in subscriptions) + subscription.Dispose(); + } + + /// Unsubscribes a handler from Lite.EventIPC and releases the service's strong reference under the publication lock. + /// The subscription being disposed. + private void Remove(ISubscription subscription) + { + lock (_gate) + { + subscription.Detach(_aggregator); + _subscriptions.Remove(subscription); + } + } + + /// Provides non-generic lifecycle operations for subscriptions retained by the event service. + private interface ISubscription : IDisposable + { + /// Removes the subscription's enqueue handler from the underlying Lite.EventIPC aggregator. + /// The aggregator that owns the handler registration. + void Detach(IEventAggregator aggregator); + } + + /// Delivers one event type through a bounded queue while isolating subscriber latency and exceptions. + /// The concrete notification type handled by this subscription. + private sealed class Subscription : ISubscription where TEvent : IdeEvent + { + private readonly Channel _queue = Channel.CreateBounded(new BoundedChannelOptions(SubscriptionBufferCapacity) + { + SingleReader = true, + AllowSynchronousContinuations = false, + FullMode = BoundedChannelFullMode.DropOldest, + }); + + private readonly Func _handler; + + private readonly Action _remove; + + private int _disposed; + + /// Initializes a subscription and starts its sequential background delivery worker. + /// The asynchronous handler invoked for each queued notification. + /// The callback that detaches the subscription from its owning service. + public Subscription(Func handler, Action remove) + { + _handler = handler; + _remove = remove; + _ = Task.Run(ProcessAsync); + } + + /// Queues a notification without blocking, dropping the oldest pending item when the buffer is full. + /// The notification to enqueue if the queue is still open. + public void Enqueue(TEvent notification) => + _queue.Writer.TryWrite(notification); + + /// Unregisters the enqueue handler from Lite.EventIPC. + /// The aggregator that owns this subscription's registration. + public void Detach(IEventAggregator aggregator) => + aggregator.Unsubscribe(Enqueue); + + /// Detaches the subscription and stops queued delivery without waiting for an active handler to finish. + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + return; + + _remove(this); + _queue.Writer.TryComplete(); + } + + /// Processes queued notifications in order, tracing handler failures and stopping delivery after disposal. + /// A task that completes when queued processing ends. + private async Task ProcessAsync() + { + await foreach (var notification in _queue.Reader.ReadAllAsync().ConfigureAwait(false)) + { + if (Volatile.Read(ref _disposed) != 0) + break; + + try + { + await _handler(notification).ConfigureAwait(false); + } + catch (Exception ex) + { + Trace.TraceError($"IDE event subscriber failed for {typeof(TEvent).Name}: {ex}"); + } + } + } + } +} diff --git a/source/Zero.Ide/ViewModels/MainWindowViewModel.Debug.cs b/source/Zero.Ide/ViewModels/MainWindowViewModel.Debug.cs index d9cc143..0699f31 100644 --- a/source/Zero.Ide/ViewModels/MainWindowViewModel.Debug.cs +++ b/source/Zero.Ide/ViewModels/MainWindowViewModel.Debug.cs @@ -11,6 +11,7 @@ using Prism.Commands; using Zero.Dbg; using Zero.Dbg.WinPe; +using Zero.Ide.Events; namespace Zero.Ide.ViewModels; @@ -220,6 +221,12 @@ private async void OnDebuggerChangedAsync(object? sender, DebugSnapshot snapshot document.Editor.ExecutionLine = 0; } + if (snapshot.State == DebugState.Paused) + _events?.Publish(new DebugStoppedEvent(snapshot.ThreadId, snapshot.InstructionPointer, snapshot.Reason, + snapshot.Location?.FilePath, snapshot.Location?.Line, new List(snapshot.Registers ?? []).AsReadOnly())); + else if (snapshot.State is DebugState.Exited or DebugState.Faulted) + _events?.Publish(new DebugSessionEndedEvent(snapshot.State, snapshot.Reason, snapshot.ExitCode)); + if (snapshot.State != DebugState.Paused || snapshot.Location is not { } location) return; diff --git a/source/Zero.Ide/ViewModels/MainWindowViewModel.cs b/source/Zero.Ide/ViewModels/MainWindowViewModel.cs index 05b99d7..62d38a6 100644 --- a/source/Zero.Ide/ViewModels/MainWindowViewModel.cs +++ b/source/Zero.Ide/ViewModels/MainWindowViewModel.cs @@ -12,6 +12,7 @@ using Prism.Commands; using Zero.Dbg; using Zero.Ide.Docking; +using Zero.Ide.Events; using Zero.Ide.Models; using Zero.Ide.Services; @@ -22,6 +23,7 @@ public partial class MainWindowViewModel : ViewModelBase private readonly ICompilerService? _compilerService; private readonly IEditorDialogService _dialogs; private readonly EditorViewModel _emptyEditor = new(); + private readonly IIdeEventService? _events; private readonly EditorExecutionCoordinator? _executionCoordinator; private readonly IProgramRunner? _programRunner; private readonly ISettingsService? _settings; @@ -38,12 +40,13 @@ public partial class MainWindowViewModel : ViewModelBase public MainWindowViewModel(EditorViewModel editor, IEditorDialogService dialogs, ISettingsService? settings = null, ICompilerService? compilerService = null, IProgramRunner? programRunner = null, IUpdateService? updates = null, - IDebugSession? debugSession = null, EditorExecutionCoordinator? executionCoordinator = null) + IDebugSession? debugSession = null, EditorExecutionCoordinator? executionCoordinator = null, IIdeEventService? events = null) { _dialogs = dialogs; _settings = settings; _compilerService = compilerService; - _executionCoordinator = executionCoordinator ?? (compilerService is null ? null : new EditorExecutionCoordinator(compilerService, programRunner)); + _events = events; + _executionCoordinator = executionCoordinator ?? (compilerService is null ? null : new EditorExecutionCoordinator(compilerService, programRunner, events)); _programRunner = programRunner; _updates = updates; settings?.SettingsChanged += (_, _) => NotifyThemeChanged(); @@ -319,7 +322,7 @@ private async Task BuildAsync(bool cleanFirst, bool runAfterBuild = false, bool var editor = document.Editor; var configuration = debugAfterBuild ? BuildConstants.DebugConfiguration : BuildConfiguration; - var mode = debugAfterBuild ? EditorExecutionMode.Debug : runAfterBuild ? EditorExecutionMode.Run : EditorExecutionMode.Build; + var mode = debugAfterBuild ? BuildExecutionMode.Debug : runAfterBuild ? BuildExecutionMode.Run : BuildExecutionMode.Build; var request = new EditorExecutionRequest( editor.Settings.CompilerPath, @@ -337,25 +340,25 @@ private async Task BuildAsync(bool cleanFirst, bool runAfterBuild = false, bool var outcome = await _executionCoordinator!.ExecuteAsync(request, update => { - if (update.Stage == EditorExecutionStage.Build) + if (update.Stage == BuildExecutionStage.Build) { BuildState = EditorBuildState.Building; BuildOutput = Status = $"Building {editor.FileName} ({configuration})"; } - else if (update.Stage == EditorExecutionStage.Built) + else if (update.Stage == BuildExecutionStage.Built) { BuildState = EditorBuildState.Idle; BuildOutput = update.Compilation!.Output + Environment.NewLine + $"Compiler exit code: {update.Compilation.ExitCode}"; Status = $"Build succeeded: {update.Compilation.OutputPath}"; } - else if (update.Stage == EditorExecutionStage.Completed && mode == EditorExecutionMode.Run) + else if (update.Stage == BuildExecutionStage.Completed && mode == BuildExecutionMode.Run) { Status = $"Started {update.Compilation!.OutputPath}"; BuildOutput += Environment.NewLine + Status; } }); - if (outcome.Stage == EditorExecutionStage.Failed) + if (outcome.Stage == BuildExecutionStage.Failed) { if (outcome.Error is { } error) { @@ -369,7 +372,7 @@ private async Task BuildAsync(bool cleanFirst, bool runAfterBuild = false, bool await _dialogs.ShowMessageAsync("Build failure", BuildOutput); } } - else if (outcome.Stage == EditorExecutionStage.RunFailed) + else if (outcome.Stage == BuildExecutionStage.RunFailed) { BuildState = EditorBuildState.RunFailed; Status = "Run failed"; @@ -564,6 +567,7 @@ private async Task OpenFolderAsync() SolutionExplorer.LoadFolder(path); DockFactory.ShowExplorer(); + _events?.Publish(new WorkspaceOpenedEvent(Path.GetFullPath(path))); } private void RemoveDocument(EditorDocument document) diff --git a/source/Zero.Tests/ZAsmTests/LinuxRuntimeTests.cs b/source/Zero.Tests/ZAsmTests/LinuxRuntimeTests.cs index 66f47df..9d7ae6f 100644 --- a/source/Zero.Tests/ZAsmTests/LinuxRuntimeTests.cs +++ b/source/Zero.Tests/ZAsmTests/LinuxRuntimeTests.cs @@ -9,6 +9,9 @@ namespace Zero.Tests.ZAsmTests; [TestClass] +// Parallel fork/exec can briefly inherit another test's open executable writer (ETXTBSY). +// Serialize these compile-then-execute fixtures, including against other test classes. +[DoNotParallelize] public sealed class LinuxRuntimeTests { [TestMethod]