Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Launch Cadmata as a packaged STEP viewer

Yuechen Li9edd6adf9c6e
diff --git a/Aetheris.CLI.Tests/CadmataViewTests.cs b/Aetheris.CLI.Tests/CadmataViewTests.cs
new file mode 100644
index 00000000..4cd38380
--- /dev/null
+++ b/Aetheris.CLI.Tests/CadmataViewTests.cs
@@ -0,0 +1,217 @@
+using System.Diagnostics;
+using System.Text.Json;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class CadmataViewTests
+{
+ [Fact]
+ public void DirectStep_UsesPackagedDiscovery_AndHandsOffAbsolutePathWithSpaces()
+ {
+ using var fixture = ViewFixture.Create("direct space.step");
+ var packaged = fixture.AddPackagedCadmata();
+ var launcher = new RecordingLauncher();
+
+ var exitCode = Run(["view", Path.GetRelativePath(Directory.GetCurrentDirectory(), fixture.StepPath)], fixture, launcher, out var stdout, out var stderr);
+
+ Assert.Equal(0, exitCode);
+ Assert.Empty(stderr);
+ Assert.Equal(packaged, launcher.ExecutablePath);
+ Assert.Equal(fixture.StepPath, launcher.StepPath);
+ Assert.Contains("Opened direct space.step in Cadmata", stdout, StringComparison.Ordinal);
+ Assert.False(File.Exists(Path.ChangeExtension(fixture.StepPath, ".firmament")));
+ }
+
+ [Fact]
+ public void Firmament_BuildsAdjacentStepBeforeLaunch()
+ {
+ using var fixture = ViewFixture.CreateFirmament("plate source.firmament");
+ fixture.AddPackagedCadmata();
+ var launcher = new RecordingLauncher();
+
+ var exitCode = Run(["view", fixture.SourcePath!], fixture, launcher, out var stdout, out var stderr);
+
+ Assert.Equal(0, exitCode);
+ Assert.Empty(stderr);
+ Assert.True(File.Exists(fixture.StepPath));
+ Assert.Equal(fixture.StepPath, launcher.StepPath);
+ Assert.Contains("Built plate source.firmament", stdout, StringComparison.Ordinal);
+ Assert.Contains("STEP: " + fixture.StepPath, stdout, StringComparison.Ordinal);
+ }
+
+ [Theory]
+ [InlineData("nested/part.stp")]
+ [InlineData("nested/part.step")]
+ public void StepExtensionsAndNestedPathsLaunchDirectly(string relativeName)
+ {
+ using var fixture = ViewFixture.Create(relativeName.Replace('/', Path.DirectorySeparatorChar));
+ fixture.AddPackagedCadmata();
+ var launcher = new RecordingLauncher();
+
+ var exitCode = Run(["view", fixture.StepPath], fixture, launcher, out _, out var stderr);
+
+ Assert.Equal(0, exitCode);
+ Assert.Empty(stderr);
+ Assert.Equal(fixture.StepPath, launcher.StepPath);
+ }
+
+ [Fact]
+ public void ConfiguredOverrideWinsAndJsonReportsStableHandoffFields()
+ {
+ using var fixture = ViewFixture.Create("plate.step");
+ var configured = Path.Combine(fixture.Root, "custom", "Cadmata custom.exe");
+ Directory.CreateDirectory(Path.GetDirectoryName(configured)!);
+ File.WriteAllText(configured, "placeholder");
+ var launcher = new RecordingLauncher();
+
+ var exitCode = Run(["view", fixture.StepPath, "--cadmata-path", configured, "--json"], fixture, launcher, out var stdout, out var stderr);
+
+ Assert.Equal(0, exitCode);
+ Assert.Empty(stderr);
+ Assert.Equal(configured, launcher.ExecutablePath);
+ using var json = JsonDocument.Parse(stdout);
+ Assert.True(json.RootElement.GetProperty("launched").GetBoolean());
+ Assert.Equal(fixture.StepPath, json.RootElement.GetProperty("stepPath").GetString());
+ Assert.Equal(configured, json.RootElement.GetProperty("cadmataPath").GetString());
+ Assert.True(json.RootElement.GetProperty("processId").GetInt32() > 0);
+ }
+
+ [Fact]
+ public void MissingCadmataAndLaunchFailureAreReadable()
+ {
+ using var fixture = ViewFixture.Create("plate.step");
+ var missing = Path.Combine(fixture.Root, "missing.exe");
+
+ var missingCode = Run(["view", fixture.StepPath, "--cadmata-path", missing], fixture, new RecordingLauncher(), out _, out var missingError);
+ Assert.Equal(1, missingCode);
+ Assert.Contains("Cadmata was not found", missingError, StringComparison.Ordinal);
+
+ var configured = fixture.AddPackagedCadmata();
+ var failingCode = Run(["view", fixture.StepPath, "--cadmata-path", configured], fixture, new RecordingLauncher(new InvalidOperationException("launch denied")), out _, out var launchError);
+ Assert.Equal(1, failingCode);
+ Assert.Contains("Could not open", launchError, StringComparison.Ordinal);
+ Assert.Contains("launch denied", launchError, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void BuildFailurePreventsLaunch()
+ {
+ using var fixture = ViewFixture.CreateFirmament("bad.firmament", "Model Broken {");
+ fixture.AddPackagedCadmata();
+ var launcher = new RecordingLauncher();
+
+ var exitCode = Run(["view", fixture.SourcePath!], fixture, launcher, out _, out var stderr);
+
+ Assert.Equal(1, exitCode);
+ Assert.Null(launcher.StepPath);
+ Assert.Contains("build failed", stderr, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public void DiscoveryOrderPrefersCanonicalEnvironmentThenCompatibilityThenPackage()
+ {
+ using var fixture = ViewFixture.Create("plate.step");
+ var canonical = fixture.Touch("canonical.exe");
+ var compatibility = fixture.Touch("compat.exe");
+ var packaged = fixture.AddPackagedCadmata();
+ var values = new Dictionary<string, string?>
+ {
+ ["AETHERIS_CADMATA_PATH"] = canonical,
+ ["AETHERIS_CAD_ASSISTANT_PATH"] = compatibility,
+ ["PATH"] = string.Empty,
+ };
+
+ var canonicalResult = Aetheris.CLI.CadmataDiscovery.Resolve(null, fixture.CliBase, key => values.GetValueOrDefault(key));
+ Assert.Equal(canonical, canonicalResult!.Path);
+
+ values["AETHERIS_CADMATA_PATH"] = null;
+ var compatibilityResult = Aetheris.CLI.CadmataDiscovery.Resolve(null, fixture.CliBase, key => values.GetValueOrDefault(key));
+ Assert.Equal(compatibility, compatibilityResult!.Path);
+
+ values["AETHERIS_CAD_ASSISTANT_PATH"] = null;
+ var packagedResult = Aetheris.CLI.CadmataDiscovery.Resolve(null, fixture.CliBase, key => values.GetValueOrDefault(key));
+ Assert.Equal(packaged, packagedResult!.Path);
+ }
+
+ private static int Run(string[] args, ViewFixture fixture, Aetheris.CLI.ICadmataProcessLauncher launcher, out string stdout, out string stderr)
+ {
+ var output = new StringWriter();
+ var error = new StringWriter();
+ var result = Aetheris.CLI.CliRunner.Run(args, output, error, launcher, fixture.CliBase);
+ stdout = output.ToString();
+ stderr = error.ToString();
+ return result;
+ }
+
+ private sealed class RecordingLauncher(Exception? failure = null) : Aetheris.CLI.ICadmataProcessLauncher
+ {
+ public string? ExecutablePath { get; private set; }
+ public string? StepPath { get; private set; }
+
+ public Process? Launch(string executablePath, string stepPath)
+ {
+ ExecutablePath = executablePath;
+ StepPath = stepPath;
+ if (failure is not null) throw failure;
+ return Process.GetCurrentProcess();
+ }
+ }
+
+ private sealed class ViewFixture : IDisposable
+ {
+ private ViewFixture(string root, string workingDirectory, string cliBase, string stepPath, string? sourcePath)
+ => (Root, WorkingDirectory, CliBase, StepPath, SourcePath) = (root, workingDirectory, cliBase, stepPath, sourcePath);
+
+ public string Root { get; }
+ public string WorkingDirectory { get; }
+ public string CliBase { get; }
+ public string StepPath { get; }
+ public string? SourcePath { get; }
+
+ public static ViewFixture Create(string relativeStep)
+ {
+ var root = Path.Combine(Path.GetTempPath(), "Aetheris view tests " + Guid.NewGuid().ToString("N"));
+ var working = Path.Combine(root, "user directory");
+ var cliBase = Path.Combine(root, "bundle");
+ var step = Path.GetFullPath(Path.Combine(working, relativeStep));
+ Directory.CreateDirectory(Path.GetDirectoryName(step)!);
+ Directory.CreateDirectory(cliBase);
+ File.WriteAllText(step, "ISO-10303-21;");
+ return new ViewFixture(root, working, cliBase, step, null);
+ }
+
+ public static ViewFixture CreateFirmament(string name, string? source = null)
+ {
+ var fixture = Create(Path.ChangeExtension(name, ".step"));
+ var sourcePath = Path.Combine(fixture.WorkingDirectory, name);
+ File.WriteAllText(sourcePath, source ?? """
+ Model Plate {
+ Units: mm
+ Box Body { Size: [10mm, 20mm, 3mm] }
+ }
+ """);
+ File.Delete(fixture.StepPath);
+ return new ViewFixture(fixture.Root, fixture.WorkingDirectory, fixture.CliBase, fixture.StepPath, sourcePath);
+ }
+
+ public string AddPackagedCadmata()
+ {
+ var path = Path.Combine(CliBase, "cadmata", "Cadmata.exe");
+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);
+ File.WriteAllText(path, "placeholder");
+ return path;
+ }
+
+ public string Touch(string name)
+ {
+ var path = Path.Combine(Root, name);
+ File.WriteAllText(path, "placeholder");
+ return path;
+ }
+
+ public void Dispose()
+ {
+ if (Directory.Exists(Root)) Directory.Delete(Root, recursive: true);
+ }
+ }
+}
diff --git a/Aetheris.CLI/CadmataLaunch.cs b/Aetheris.CLI/CadmataLaunch.cs
new file mode 100644
index 00000000..1db4a725
--- /dev/null
+++ b/Aetheris.CLI/CadmataLaunch.cs
@@ -0,0 +1,110 @@
+using System.Diagnostics;
+
+namespace Aetheris.CLI;
+
+public sealed record CadmataDiscoveryResult(string Path, string Source);
+
+public static class CadmataDiscovery
+{
+ public static CadmataDiscoveryResult? Resolve(
+ string? explicitPath,
+ string cliBaseDirectory,
+ Func<string, string?>? environment = null,
+ string? pathValue = null)
+ {
+ environment ??= Environment.GetEnvironmentVariable;
+
+ if (!string.IsNullOrWhiteSpace(explicitPath))
+ {
+ var fullPath = Path.GetFullPath(explicitPath);
+ return File.Exists(fullPath)
+ ? new CadmataDiscoveryResult(fullPath, "explicit --cadmata-path")
+ : null;
+ }
+
+ var configured = new[]
+ {
+ (Value: environment("AETHERIS_CADMATA_PATH"), Source: "AETHERIS_CADMATA_PATH"),
+ (Value: environment("AETHERIS_CAD_ASSISTANT_PATH"), Source: "AETHERIS_CAD_ASSISTANT_PATH compatibility setting"),
+ };
+
+ foreach (var candidate in configured)
+ {
+ if (string.IsNullOrWhiteSpace(candidate.Value)) continue;
+ var fullPath = Path.GetFullPath(candidate.Value);
+ if (File.Exists(fullPath)) return new CadmataDiscoveryResult(fullPath, candidate.Source);
+ }
+
+ var packagedCandidates = new[]
+ {
+ (Path: Path.Combine(cliBaseDirectory, "Cadmata.exe"), Source: "sibling Cadmata executable"),
+ (Path: Path.Combine(cliBaseDirectory, "cadmata", "Cadmata.exe"), Source: "package-relative cadmata directory"),
+ (Path: Path.Combine(cliBaseDirectory, "tools", "cadmata", "Cadmata.exe"), Source: "package-relative tools/cadmata directory"),
+ };
+
+ foreach (var candidate in packagedCandidates)
+ {
+ if (File.Exists(candidate.Path)) return new CadmataDiscoveryResult(Path.GetFullPath(candidate.Path), candidate.Source);
+ }
+
+ pathValue ??= environment("PATH");
+ if (!string.IsNullOrWhiteSpace(pathValue))
+ {
+ foreach (var directory in pathValue.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
+ {
+ foreach (var name in OperatingSystem.IsWindows() ? new[] { "Cadmata.exe", "cadmata.exe" } : new[] { "cadmata", "Cadmata" })
+ {
+ var candidate = Path.Combine(directory, name);
+ if (File.Exists(candidate)) return new CadmataDiscoveryResult(Path.GetFullPath(candidate), "PATH");
+ }
+ }
+ }
+
+ return ResolveDevelopmentBuild(cliBaseDirectory)
+ ?? ResolveDevelopmentBuild(Directory.GetCurrentDirectory());
+ }
+
+ private static CadmataDiscoveryResult? ResolveDevelopmentBuild(string startingPath)
+ {
+ var directory = new DirectoryInfo(Path.GetFullPath(startingPath));
+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx")))
+ {
+ directory = directory.Parent;
+ }
+
+ if (directory is null) return null;
+ foreach (var configuration in new[] { "Release", "Debug" })
+ {
+ var candidate = Path.Combine(directory.FullName, "Aetheris.Server", "bin", configuration, "net10.0", "Cadmata.exe");
+ if (File.Exists(candidate)) return new CadmataDiscoveryResult(candidate, "development build fallback");
+ }
+
+ return null;
+ }
+}
+
+internal interface ICadmataProcessLauncher
+{
+ Process? Launch(string executablePath, string stepPath);
+}
+
+internal sealed class SystemCadmataProcessLauncher : ICadmataProcessLauncher
+{
+ public Process? Launch(string executablePath, string stepPath)
+ {
+ var startInfo = new ProcessStartInfo(executablePath)
+ {
+ UseShellExecute = true,
+ WindowStyle = ProcessWindowStyle.Hidden,
+ WorkingDirectory = Path.GetDirectoryName(executablePath) ?? AppContext.BaseDirectory,
+ };
+ startInfo.ArgumentList.Add(stepPath);
+ var process = Process.Start(startInfo);
+ if (process is not null && process.WaitForExit(250))
+ {
+ throw new InvalidOperationException($"Cadmata exited during startup with code {process.ExitCode}.");
+ }
+
+ return process;
+ }
+}
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 8a34a3ef..837d08dd 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -128,7 +128,7 @@ public static class CliRunner
private const string SectionsUsage = "Usage: aetheris sections <artifact.step> --axis Z --levels <z,...> [--epsilon <mm>] --json";
private const string VerifyUsage = "Usage: aetheris verify <file.firmament|file.step> [--expected-volume <value>] [--cad-assistant] [--cad-assistant-path <path>] [--timeout <seconds>] [--evidence-dir <path>] [--require-external] [--json]";
private const string InspectUsage = "Usage: aetheris inspect <file.firmament|file.step> [--json]";
- private const string ViewUsage = "Usage: aetheris view <file.firmament|file.step> [--cad-assistant-path <path>] [--json]";
+ private const string ViewUsage = "Usage: aetheris view <file.firmament|file.step> [--cadmata-path <path>] [--json]";
private const string MatchUsage = "Usage: aetheris match <file.step> <concept.firmament> [--linear-tolerance <mm>] [--angular-tolerance <deg>] [--json]";
private const string TraceUsage = "Usage: aetheris trace (--case <name>|--fixture <path>) [--out-dir <dir>] [--json]";
private const string CanonUsage = "Usage: aetheris canon <file.step> --out <canonical.step> [--mode deterministic|production] [--json]";
@@ -153,6 +153,9 @@ public static class CliRunner
}
public static int Run(string[] args, TextWriter stdout, TextWriter stderr)
+ => Run(args, stdout, stderr, new SystemCadmataProcessLauncher(), AppContext.BaseDirectory);
+
+ internal static int Run(string[] args, TextWriter stdout, TextWriter stderr, ICadmataProcessLauncher cadmataLauncher, string cliBaseDirectory)
{
if (args.Length == 0)
{
@@ -186,7 +189,7 @@ public static class CliRunner
"sections" => RunSections(args.Skip(1).ToArray(), stdout, stderr),
"analyze" => RunAnalyze(args.Skip(1).ToArray(), stdout, stderr),
"verify" => RunVerify(args.Skip(1).ToArray(), stdout, stderr),
- "view" => RunView(args.Skip(1).ToArray(), stdout, stderr),
+ "view" => RunView(args.Skip(1).ToArray(), stdout, stderr, cadmataLauncher, cliBaseDirectory),
"match" => RunMatch(args.Skip(1).ToArray(), stdout, stderr),
"trace" => RunTrace(args.Skip(1).ToArray(), stdout, stderr),
"canon" => RunCanon(args.Skip(1).ToArray(), stdout, stderr),
@@ -499,7 +502,7 @@ public static class CliRunner
return success ? 0 : 1;
}
- private static int RunView(string[] args, TextWriter stdout, TextWriter stderr)
+ private static int RunView(string[] args, TextWriter stdout, TextWriter stderr, ICadmataProcessLauncher launcher, string cliBaseDirectory)
{
if (args.Length == 0 || IsHelpFlag(args[0])) { WriteViewHelp(stdout); return args.Length == 0 ? 1 : 0; }
var input = args[0];
@@ -507,7 +510,7 @@ public static class CliRunner
var json = false;
for (var i = 1; i < args.Length; i++)
{
- if (args[i] == "--cad-assistant-path" && i + 1 < args.Length) { executable = args[++i]; continue; }
+ if ((args[i] == "--cadmata-path" || args[i] == "--cad-assistant-path") && i + 1 < args.Length) { executable = args[++i]; continue; }
if (args[i] == "--json") { json = true; continue; }
stderr.WriteLine($"Unknown view option '{args[i]}'."); stderr.WriteLine(ViewUsage); return 1;
}
@@ -525,27 +528,39 @@ public static class CliRunner
return 1;
}
stepPath = build.Value.OutputPath;
+ if (!json)
+ {
+ stdout.WriteLine($"✓ Built {Path.GetFileName(fullInput)}");
+ stdout.WriteLine($" STEP: {stepPath}");
+ stdout.WriteLine();
+ }
}
else if (string.Equals(extension, ".step", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".stp", StringComparison.OrdinalIgnoreCase)) stepPath = fullInput;
else { stderr.WriteLine("View expects Firmament (.firmament) or STEP (.step, .stp) input."); return 1; }
- var resolvedExecutable = CadAssistantInspection.ResolveExecutable(executable);
- if (resolvedExecutable is null)
+ var discovery = CadmataDiscovery.Resolve(executable, cliBaseDirectory);
+ if (discovery is null)
{
- const string message = "Cadmata/CAD Assistant was not found. Set --cad-assistant-path or AETHERIS_CAD_ASSISTANT_PATH.";
- if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "view", success = false, input = fullInput, output = stepPath, diagnostics = new[] { message } }, JsonOptions));
+ const string message = "Cadmata was not found. Install the packaged Cadmata host beside Aetheris, put it on PATH, or set --cadmata-path (AETHERIS_CADMATA_PATH; legacy AETHERIS_CAD_ASSISTANT_PATH is also supported).";
+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "view", success = false, source = string.Equals(extension, ".firmament", StringComparison.OrdinalIgnoreCase) ? fullInput : null, stepPath, cadmataPath = (string?)null, launched = false, diagnostics = new[] { message } }, JsonOptions));
else stderr.WriteLine(message);
return 1;
}
+ Process? process;
try
{
- var startInfo = new ProcessStartInfo(resolvedExecutable) { UseShellExecute = true };
- startInfo.ArgumentList.Add(stepPath);
- if (Process.Start(startInfo) is null) throw new InvalidOperationException("Process.Start returned no process.");
+ process = launcher.Launch(discovery.Path, stepPath);
+ if (process is null) throw new InvalidOperationException("Process.Start returned no process.");
+ }
+ catch (Exception ex)
+ {
+ var message = $"Could not open '{stepPath}' in Cadmata: {ex.Message}";
+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "view", success = false, source = string.Equals(extension, ".firmament", StringComparison.OrdinalIgnoreCase) ? fullInput : null, stepPath, cadmataPath = discovery.Path, launched = false, diagnostics = new[] { message } }, JsonOptions));
+ else stderr.WriteLine(message);
+ return 1;
}
- catch (Exception ex) { stderr.WriteLine($"Could not open '{stepPath}' in Cadmata/CAD Assistant: {ex.Message}"); return 1; }
- if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "view", success = true, input = fullInput, output = stepPath, launcher = resolvedExecutable }, JsonOptions));
- else stdout.WriteLine($"Opened {stepPath} in Cadmata/CAD Assistant.");
+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "view", success = true, source = string.Equals(extension, ".firmament", StringComparison.OrdinalIgnoreCase) ? fullInput : null, stepPath, cadmataPath = discovery.Path, launched = true, processId = process.Id, diagnostics = Array.Empty<string>() }, JsonOptions));
+ else stdout.WriteLine($"✓ Opened {Path.GetFileName(stepPath)} in Cadmata");
return 0;
}
@@ -2963,7 +2978,7 @@ public static class CliRunner
stdout.WriteLine("Commands:");
stdout.WriteLine(" validate Check Firmament source without materializing geometry.");
stdout.WriteLine(" build Compile Firmament to exact STEP AP242.");
- stdout.WriteLine(" view Build/open a model in Cadmata or CAD Assistant.");
+ stdout.WriteLine(" view Build/open a model in Cadmata.");
stdout.WriteLine(" inspect Inspect Firmament semantics or STEP topology.");
stdout.WriteLine(" analyze Analyze STEP topology and analytic surfaces.");
stdout.WriteLine(" verify Build/reimport and verify a model.");
@@ -3030,10 +3045,12 @@ public static class CliRunner
private static void WriteViewHelp(TextWriter stdout)
{
- stdout.WriteLine("Open a STEP model in Cadmata/CAD Assistant.");
+ stdout.WriteLine("Open a STEP model in Cadmata.");
stdout.WriteLine("Firmament input is built to its adjacent .step artifact before launch; STEP input opens directly.");
stdout.WriteLine();
stdout.WriteLine(ViewUsage);
+ stdout.WriteLine(" --cadmata-path <path> Explicit Cadmata executable (legacy --cad-assistant-path is accepted). Otherwise packaged siblings, environment compatibility settings, PATH, and a development build are checked.");
+ stdout.WriteLine(" --json Emit launch details without waiting for Cadmata to exit.");
stdout.WriteLine("Example: aetheris view part.firmament");
}
diff --git a/Aetheris.CLI/Properties/AssemblyInfo.cs b/Aetheris.CLI/Properties/AssemblyInfo.cs
new file mode 100644
index 00000000..85dc7d74
--- /dev/null
+++ b/Aetheris.CLI/Properties/AssemblyInfo.cs
@@ -0,0 +1,3 @@
+using System.Runtime.CompilerServices;
+
+[assembly: InternalsVisibleTo("Aetheris.CLI.Tests")]
diff --git a/Aetheris.Server.Tests/CadmataStartupTests.cs b/Aetheris.Server.Tests/CadmataStartupTests.cs
new file mode 100644
index 00000000..45c7ca24
--- /dev/null
+++ b/Aetheris.Server.Tests/CadmataStartupTests.cs
@@ -0,0 +1,102 @@
+using System.Net;
+using System.Net.Http.Json;
+using Aetheris.Server.Contracts;
+using Aetheris.Server.Startup;
+using Microsoft.AspNetCore.Mvc.Testing;
+using Microsoft.AspNetCore.TestHost;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.DependencyInjection.Extensions;
+
+namespace Aetheris.Server.Tests;
+
+public sealed class CadmataStartupTests
+{
+ [Fact]
+ public void Parse_NormalizesRelativeUnicodePathWithSpaces()
+ {
+ var directory = Path.Combine(Path.GetTempPath(), "Cadmata startup ü " + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(directory);
+ try
+ {
+ var step = Path.Combine(directory, "nested part.stp");
+ File.WriteAllText(step, "ISO-10303-21;");
+ var relative = Path.GetRelativePath(Directory.GetCurrentDirectory(), step);
+
+ var options = CadmataLaunchOptions.Parse([relative, "--no-browser"]);
+
+ Assert.NotNull(options.Step);
+ Assert.Equal(Path.GetFullPath(step), options.Step!.Path);
+ Assert.Equal("nested part.stp", options.Step.FileName);
+ Assert.Equal("ISO-10303-21;", options.Step.StepText);
+ Assert.True(options.NoBrowser);
+ }
+ finally
+ {
+ Directory.Delete(directory, recursive: true);
+ }
+ }
+
+ [Fact]
+ public void Parse_RejectsMissingAndInvalidStartupFilesClearly()
+ {
+ var missing = Assert.Throws<CadmataLaunchException>(() => CadmataLaunchOptions.Parse(["missing.step"]));
+ Assert.Contains("not found", missing.Message, StringComparison.OrdinalIgnoreCase);
+
+ var invalid = Path.Combine(Path.GetTempPath(), $"invalid-{Guid.NewGuid():N}.txt");
+ File.WriteAllText(invalid, "not step");
+ try
+ {
+ var exception = Assert.Throws<CadmataLaunchException>(() => CadmataLaunchOptions.Parse([invalid]));
+ Assert.Contains(".step or .stp", exception.Message, StringComparison.Ordinal);
+ }
+ finally { File.Delete(invalid); }
+ }
+
+ [Fact]
+ public void ValidateProductionAssets_RequiresPackagedIndexForStartupOpen()
+ {
+ var directory = Path.Combine(Path.GetTempPath(), "Cadmata assets " + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(directory);
+ try
+ {
+ var options = new CadmataLaunchOptions(
+ new CadmataStartupStepContent("C:\\Models\\plate.step", "plate.step", "ISO-10303-21;"),
+ NoBrowser: false,
+ HasExplicitUrls: false);
+
+ var missing = Assert.Throws<CadmataLaunchException>(() => options.ValidateProductionAssets(directory));
+ Assert.Contains("Production frontend assets", missing.Message, StringComparison.Ordinal);
+
+ Directory.CreateDirectory(Path.Combine(directory, "wwwroot"));
+ File.WriteAllText(Path.Combine(directory, "wwwroot", "index.html"), "<!doctype html>");
+ options.ValidateProductionAssets(directory);
+
+ new CadmataLaunchOptions(null, false, false).ValidateProductionAssets(Path.Combine(directory, "missing"));
+ }
+ finally
+ {
+ Directory.Delete(directory, recursive: true);
+ }
+ }
+
+ [Fact]
+ public async Task StartupEndpoint_ReturnsConfiguredStepExactlyOnce()
+ {
+ var content = new CadmataStartupStepContent("C:\\Models\\plate.step", "plate.step", "ISO-10303-21;");
+ await using var factory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
+ builder.ConfigureTestServices(services =>
+ {
+ services.RemoveAll<CadmataStartupStep>();
+ services.AddSingleton(new CadmataStartupStep(content));
+ }));
+ using var client = factory.CreateClient();
+
+ var first = await client.PostAsync("/api/v1/startup/step", null);
+ first.EnsureSuccessStatusCode();
+ var envelope = await first.Content.ReadFromJsonAsync<ApiResponseDto<CadmataStartupStepContent>>();
+ Assert.Equal(content, envelope!.Data);
+
+ var second = await client.PostAsync("/api/v1/startup/step", null);
+ Assert.Equal(HttpStatusCode.NoContent, second.StatusCode);
+ }
+}
diff --git a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
index 7c85f9a0..f62e7f4d 100644
--- a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
+++ b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
@@ -87,7 +87,7 @@ public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFact
}
[Fact]
- public async Task DisplayPrepare_BoxCylinderThroughHole_UsesAnalyticLaneWithoutTessellationFallback()
+ public async Task DisplayPrepare_BoxCylinderThroughHole_SuppliesTrimmedPlanarFallbacks()
{
var document = await CreateDocumentAsync("/api/v1/documents");
var box = await CreateBoxAsync("/api/v1/documents", document.Data!.DocumentId, 40, 30, 12);
@@ -119,7 +119,17 @@ public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFact
Assert.NotEmpty(prepared.Data.AnalyticPacket.AnalyticFaces);
Assert.Contains(prepared.Data.AnalyticPacket.AnalyticFaces, face => face.SurfaceKind == "Cylinder");
Assert.Empty(prepared.Data.AnalyticPacket.FallbackFaces);
- Assert.Null(prepared.Data.TessellationFallback);
+ Assert.NotNull(prepared.Data.TessellationFallback);
+ var trimmedPlanes = prepared.Data.AnalyticPacket.AnalyticFaces
+ .Where(face => face.SurfaceKind == "Plane" && face.LoopCount > 1)
+ .ToArray();
+ Assert.Equal(2, trimmedPlanes.Length);
+ foreach (var face in trimmedPlanes)
+ {
+ var fallback = Assert.Single(prepared.Data.TessellationFallback!.FacePatches, patch => patch.FaceId == face.FaceId);
+ Assert.NotEmpty(fallback.Positions);
+ Assert.NotEmpty(fallback.TriangleIndices);
+ }
}
[Fact]
diff --git a/Aetheris.Server/Aetheris.Server.csproj b/Aetheris.Server/Aetheris.Server.csproj
index f3b31072..66c771e0 100644
--- a/Aetheris.Server/Aetheris.Server.csproj
+++ b/Aetheris.Server/Aetheris.Server.csproj
@@ -1,9 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
+ <OutputType>WinExe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
+ <AssemblyName>Cadmata</AssemblyName>
<SpaRoot>..\aetheris.client\</SpaRoot>
<SpaProxyServerUrl>https://localhost:5173</SpaProxyServerUrl>
<SpaProxyLaunchCommand>npm run dev</SpaProxyLaunchCommand>
@@ -21,4 +23,8 @@
<ProjectReference Include="..\Aetheris.Kernel.Firmament\Aetheris.Kernel.Firmament.csproj" />
</ItemGroup>
+ <ItemGroup Condition="Exists('$(SpaRoot)dist')">
+ <Content Include="$(SpaRoot)dist\**" Link="wwwroot\%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
+ </ItemGroup>
+
</Project>
diff --git a/Aetheris.Server/Api/KernelEndpoints.cs b/Aetheris.Server/Api/KernelEndpoints.cs
index e4173978..6d1ac520 100644
--- a/Aetheris.Server/Api/KernelEndpoints.cs
+++ b/Aetheris.Server/Api/KernelEndpoints.cs
@@ -310,8 +310,10 @@ public static class KernelEndpoints
TessellationResponseDto? tessellationFallback = null;
DisplayTessellationResult? boundedMeshResult = null;
var displayDiagnostics = new List<DisplayDiagnosticDto>();
+ var needsTrimmedAnalyticFallback = analyticDto.AnalyticFaces.Any(face =>
+ face.SurfaceKind == "Plane" && face.LoopCount > 1);
- if (lane is not "analytic-only")
+ if (lane is not "analytic-only" || needsTrimmedAnalyticFallback)
{
var options = ApiMappings.BuildTessellationOptions(request?.TessellationOptions);
var completeBoundedMesh = DisplayPreparationFallbackBuilder.Build(body, options);
diff --git a/Aetheris.Server/Program.cs b/Aetheris.Server/Program.cs
index 340be2e3..5b2fa489 100644
--- a/Aetheris.Server/Program.cs
+++ b/Aetheris.Server/Program.cs
@@ -1,8 +1,40 @@
using Aetheris.Server.Api;
using Aetheris.Server.Configuration;
using Aetheris.Server.Documents;
+using Aetheris.Server.Startup;
+using Microsoft.AspNetCore.Hosting.Server;
+using Microsoft.AspNetCore.Hosting.Server.Features;
+using System.Diagnostics;
-var builder = WebApplication.CreateBuilder(args);
+CadmataLaunchOptions launchOptions;
+try
+{
+ launchOptions = CadmataLaunchOptions.Parse(args);
+ launchOptions.ValidateProductionAssets(AppContext.BaseDirectory);
+}
+catch (CadmataLaunchException exception)
+{
+ Console.Error.WriteLine($"Cadmata could not start: {exception.Message}");
+ return 2;
+}
+
+var builder = WebApplication.CreateBuilder(new WebApplicationOptions
+{
+ Args = args,
+ ContentRootPath = AppContext.BaseDirectory,
+});
+
+if (launchOptions.Step is not null && !launchOptions.HasExplicitUrls)
+{
+ builder.WebHost.UseUrls("http://127.0.0.1:0");
+}
+
+if (launchOptions.Step is not null)
+{
+ // The CLI intentionally returns after process creation. Keep the detached
+ // host from retaining noisy per-request console output in redirected pipes.
+ builder.Logging.ClearProviders();
+}
var stepUploadOptions = builder.Configuration
.GetSection(StepUploadOptions.SectionName)
@@ -18,6 +50,7 @@ builder.Services.AddSingleton(stepUploadOptions);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<KernelDocumentStore>();
+builder.Services.AddSingleton(new CadmataStartupStep(launchOptions.Step));
var app = builder.Build();
@@ -28,7 +61,43 @@ if (app.Environment.IsDevelopment())
}
app.MapKernelApi();
+app.MapCadmataStartupApi();
+
+app.UseDefaultFiles();
+app.UseStaticFiles();
+app.MapFallbackToFile("index.html");
+
+if (launchOptions.Step is null)
+{
+ app.Run();
+ return 0;
+}
+
+await app.StartAsync();
+var addresses = app.Services.GetRequiredService<IServer>()
+ .Features.Get<IServerAddressesFeature>()?.Addresses;
+var address = addresses?.FirstOrDefault(static value => value.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
+ ?? app.Urls.FirstOrDefault()
+ ?? throw new InvalidOperationException("Cadmata started without a browser address.");
+
+Console.WriteLine($"Cadmata ready: {address}");
+Console.WriteLine($"Opening: {launchOptions.Step.Path}");
+
+if (!launchOptions.NoBrowser)
+{
+ try
+ {
+ Process.Start(new ProcessStartInfo(address) { UseShellExecute = true });
+ }
+ catch (Exception exception)
+ {
+ Console.Error.WriteLine($"Cadmata could not open the default browser: {exception.Message}");
+ await app.StopAsync();
+ return 3;
+ }
+}
-app.Run();
+await app.WaitForShutdownAsync();
+return 0;
public partial class Program;
diff --git a/Aetheris.Server/Startup/CadmataLaunchOptions.cs b/Aetheris.Server/Startup/CadmataLaunchOptions.cs
new file mode 100644
index 00000000..18c97ff5
--- /dev/null
+++ b/Aetheris.Server/Startup/CadmataLaunchOptions.cs
@@ -0,0 +1,104 @@
+namespace Aetheris.Server.Startup;
+
+public sealed class CadmataLaunchException(string message) : Exception(message);
+
+public sealed record CadmataStartupStepContent(string Path, string FileName, string StepText);
+
+public sealed record CadmataLaunchOptions(CadmataStartupStepContent? Step, bool NoBrowser, bool HasExplicitUrls)
+{
+ public void ValidateProductionAssets(string applicationDirectory)
+ {
+ if (Step is null)
+ {
+ return;
+ }
+
+ var indexPath = Path.Combine(Path.GetFullPath(applicationDirectory), "wwwroot", "index.html");
+ if (!File.Exists(indexPath))
+ {
+ throw new CadmataLaunchException(
+ $"Production frontend assets were not found beside Cadmata: {indexPath}. " +
+ "Reinstall the Cadmata package or build aetheris.client before building the host.");
+ }
+ }
+
+ public static CadmataLaunchOptions Parse(string[] args)
+ {
+ string? stepPath = null;
+ var noBrowser = false;
+ var hasExplicitUrls = false;
+
+ for (var index = 0; index < args.Length; index++)
+ {
+ var argument = args[index];
+ if (string.Equals(argument, "--no-browser", StringComparison.Ordinal))
+ {
+ noBrowser = true;
+ continue;
+ }
+
+ if (string.Equals(argument, "--urls", StringComparison.OrdinalIgnoreCase))
+ {
+ hasExplicitUrls = true;
+ index++;
+ continue;
+ }
+
+ if (argument.StartsWith("--urls=", StringComparison.OrdinalIgnoreCase))
+ {
+ hasExplicitUrls = true;
+ continue;
+ }
+
+ if (argument.StartsWith("--", StringComparison.Ordinal))
+ {
+ continue;
+ }
+
+ if (stepPath is not null)
+ {
+ throw new CadmataLaunchException("Only one STEP path may be supplied.");
+ }
+
+ stepPath = argument;
+ }
+
+ if (stepPath is null)
+ {
+ return new CadmataLaunchOptions(null, noBrowser, hasExplicitUrls);
+ }
+
+ var fullPath = Path.GetFullPath(stepPath);
+ var extension = Path.GetExtension(fullPath);
+ if (!string.Equals(extension, ".step", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(extension, ".stp", StringComparison.OrdinalIgnoreCase))
+ {
+ throw new CadmataLaunchException($"Startup file must use .step or .stp: {fullPath}");
+ }
+
+ if (!File.Exists(fullPath))
+ {
+ throw new CadmataLaunchException($"STEP file was not found: {fullPath}");
+ }
+
+ string stepText;
+ try
+ {
+ stepText = File.ReadAllText(fullPath);
+ }
+ catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
+ {
+ throw new CadmataLaunchException($"STEP file could not be read: {exception.Message}");
+ }
+
+ if (string.IsNullOrWhiteSpace(stepText))
+ {
+ throw new CadmataLaunchException($"STEP file is empty: {fullPath}");
+ }
+
+ return new CadmataLaunchOptions(
+ new CadmataStartupStepContent(fullPath, Path.GetFileName(fullPath), stepText),
+ noBrowser,
+ hasExplicitUrls);
+ }
+}
diff --git a/Aetheris.Server/Startup/CadmataStartupStep.cs b/Aetheris.Server/Startup/CadmataStartupStep.cs
new file mode 100644
index 00000000..6ac003a9
--- /dev/null
+++ b/Aetheris.Server/Startup/CadmataStartupStep.cs
@@ -0,0 +1,24 @@
+using Aetheris.Server.Api;
+
+namespace Aetheris.Server.Startup;
+
+public sealed class CadmataStartupStep(CadmataStartupStepContent? content)
+{
+ private CadmataStartupStepContent? _content = content;
+
+ public CadmataStartupStepContent? Claim() => Interlocked.Exchange(ref _content, null);
+}
+
+public static class CadmataStartupApi
+{
+ public static IEndpointRouteBuilder MapCadmataStartupApi(this IEndpointRouteBuilder endpoints)
+ {
+ endpoints.MapPost("/api/v1/startup/step", (CadmataStartupStep startup) =>
+ {
+ var content = startup.Claim();
+ return content is null ? Results.NoContent() : ApiMappings.Ok(content);
+ });
+
+ return endpoints;
+ }
+}
diff --git a/Aetheris.Server/wwwroot/.gitkeep b/Aetheris.Server/wwwroot/.gitkeep
new file mode 100644
index 00000000..8b137891
--- /dev/null
+++ b/Aetheris.Server/wwwroot/.gitkeep
@@ -0,0 +1 @@
+
diff --git a/aetheris.client/src/App.tsx b/aetheris.client/src/App.tsx
index 22d9feca..91f1a2b5 100644
--- a/aetheris.client/src/App.tsx
+++ b/aetheris.client/src/App.tsx
@@ -1,7 +1,8 @@
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import './App.css';
import {
ApiError,
+ claimStartupStep,
createBox,
createDocument,
executeBoolean,
@@ -129,6 +130,7 @@ function App() {
const [cadmataArtifact, setCadmataArtifact] = useState<CadmataVisualizationArtifact | null>(null);
const [cadmataLayers, setCadmataLayers] = useState<CadmataLayerVisibility>(DEFAULT_CADMATA_LAYERS);
const [selectedCadmataId, setSelectedCadmataId] = useState<string | null>(null);
+ const startupStepClaimed = useRef(false);
const resetSessionState = useCallback(() => {
setBodyIds([]);
@@ -249,6 +251,8 @@ function App() {
}, [createFreshDocument, resetSessionState]);
useEffect(() => {
+ // Document creation is the startup synchronization with the server.
+ // eslint-disable-next-line react-hooks/set-state-in-effect
void handleCreateDocument();
}, [handleCreateDocument]);
@@ -391,32 +395,10 @@ function App() {
}
}, [stepCanonicalHash]);
- const handleImportStep = useCallback(async () => {
- if (!documentId || !stepImportFile || documentStatus !== 'ready' || serverStatus !== 'connected') {
- return;
- }
-
- if (stepImportFile.size <= 0) {
- setStatus('error');
- setStatusMessage('Selected STEP file is empty.');
- setDiagnostics([]);
- setImportStatus('error');
- setImportStatusMessage('Import error: Selected STEP file is empty.');
- return;
- }
-
- if (stepImportFile.size > STEP_UPLOAD_LIMIT_BYTES) {
- const limitMessage = `Selected STEP file is too large (${formatMegabytes(stepImportFile.size)}). Limit is ${STEP_UPLOAD_LIMIT_MB} MB.`;
- setStatus('error');
- setStatusMessage(limitMessage);
- setDiagnostics([]);
- setImportStatus('error');
- setImportStatusMessage(`Import error: ${limitMessage}`);
- return;
- }
-
+ const importStepText = useCallback(async (stepText: string, fileName: string) => {
+ if (!documentId || documentStatus !== 'ready' || serverStatus !== 'connected') return;
setImportStatus('importing');
- setImportStatusMessage('Importing STEP…');
+ setImportStatusMessage(`Importing ${fileName}…`);
setIsImporting(true);
setDiagnostics([]);
@@ -424,12 +406,11 @@ function App() {
setStatus('loading');
setStatusMessage('Import STEP...');
- const stepText = await stepImportFile.text();
if (stepText.trim().length === 0) {
throw new ApiError('Selected STEP file is empty.', []);
}
- const imported = await importStep(documentId, stepText);
+ const imported = await importStep(documentId, stepText, fileName);
setStepExportText('');
const displayRefresh = await refreshSummaryAndActiveTessellation(imported.occurrenceId, true);
const exported = await exportDefinitionStep(documentId, imported.definitionId);
@@ -464,13 +445,56 @@ function App() {
} finally {
setIsImporting(false);
}
- }, [documentId, documentStatus, refreshSummaryAndActiveTessellation, serverStatus, stepImportFile]);
+ }, [documentId, documentStatus, refreshSummaryAndActiveTessellation, serverStatus]);
+
+ const handleImportStep = useCallback(async () => {
+ if (!stepImportFile) return;
+
+ if (stepImportFile.size <= 0) {
+ setStatus('error');
+ setStatusMessage('Selected STEP file is empty.');
+ setDiagnostics([]);
+ setImportStatus('error');
+ setImportStatusMessage('Import error: Selected STEP file is empty.');
+ return;
+ }
+
+ if (stepImportFile.size > STEP_UPLOAD_LIMIT_BYTES) {
+ const limitMessage = `Selected STEP file is too large (${formatMegabytes(stepImportFile.size)}). Limit is ${STEP_UPLOAD_LIMIT_MB} MB.`;
+ setStatus('error');
+ setStatusMessage(limitMessage);
+ setDiagnostics([]);
+ setImportStatus('error');
+ setImportStatusMessage(`Import error: ${limitMessage}`);
+ return;
+ }
+
+ await importStepText(await stepImportFile.text(), stepImportFile.name);
+ }, [importStepText, stepImportFile]);
+
+ useEffect(() => {
+ if (startupStepClaimed.current || !documentId || documentStatus !== 'ready' || serverStatus !== 'connected') return;
+ startupStepClaimed.current = true;
+
+ void (async () => {
+ try {
+ const startupStep = await claimStartupStep();
+ if (startupStep) await importStepText(startupStep.stepText, startupStep.fileName);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : 'Startup STEP could not be loaded.';
+ setStatus('error');
+ setStatusMessage(message);
+ setImportStatus('error');
+ setImportStatusMessage(`Import error: ${message}`);
+ }
+ })();
+ }, [documentId, documentStatus, importStepText, serverStatus]);
const handleStepFileAccepted = useCallback((selected: File) => {
setStepImportFile(selected);
}, []);
- const handleStepFileValidationError = useCallback((_message: string) => {
+ const handleStepFileValidationError = useCallback(() => {
setStepImportFile(null);
}, []);
diff --git a/aetheris.client/src/__tests__/App.test.tsx b/aetheris.client/src/__tests__/App.test.tsx
index 32593503..1e047d5f 100644
--- a/aetheris.client/src/__tests__/App.test.tsx
+++ b/aetheris.client/src/__tests__/App.test.tsx
@@ -6,6 +6,7 @@ import { STEP_UPLOAD_LIMIT_BYTES } from '../config/stepUpload';
const apiMocks = vi.hoisted(() => ({
createDocument: vi.fn(),
+ claimStartupStep: vi.fn(),
createBox: vi.fn(),
executeBoolean: vi.fn(),
exportDefinitionStep: vi.fn(),
@@ -23,6 +24,7 @@ vi.mock('../api/aetherisApi', async () => {
return {
...actual,
createDocument: apiMocks.createDocument,
+ claimStartupStep: apiMocks.claimStartupStep,
createBox: apiMocks.createBox,
executeBoolean: apiMocks.executeBoolean,
exportDefinitionStep: apiMocks.exportDefinitionStep,
@@ -41,6 +43,7 @@ vi.mock('../viewer/AetherisViewport', () => ({
function setupDocumentApiMocks(): void {
apiMocks.createDocument.mockResolvedValue({ documentId: 'doc-1', name: 'Test', volatile: true });
+ apiMocks.claimStartupStep.mockResolvedValue(null);
apiMocks.createBox.mockResolvedValue({
documentId: 'doc-1',
bodyId: 'occ-2',
@@ -110,6 +113,39 @@ describe('App STEP file upload flow', () => {
expect(apiMocks.createDocument).toHaveBeenCalledTimes(1);
});
+ it('claims and imports a startup STEP only after the workspace is ready', async () => {
+ apiMocks.claimStartupStep.mockResolvedValue({ path: 'C:\\Models\\startup.step', fileName: 'startup.step', stepText: 'ISO-10303-21;' });
+ apiMocks.importStep.mockResolvedValue({ documentId: 'doc-1', definitionId: 'def-2', occurrenceId: 'occ-2', name: 'startup.step', diagnostics: [] });
+ apiMocks.exportDefinitionStep.mockResolvedValue({ documentId: 'doc-1', definitionId: 'def-2', stepText: 'ISO-10303-21;', canonicalHash: 'startup-hash', diagnostics: [] });
+
+ render(<App />);
+
+ await waitFor(() => expect(apiMocks.claimStartupStep).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(apiMocks.importStep).toHaveBeenCalledTimes(1));
+ expect(apiMocks.createDocument.mock.invocationCallOrder[0]).toBeLessThan(apiMocks.claimStartupStep.mock.invocationCallOrder[0]);
+ expect(apiMocks.importStep).toHaveBeenCalledWith('doc-1', 'ISO-10303-21;', 'startup.step');
+ expect(apiMocks.claimStartupStep).toHaveBeenCalledTimes(1);
+ });
+
+ it('shows a readable startup STEP load failure', async () => {
+ apiMocks.claimStartupStep.mockResolvedValue({ path: 'C:\\Models\\bad.step', fileName: 'bad.step', stepText: 'BAD' });
+ apiMocks.importStep.mockRejectedValue(new ApiError('STEP payload could not be imported.', []));
+
+ render(<App />);
+
+ await waitFor(() => expect(apiMocks.importStep).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(screen.getAllByText('STEP payload could not be imported.').length).toBeGreaterThan(0));
+ expect(apiMocks.prepareBodyDisplay).not.toHaveBeenCalled();
+ });
+
+ it('keeps the ordinary empty viewer when no startup STEP exists', async () => {
+ render(<App />);
+
+ await screen.findByText('Ready. Select a file to import.');
+ expect(apiMocks.claimStartupStep).toHaveBeenCalledTimes(1);
+ expect(apiMocks.importStep).not.toHaveBeenCalled();
+ });
+
it('keeps canonical hash visible from viewer inspector', async () => {
apiMocks.importStep.mockResolvedValue({
documentId: 'doc-1',
@@ -275,7 +311,7 @@ describe('App STEP file upload flow', () => {
fireEvent.click(screen.getByRole('button', { name: 'Import STEP 242' }));
await waitFor(() => {
- expect(apiMocks.importStep).toHaveBeenCalledWith('doc-1', 'ISO-10303-21;DATA;');
+ expect(apiMocks.importStep).toHaveBeenCalledWith('doc-1', 'ISO-10303-21;DATA;', 'part.stp');
});
expect(apiMocks.exportDefinitionStep).toHaveBeenCalledWith('doc-1', 'def-2');
await screen.findByText('hash-123');
diff --git a/aetheris.client/src/api/aetherisApi.ts b/aetheris.client/src/api/aetherisApi.ts
index 4e037c2f..85964001 100644
--- a/aetheris.client/src/api/aetherisApi.ts
+++ b/aetheris.client/src/api/aetherisApi.ts
@@ -110,6 +110,12 @@ export interface AnalyticDisplayFaceDomainHintDto {
maxV: number | null;
}
+export interface StartupStepDto {
+ path: string;
+ fileName: string;
+ stepText: string;
+}
+
export interface AnalyticDisplayPlaneGeometryDto {
origin: Point3Dto;
normal: Vector3Dto;
@@ -396,4 +402,13 @@ export async function importStep(documentId: string, stepText: string, name?: st
});
}
+export async function claimStartupStep(): Promise<StartupStepDto | null> {
+ const response = await fetch('/api/v1/startup/step', { method: 'POST' });
+ if (response.status === 204) {
+ return null;
+ }
+
+ return parseEnvelope<StartupStepDto>(response);
+}
+
export { parseEnvelope };
diff --git a/aetheris.client/src/components/StepImportDropzone.tsx b/aetheris.client/src/components/StepImportDropzone.tsx
index 56066826..353aaa8a 100644
--- a/aetheris.client/src/components/StepImportDropzone.tsx
+++ b/aetheris.client/src/components/StepImportDropzone.tsx
@@ -146,6 +146,8 @@ export function StepImportDropzone({ resetToken, onFileAccepted, onValidationErr
const inputRef = useRef<HTMLInputElement | null>(null);
useEffect(() => {
+ // The parent token deliberately resets this component's local selection.
+ // eslint-disable-next-line react-hooks/set-state-in-effect
setSelectionMetadata(null);
setSelectionError(null);
}, [resetToken]);
diff --git a/aetheris.client/src/components/ui/button.tsx b/aetheris.client/src/components/ui/button.tsx
index 30074415..8796761a 100644
--- a/aetheris.client/src/components/ui/button.tsx
+++ b/aetheris.client/src/components/ui/button.tsx
@@ -30,4 +30,4 @@ function Button({ className, variant, size, ...props }: React.ComponentProps<'bu
return <button className={cn(buttonVariants({ variant, size, className }))} {...props} />;
}
-export { Button, buttonVariants };
+export { Button };
diff --git a/aetheris.client/src/viewer/AetherisViewport.tsx b/aetheris.client/src/viewer/AetherisViewport.tsx
index 2206d888..88cac911 100644
--- a/aetheris.client/src/viewer/AetherisViewport.tsx
+++ b/aetheris.client/src/viewer/AetherisViewport.tsx
@@ -170,6 +170,8 @@ function DraftingGrid() {
bounds,
layerEnvelopes,
} = useMemo(() => {
+ // The camera is mutable; this snapshot is the render-time invalidation key.
+ void cameraSnapshot;
const orthographicCamera = camera as OrthographicCamera;
// Use frustum-based corner projection instead of raycaster
@@ -608,6 +610,7 @@ function FitCameraToScene({ displayScene }: { displayScene: DisplayScene | null
return;
}
+ /* eslint-disable react-hooks/immutability -- Three.js cameras are imperative renderer-owned objects. */
camera.position.set(...fit.position);
camera.zoom = fit.zoom;
camera.near = fit.near;
@@ -615,6 +618,7 @@ function FitCameraToScene({ displayScene }: { displayScene: DisplayScene | null
camera.lookAt(...fit.target);
camera.updateProjectionMatrix();
camera.updateMatrixWorld(false);
+ /* eslint-enable react-hooks/immutability */
if (controls && typeof controls === 'object' && 'target' in controls) {
const orbitControls = controls as { target: Vector3; update?: () => void };
diff --git a/aetheris.client/src/viewer/CadmataOverlay.tsx b/aetheris.client/src/viewer/CadmataOverlay.tsx
index 8251a8f5..2e028c19 100644
--- a/aetheris.client/src/viewer/CadmataOverlay.tsx
+++ b/aetheris.client/src/viewer/CadmataOverlay.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-refresh/only-export-components -- layer contracts and the overlay intentionally share one small module. */
import { Line } from '@react-three/drei';
import { useMemo } from 'react';
import { DoubleSide, Vector3 } from 'three';
diff --git a/aetheris.client/tailwind.config.ts b/aetheris.client/tailwind.config.ts
index 31e8975a..55ef95f8 100644
--- a/aetheris.client/tailwind.config.ts
+++ b/aetheris.client/tailwind.config.ts
@@ -1,4 +1,5 @@
import type { Config } from 'tailwindcss';
+import tailwindcssAnimate from 'tailwindcss-animate';
export default {
darkMode: ['class'],
@@ -30,5 +31,5 @@ export default {
},
},
},
- plugins: [require('tailwindcss-animate')],
+ plugins: [tailwindcssAnimate],
} satisfies Config;
diff --git a/docs/release/p1-cadmata-m1.md b/docs/release/p1-cadmata-m1.md
new file mode 100644
index 00000000..5dab6d6b
--- /dev/null
+++ b/docs/release/p1-cadmata-m1.md
@@ -0,0 +1,91 @@
+# P1-CADMATA-M1 release hardening
+
+## Architecture and Preview 1 contract
+
+Cadmata is the `aetheris.client` React 19/TypeScript/Vite 7 single-page
+application hosted by `Aetheris.Server`. The server owns document/import and
+display-preparation APIs; the client converts DisplayIR to `DisplayScene` and
+renders it with React Three Fiber/Three.js. `FitCameraToScene` already fits a
+new scene using the pure bounds helpers in `displaySceneBounds.ts`.
+
+Preview 1 uses one deliberately narrow launch contract:
+
+```text
+Cadmata.exe <absolute-file.step>
+```
+
+The host validates and reads one `.step`/`.stp`, serves the existing Vite
+production bundle on an ephemeral loopback address, and exposes the startup
+content once through `POST /api/v1/startup/step`. After Cadmata creates its
+ordinary document and the renderer is ready, `App` claims that intent and runs
+the same import/display transition used by browser file-open. A missing file,
+invalid extension, unreadable/empty STEP, missing production bundle, browser
+launch failure, import failure, or display failure produces a bounded readable
+diagnostic. No daemon, fixed port, dev server, or singleton IPC is involved.
+
+## CLI path and discovery
+
+`aetheris view source.firmament` builds the adjacent STEP first and does not
+launch after a failed build. `aetheris view artifact.step` or `.stp` skips the
+compiler. In both cases the CLI normalizes the handoff to an absolute path,
+starts Cadmata, checks for an immediate exit for 250 ms, reports the handoff,
+and returns without supervising the viewer. Each command starts a new host.
+
+Discovery order is:
+
+1. `--cadmata-path` (legacy `--cad-assistant-path` remains accepted)
+2. `AETHERIS_CADMATA_PATH`
+3. compatibility `AETHERIS_CAD_ASSISTANT_PATH`
+4. `Cadmata.exe` beside the CLI
+5. `cadmata/Cadmata.exe`, then `tools/cadmata/Cadmata.exe`, relative to the CLI
+6. `Cadmata` on `PATH`
+7. a Release/Debug `Aetheris.Server` source-build fallback
+
+## Production and smoke evidence
+
+The host content root is its executable directory. Vite `dist` is copied to
+`wwwroot` for build/publish, and the host serves default/static files plus the
+SPA fallback. The release-like smoke used this isolated shape:
+
+```text
+bundle/
+ aetheris.exe
+ cadmata/
+ Cadmata.exe
+ Cadmata.dll and runtime files
+ wwwroot/index.html and hashed assets
+```
+
+The bundle ran outside the repository from a temporary `Aetheris Smoke ...`
+directory. Relative and absolute source/STEP inputs, nested directories,
+spaces, Unicode, `.step`, and `.stp` were exercised. Source view produced its
+adjacent STEP; direct STEP view did not build. Package-relative discovery
+selected `bundle/cadmata/Cadmata.exe` without environment configuration.
+
+The actual GUI smoke imported `box-hole-pmi.firmament` as `plate ü.step`.
+It exposed and then verified a real display defect: the two multi-loop planar
+faces had analytic metadata but no renderable bounded polygon, so the client
+dropped them. Display preparation now supplies the existing tessellated
+fallback for those trimmed planes. The corrected GUI showed one solid plate,
+the round through-hole, and usable initial framing. Browser inspection found no
+console error or failed resource request; Three.js emitted one upstream
+`THREE.Clock` deprecation warning.
+
+Measured on this development machine, the final isolated direct-STEP CLI
+handoff returned in 402 ms; the Firmament build plus handoff returned in
+1,157 ms. Document readiness took 51 ms and STEP import plus display
+preparation took 234 ms in the running production host. The browser smoke was
+visibly usable within about 2.5 seconds; that last number includes browser
+navigation and observation overhead, not only renderer work.
+
+## Packaging boundary and future work
+
+P1-PACKAGE-M1 should build the Vite bundle before publishing the host and place
+the complete host under `cadmata` beside `aetheris`. The current conditional
+MSBuild copy is preparation, not the final NuGet build graph. The browser-host,
+`WinExe` detachment, compatibility names, and one-shot startup endpoint are
+Preview 1 compromises. The concrete post-release refactor record is
+`docs/roadmap/cadmata-post-preview1-refactor-notes.md`; it covers the future
+MachinaLayout.js application shell, TSPack consolidation, document state,
+renderer boundary, packaging, and preserved test seams without implementing
+that redesign here.
diff --git a/docs/roadmap/cadmata-post-preview1-refactor-notes.md b/docs/roadmap/cadmata-post-preview1-refactor-notes.md
new file mode 100644
index 00000000..b84e4f34
--- /dev/null
+++ b/docs/roadmap/cadmata-post-preview1-refactor-notes.md
@@ -0,0 +1,187 @@
+# Cadmata post-Preview-1 refactor notes
+
+This document records concrete seams observed while hardening the Preview 1
+`aetheris view` path. It is intentionally a roadmap, not authorization to
+redesign Cadmata during the Preview 1 freeze.
+
+## Current architecture snapshot
+
+- `aetheris.client` is a React 19 + TypeScript 5.9 single-page application
+ built by Vite 7. `src/main.tsx` mounts the single `App` component.
+- `Aetheris.Server` is the ASP.NET Core host. `Program.cs` configures Kestrel,
+ the in-memory `KernelDocumentStore`, and `/api/v1` kernel/document routes.
+ Before Preview 1 hardening it did not serve the Vite production bundle.
+- `App.tsx` owns application shell, document creation, STEP import/export,
+ active occurrence, display preparation, picking, demo modeling state,
+ diagnostics, and most presentation state in one component.
+- STEP import currently flows through `StepImportDropzone` -> browser `File`
+ -> `File.text()` -> `importStep` -> document summary/display preparation ->
+ `buildDisplaySceneData` -> `AetherisViewport`.
+- The renderer boundary is reasonably explicit: API DTOs are converted to a
+ framework-independent-ish `DisplayScene`, then `AetherisViewport` maps its
+ renderables to React Three Fiber nodes.
+- Camera fitting already exists in `FitCameraToScene`, backed by pure helpers
+ in `viewer/displaySceneBounds.ts`, and runs when `displayScene` changes.
+- Development assumes Vite HTTPS on port 5173 proxying `/api` to the ASP.NET
+ HTTPS development endpoint. Those assumptions belong only to `npm run dev`.
+
+## Pain points observed during Preview 1 hardening
+
+- The public CLI called an arbitrary external program labelled both “Cadmata”
+ and “CAD Assistant”; the repository's actual Cadmata React/server stack had
+ no executable file-open entry point.
+- `App.tsx` couples document lifecycle, import lifecycle, viewer selection,
+ modeling-demo state, status copy, and layout. Startup-open therefore has to
+ join a large component even though it is conceptually one document intent.
+- Browser-selected files and process-supplied files enter through different
+ transport mechanisms but need the same import/display state transition.
+ Keep the transition shared; do not let process arguments leak into renderer
+ code.
+- The Vite configuration contains certificate creation and fixed-port proxy
+ behavior alongside production bundle configuration. This is useful in
+ development but makes the production boundary harder to see.
+- Display preparation classified an all-analytic through-hole body as needing
+ no bounded fallback, even though multi-loop planar analytic DTOs intentionally
+ omit a simple outer polygon. The renderer then dropped the two holed faces.
+ Preview 1 now requests bounded patches for that narrow case; a future display
+ contract should declare per-face render requirements instead of making the
+ client infer them from loop count.
+
+## MachinaLayout.js migration candidates
+
+`machinalayout` is already a runtime dependency, but the current application
+shell remains hand-composed in `App.tsx`/`App.css`. Candidates below are based
+on inspected code, not a proposed wholesale port.
+
+| Current component/region | Current responsibility | Likely future composition | State dependency | Migration risk |
+| --- | --- | --- | --- | --- |
+| `App` shell | Header, tab switcher, workspace columns, status/footer | Application shell + vertical stack | Nearly all app state | High; split state first |
+| Viewer workspace | Viewport plus import/inspection controls | Resizable main viewport and sidebar | Document/import/display state | Medium |
+| STEP import panel | Dropzone, import action, import status | Panel/form composition | File and import lifecycle | Low |
+| Inspector/status panels | Body metadata, diagnostics, display status | Inspector/property panels | Active occurrence and display DTOs | Medium |
+| Modeling demo | Box/transform/Boolean controls | Separate routed/tool panel | Demo-only state | Medium; avoid contaminating viewer shell |
+| Viewport overlays | Grid/axis and future transient controls | Overlay slots | Viewer-local state | Low if renderer stays isolated |
+
+## TSPack migration/consolidation opportunities
+
+- Cadmata currently uses `package.json`/npm scripts directly and has no TSPack
+ manifest or workspace seam in this repository.
+- A future migration could make dependency synchronization, locked production
+ builds, policy/security checks, and the .NET publish prerequisite one
+ reproducible workflow. Preview 1 should not invent that migration.
+- The important integration point is artifact production: generate `dist`
+ once, then copy it into the Cadmata host publish output. Keep Vite-specific
+ commands out of CLI runtime discovery.
+- Preserve the existing `build`, `test`, and `lint` behavioral boundaries so a
+ future TSPack task can wrap or replace tooling without changing app logic.
+- The public manual's `docs-sync` currently emits plain `JSON.stringify`
+ output that needs one `tspack format` pass before `tspack check --format`.
+ A future consolidated build should make generated artifacts formatter-stable
+ so sync followed by check is idempotent.
+
+## State-management cleanup
+
+- Extract a document/session controller from `App.tsx`: create/reset document,
+ import STEP, refresh summary/display, and expose one typed state machine.
+- Model import as explicit states (`idle`, `selected`, `importing`, `loaded`,
+ `display-failed`, `failed`) rather than coordinating `status`,
+ `importStatus`, booleans, and multiple message strings.
+- Keep browser file selection as an adapter that yields `{name, stepText}`.
+ Startup open should yield the same shape through a host adapter.
+- Demo modeling controls should own their state outside the viewer/document
+ state so the default Cadmata path does not initialize unrelated concerns.
+
+## Renderer/application boundary
+
+- Preserve `DisplayScene` and the pure mapping/bounds helpers. They provide a
+ valuable seam between server DTOs and React Three Fiber.
+- Make camera-fit an explicit renderer command or scene-load policy in a later
+ design, while retaining the tested pure fit calculation.
+- Keep the renderer ignorant of process arguments, filesystem paths, Kestrel,
+ and document transport. It should receive a scene and interaction callbacks.
+- `AetherisViewport` still combines scene materialization, grid/axis helpers,
+ picking, overlays, lighting, camera, and controls. Split only when the future
+ layout/application architecture defines stable ownership.
+
+## File/document lifecycle
+
+- Preview 1 startup STEP enters through the host, is exposed as a single
+ startup-open intent, and is consumed by `App` after document creation. In a
+ proper refactor, make document-open intent a first-class application state
+ transition and keep the renderer adapter ignorant of process arguments.
+- Define cancellation/replacement semantics before adding multi-document or
+ singleton behavior. Preview 1 intentionally starts a new instance per view.
+- Preserve readable distinction between import success and display
+ materialization failure; current tests already defend that distinction.
+- Browser `File` validation and host-side path/extension/read validation should
+ eventually share policy at an application boundary rather than duplicate
+ presentation checks.
+
+## Routing/window/application-shell concerns
+
+- There is currently one SPA route and no document URL model. The Preview 1
+ host should use a fixed root URL and server-held startup intent, not encode
+ local paths in browser history.
+- A future desktop shell can replace browser launch without changing the
+ startup-open application transition or renderer.
+- Do not introduce singleton IPC until document/session ownership and window
+ semantics are designed together.
+
+## Packaging implications
+
+- The intended Preview 1 bundle seam is `aetheris[.exe]` beside a `cadmata`
+ directory containing `Cadmata.exe` and its normal .NET publish files,
+ including `wwwroot` production assets.
+- The CLI should discover that relative shape without current-directory or
+ source-tree knowledge. Development-source fallback may remain explicit and
+ diagnostic until P1-PACKAGE-M1 publishes the bundle.
+- Production assets must be rooted at the host content root/executable output;
+ never search upward for the repository or start Vite at runtime.
+- The Preview 1 host validates `wwwroot/index.html` before accepting a startup
+ file. This is a useful packaging assertion, but the future package pipeline
+ should make the frontend artifact a declared build input rather than relying
+ on `dist` existing when MSBuild evaluates the project.
+
+## Testing seams worth preserving
+
+- Pure display-scene mapping and camera bounds/fit tests.
+- API integration tests through `WebApplicationFactory`.
+- App behavioral tests that distinguish import, display success, and display
+ failure without brittle visual snapshots.
+- CLI process-launch abstraction tests: exact executable, absolute argument,
+ build-before-launch, and no-build direct STEP behavior.
+
+## Temporary Preview 1 compromises to remove
+
+This register is updated whenever Preview 1 glue is added.
+
+| File/path | Reason | Why acceptable for Preview 1 | Preferred replacement | Removal dependency |
+| --- | --- | --- | --- | --- |
+| `Aetheris.Server` host/browser startup path | Reuses the working API and Vite UI without a desktop rewrite | One file, one local instance, no daemon or manual server | Desktop/webview application shell with explicit document-open adapter | Post-P1 shell/window architecture |
+| CLI compatibility flag/env (`--cad-assistant-path`, `AETHERIS_CAD_ASSISTANT_PATH`) | Avoids breaking existing scripts | Public text can call the target Cadmata while honoring old configuration | Canonical Cadmata option/env with deprecation window | Packaging and compatibility policy |
+| Cadmata host builds as `WinExe` and opens a browser | A console-subsystem host kept captured shell handles open after CLI exit | It provides a detached Windows application without changing the React/server stack | Native desktop/webview shell with a structured readiness/error channel | Post-P1 host/shell replacement |
+| `Aetheris.Server.csproj` conditionally copies an existing Vite `dist` | Keeps frontend tooling out of CLI runtime and supports a self-contained publish shape | Packaging can build the SPA first and publish the host second | One TSPack/MSBuild package graph with an explicit frontend artifact dependency | P1 packaging workflow or later TSPack consolidation |
+
+## Things that are surprisingly good and should NOT be rewritten
+
+- `displaySceneBounds.ts` is pure, focused, and already covers far-from-origin
+ and fit behavior.
+- `buildDisplaySceneData` isolates API-to-render-scene conversion.
+- Server import, document, display-preparation, and diagnostics endpoints form
+ a usable application boundary; a shell rewrite need not replace the kernel
+ API.
+- Behavioral frontend tests mock the renderer and exercise state transitions,
+ which is the right level for startup-open regression coverage.
+
+## Candidate post-P1 milestone ladder
+
+1. Specify document-open/session/window state independent of React and host.
+2. Extract the current document/import controller behind that contract while
+ preserving the existing API and behavioral tests.
+3. Establish the TSPack workspace/build/package contract and reproducible
+ frontend artifact handoff.
+4. Move the application shell and panels incrementally to MachinaLayout.js.
+5. Introduce a desktop shell adapter if desired, then remove the temporary
+ browser-host launch glue.
+6. Revisit renderer component ownership and overlays only after application
+ state and layout boundaries are stable.