diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 79f8281..787d2a5 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -57,6 +57,12 @@ jobs:
if: startsWith(github.ref, 'refs/tags/v')
run: dotnet publish src/Bermuda/Bermuda.csproj --configuration Release --runtime win-x64 --self-contained true --output artifacts/publish -p:PublishSingleFile=false -p:PublishReadyToRun=false
+ # The native side apps listed in fdc3-appd.json ship inside Bermuda's MSIX as more applications, so they
+ # are published into the same folder (shared runtime/library files are identical).
+ - name: Publish self-contained native apps into the same folder
+ if: startsWith(github.ref, 'refs/tags/v')
+ run: dotnet msbuild src/Bermuda/Bermuda.csproj -t:PublishNativeApps -p:Configuration=Release -p:NativeAppsPublishDir=${{ github.workspace }}/artifacts/publish/
+
- name: Upload self-contained app
if: startsWith(github.ref, 'refs/tags/v')
uses: actions/upload-artifact@v4
@@ -70,6 +76,11 @@ jobs:
- name: Check committed FDC3 preload is up to date
run: git diff --ignore-cr-at-eol --exit-code -- src/Bermuda/Preload
+ # The FDC3 contract is generated from src/Bermuda.Fdc3.Proto/Protos/fdc3.proto by the build
+ # (Bermuda.Fdc3.Proto); the outputs are committed, so a stale or hand-edited copy fails here.
+ - name: Check committed FDC3 generated code is up to date
+ run: git diff --ignore-cr-at-eol --exit-code -- src/Bermuda.IpcContract/Generated src/Bermuda.Fdc3.Grpc/Generated
+
# ─── E2E (requires a Windows desktop runner) ──────────────────────────────
#
# The Playwright tests connect to the live app via CDP (port 9222).
@@ -83,6 +94,10 @@ jobs:
name: E2E tests
needs: build
runs-on: self-hosted
+ # The runner is one machine with fixed-name resources (the app's windows, ports, the FDC3 pipe): one e2e at a time.
+ concurrency:
+ group: e2e-self-hosted
+ cancel-in-progress: false
steps:
- uses: actions/checkout@v4
@@ -111,6 +126,32 @@ jobs:
working-directory: src/Bermuda.Web
run: pnpm exec playwright install chromium
+ # The runner is a normal user machine: Bermuda may be installed and running, a dev may have Aspire up, and
+ # an older run may have left processes behind. So every run gets its own FDC3 pipe, ports and dashboard
+ # endpoints, and nothing here depends on the defaults being free.
+ - name: Isolate this run from the rest of the machine
+ shell: pwsh
+ run: |
+ function Get-FreePort {
+ $listener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, 0)
+ $listener.Start()
+ $port = $listener.LocalEndpoint.Port
+ $listener.Stop()
+ $port
+ }
+ $lines = @(
+ "FDC3_GRPC_PIPE=bermuda-fdc3-ci-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT",
+ "WEB_PORT=$(Get-FreePort)",
+ "CDP_PORT=$(Get-FreePort)",
+ "ASPNETCORE_URLS=http://localhost:$(Get-FreePort)",
+ "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL=http://localhost:$(Get-FreePort)",
+ "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL=http://localhost:$(Get-FreePort)",
+ "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL=http://localhost:$(Get-FreePort)",
+ "ASPIRE_ALLOW_UNSECURED_TRANSPORT=true"
+ )
+ $lines | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
+ $lines | ForEach-Object { Write-Host $_ }
+
- name: Run E2E tests
working-directory: src/Bermuda.Web
run: pnpm e2e --reporter=list
diff --git a/Bermuda.slnx b/Bermuda.slnx
index 45011e6..eedad4a 100644
--- a/Bermuda.slnx
+++ b/Bermuda.slnx
@@ -3,7 +3,12 @@
+
+
+
+
+
diff --git a/Directory.Packages.props b/Directory.Packages.props
index f858674..b486d76 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -17,7 +17,7 @@
-
+
@@ -27,6 +27,13 @@
+
+
+
+
+
+
+
diff --git a/README.md b/README.md
index 69acb62..b5b3fc0 100644
--- a/README.md
+++ b/README.md
@@ -104,7 +104,7 @@ await window.fdc3.broadcast({ type: 'bermuda.incident', id: { incidentId: '7' }
const resolution = await window.fdc3.raiseIntent('ViewIncident', context)
```
-- **Where it lives** — the agent is `src/Bermuda.Fdc3/DesktopAgent.cs` (one per process, shared by all windows). `src/Bermuda.Web/src/fdc3/` implements the `@finos/fdc3-standard` `DesktopAgent` interface by calling `fdc3.*` `invoke()` commands (the `IFdc3Commands` interface in `Bermuda.IpcContract/Fdc3Contract.cs`, implemented per app instance by `Fdc3Connection`, so their TS types are generated like everything else) and dispatching the host's `fdc3.context` / `fdc3.intent` / `fdc3.event` pushes to registered handlers.
+- **Where it lives** — the agent is `src/Bermuda.Fdc3/DesktopAgent.cs` (one per process, shared by all windows). `src/Bermuda.Web/src/fdc3/` implements the `@finos/fdc3-standard` `DesktopAgent` interface by calling `fdc3.*` `invoke()` commands (the `IFdc3Commands` interface, generated from `Bermuda.Fdc3.Proto/Protos/fdc3.proto` into `Bermuda.IpcContract/Generated/Fdc3Contract.g.cs`, implemented per app instance by `Fdc3Connection`, so their TS types are generated like everything else) and dispatching the host's `fdc3.context` / `fdc3.intent` / `fdc3.event` pushes to registered handlers.
- **Supported** — the 8 recommended user channels, app channels, private channels (with their events), `broadcast`/`addContextListener`/`getCurrentContext`, `findIntent`/`findIntentsByContext`/`raiseIntent`/`raiseIntentForContext`/`addIntentListener` with results (context or channel), `open`, `findInstances`, `getAppMetadata`, `getInfo`, and the `userChannelChanged` event. Not yet: Desktop Agent Bridging, or the Web Connection Protocol for browser apps outside the host.
- **Preload bundle** — `fdc3-preload.js` is built from `src/Bermuda.Web/src/fdc3/preload.ts` by `pnpm build:preload` (part of `pnpm build`) and committed, like `ipc.d.ts`, so the host builds without Node; CI fails if it's out of date. Re-run `pnpm build:preload` after touching anything under `src/fdc3/`.
- **App Directory** — `src/Bermuda/fdc3-appd.json` uses the AppD v2 `applications` shape; relative `details.url`s resolve against `WEB_URL`. `fdc3.open` (or raising an intent at an app that isn't running) opens the app in a new host window and resolves once the app has connected (and, if you passed a context, registered a listener for it), or rejects with `AppTimeout`. Intent results the raiser never collects are dropped after 10 minutes.
@@ -117,6 +117,8 @@ const resolution = await window.fdc3.raiseIntent('ViewIncident', context)
# Build a self-contained MSIX installer (needs the winapp CLI: winget install Microsoft.winappcli --source winget)
dotnet msbuild src/Bermuda -t:CreateMsix -p:Configuration=Release
# Output: artifacts/msix/
+
+# The package also contains the native FDC3 side apps listed in src/Bermuda/fdc3-appd.json (type "native").
```
### Releases and auto-update
diff --git a/docs/fdc3.md b/docs/fdc3.md
index c778857..43c15ad 100644
--- a/docs/fdc3.md
+++ b/docs/fdc3.md
@@ -28,7 +28,7 @@ Make the Bermuda host an [FDC3 2.2](https://fdc3.finos.org/docs/2.2/fdc3-intro)
|---|---|---|
| `DesktopAgent` | `src/Bermuda.Fdc3` | All state and rules: instances, channels, listeners, intents, results, launching. One per process. |
| `Fdc3Connection` | `src/Bermuda.Fdc3` | One app instance's handle on the agent; implements the command interface for that instance. `IDisposable`. |
-| `IFdc3Commands` | `src/Bermuda.IpcContract/Fdc3Contract.cs` | The wire contract: one method per `fdc3.*` command. TypeScript types are generated from it into `ipc.d.ts`. |
+| `IFdc3Commands` | `src/Bermuda.IpcContract/Generated/Fdc3Contract.g.cs` | The wire contract: one method per `fdc3.*` command. Generated from `src/Bermuda.Fdc3.Proto/Protos/fdc3.proto` (see 7a); TypeScript types are generated from it into `ipc.d.ts`. |
| `HostBridge` | `src/Bermuda` | Dispatches an `invoke()` command to the window's connection, binding the JSON payload to the method's parameter type. |
| `MainWindow` | `src/Bermuda` | One connected instance per page load; injects the preload; delivers the agent's pushes to the page. |
| `WindowAppLauncher` | `src/Bermuda` | Opens App Directory apps in new host windows for `open` and for intents. |
@@ -138,6 +138,33 @@ Rejections are `Error`s whose `message` is the standard FDC3 error string; over
- Selecting an incident broadcasts `{ type: "bermuda.incident", id: { incidentId }, name: }`. Selection that *arrives* over FDC3 (a broadcast on the joined channel, or the `ViewIncident` intent) selects the incident but does not re-broadcast, so linked windows cannot echo.
- Incidents unknown to the receiving window are ignored.
+## 7a. Native apps over gRPC (named pipe)
+
+Native side apps join the same in-process agent as the web windows, so they share channels and intents with them. `Bermuda.Fdc3.Grpc` hosts a gRPC service (Kestrel named-pipe transport, HTTP/2 without TLS) that serves `IFdc3Commands`.
+
+**The proto is the source of truth for the whole FDC3 contract**, web and native: `src/Bermuda.Fdc3.Proto/Protos/fdc3.proto`. Building `Bermuda.Fdc3.Proto` does three things:
+
+1. Grpc.Tools turns it into the gRPC messages and the `Fdc3Agent` service (and client) classes.
+2. `Bermuda.Fdc3.Grpc.Generator` reads protoc's descriptor set and writes `src/Bermuda.IpcContract/Generated/Fdc3Contract.g.cs`: the `Fdc3*` records and `IFdc3Commands` that `DesktopAgent`, `Fdc3Connection` and the web bridge are written against (and that `ipc.d.ts` is generated from).
+3. The same tool writes `src/Bermuda.Fdc3.Grpc/Generated/Fdc3Generated.g.cs`: the proto↔record mapping and one service override per rpc.
+
+Both generated files are checked in, like `ipc.d.ts`, and CI fails if they are stale. So adding or changing a command, field or message means editing the proto and rebuilding; nothing else is hand-synchronised. The naming and nullability conventions (and the `async` method option for commands that wait on another app) are documented at the top of the proto; a proto that breaks them fails the build with the list of problems. Hand-written: the `Subscribe` stream and caller lookup (`Fdc3AgentService.cs`), the JSON helper (`Mapping.cs`) and the host and client.
+
+- **Pipe**: `\\.\pipe\bermuda-fdc3-` by default (pipe names are machine-wide, so the user name keeps users apart). Override with `FDC3_GRPC_PIPE`; disable with `FDC3_GRPC_ENABLED=false` (both in `appsettings.json` or the environment). The pipe is current-user-only.
+- **Connect**: call `Subscribe(app_id)`. `app_id` MUST be in the App Directory, else the call fails with `AppNotFound`. The first stream message is `connected { instance_id }`; context, intent and API-event deliveries follow (`ContextEvent`, `IntentEvent`, `ApiEvent`, mirroring `Fdc3*Event`).
+- **Calls**: every other RPC carries the `x-fdc3-instance` header (the `instance_id`) and must use the same pipe connection as the stream, else `AccessDenied`.
+- **Lifetime**: the stream is the app instance. When it ends (cancelled, process exit, pipe closed) the instance is disconnected like a closed window.
+- **Contexts** are JSON text (`*_json` fields). **Errors** are gRPC errors whose status *detail* is the `Fdc3Errors` string (`NoChannelFound`, `MalformedContext`, …); the code is a coarse mapping (e.g. `NotFound`, `InvalidArgument`, `PermissionDenied`).
+- **Client**: any gRPC stack that can dial a named pipe. `Fdc3PipeClient` (in `Bermuda.Fdc3.Proto`, so a client does not need ASP.NET Core; used by the sample `src/Bermuda.NativeApp`) is a ~100-line .NET reference (`SocketsHttpHandler.ConnectCallback` returning a `NamedPipeClientStream`).
+- **Native apps are discovered from the App Directory.** `fdc3-appd.json` is the one list of side apps. An entry with `"type": "native"` and `details.path` (its exe, relative to Bermuda's folder) is a native app; `details.project` (Bermuda extension: the .csproj that builds it, relative to the file) tells builds where it comes from. Everything else follows from that entry, so **adding a native app is a one-line edit of `fdc3-appd.json`** plus its project:
+ - **Aspire** (`Bermuda.AppHost`) starts a resource per native entry next to the host.
+ - **MSIX** (`CreateMsix`, via `src/Bermuda/tools/native-apps.cs`, a file-based C# app) publishes each project into Bermuda's package folder and adds an `` for it to the manifest (full trust, no Start menu entry, no startup task). CI publishes them for tagged releases with `dotnet msbuild src/Bermuda -t:PublishNativeApps`. So they deploy, update and are signed exactly like Bermuda, from the same `.appinstaller`.
+ - **Bermuda** starts each one when the host starts (`App.StartNativeApps`; `NATIVE_APP_AUTOSTART=false` turns that off) and closes them on exit. An app should allow one copy per user, so a second start is harmless, and retry until the host's pipe is up.
+ - **On demand**: `fdc3.open`, or an intent raised at a native app that is not running, makes Bermuda start it (`NativeAppHost`, the same code as autostart). The host passes the pipe name (`FDC3_GRPC_PIPE`) and the instance id it is expecting (`FDC3_INSTANCE_ID`) in the app's environment, and the app sends that id in `SubscribeRequest.instance_id`, which completes the open. A native app that crashes is therefore started again the next time something needs it. `details.path` must stay inside Bermuda's folder.
+ - **Only native apps connect over the pipe.** `Subscribe` rejects an App Directory entry that is not `type: native` (`AccessDenied`), so a process cannot claim to be `bermuda-incidents` or another web app. It does not check which program is on the other end of the pipe (anything running as the same user can name a native app); for that, the pipe would need the client's process id, which Kestrel's named-pipe transport does not expose.
+ The sample is `src/Bermuda.NativeApp` (`native-incidents`): it joins a channel and acknowledges incidents. It handles its own `AcknowledgeIncident` intent rather than `ViewIncident`, so an untargeted `raiseIntent('ViewIncident', …)` still resolves to the dashboard (two running listeners would need the caller to pick one).
+- Limitations: native apps are not launched by the agent (`open`/intents can target them only while connected), and web windows are still the only apps with launch URLs.
+
## 8. Known limitations
- **No origin check.** Any page loaded in a host window gets `window.fdc3` and can issue `fdc3.*` commands as that window's app identity (and, as before this feature, can use the host's other bridges). Fine while the host only loads trusted app URLs; restrict by origin before navigating to untrusted content.
@@ -155,6 +182,7 @@ Rejections are `Error`s whose `message` is the standard FDC3 error string; over
| `open` and metadata (4.5) | `DesktopAgentTests`: open with context, unknown app, `getInfo`; `ReviewRegressionTests`: contextless `open` waits for connect, times out |
| Wire contract (5) | `IpcDispatchTests`: command naming, every command discovered, payload binding, `InvalidArguments`, unwrapped errors |
| `window.fdc3` (4.2, frontend) | `hostDesktopAgent.test.ts` (listener routing, results, validation, `getResult` caching), `preload.test.ts` |
+| gRPC pipe (7a) | `Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests`: unknown app rejected, instance lifetime, channel broadcast web↔pipe and pipe↔pipe, intent round trip both directions, error details, instance-header/connection binding |
| End to end, live app | `e2e/fdc3.spec.ts`: `getInfo`, two linked windows sharing selection and an intent to a specific instance, and a plain-HTML app receiving `open` with a context (proves the preload) |
Run: `dotnet test`, `pnpm test`, and `pnpm e2e` (needs the app: `aspire run`).
diff --git a/src/Bermuda.AppHost/AppHost.cs b/src/Bermuda.AppHost/AppHost.cs
index f25c98f..96a9b17 100644
--- a/src/Bermuda.AppHost/AppHost.cs
+++ b/src/Bermuda.AppHost/AppHost.cs
@@ -1,21 +1,50 @@
+using System.Text.Json;
+
var builder = DistributedApplication.CreateBuilder(args);
var api = builder.AddProject("api");
+// Ports and the FDC3 pipe name can be overridden (WEB_PORT, CDP_PORT, FDC3_GRPC_PIPE in the AppHost's
+// configuration or environment), so a CI run can be isolated from anything else on the machine.
+var webPort = builder.Configuration["WEB_PORT"] is { Length: > 0 } wp ? wp : "5555";
+var cdpPort = builder.Configuration["CDP_PORT"] is { Length: > 0 } cp ? cp : "9222";
+
var web = builder.AddViteApp("web", "../Bermuda.Web")
.WithPnpm()
- .WithEnvironment("PORT", "5555")
+ .WithEnvironment("PORT", webPort)
.WithEnvironment("VITE_API_URL", api.GetEndpoint("http"));
builder.AddExecutable("relay", "pnpm", "../Bermuda.Web", "run", "relay:watch")
.WithEnvironment("RELAY_SCHEMA_URL", api.GetEndpoint("http"))
.WaitFor(api);
-builder.AddProject("host")
+// An optional pipe name for the host and the native apps.
+var pipeName = builder.Configuration["FDC3_GRPC_PIPE"];
+
+var host = builder.AddProject("host")
.WithEnvironment("WEB_URL", web.GetEndpoint("http"))
- .WithEnvironment("CDP_PORT", "9222")
+ .WithEnvironment("CDP_PORT", cdpPort)
.WaitFor(web)
.WaitFor(api);
+if (!string.IsNullOrWhiteSpace(pipeName)) host.WithEnvironment("FDC3_GRPC_PIPE", pipeName);
+
+// The native FDC3 side apps are discovered from the App Directory (type "native" with details.project), so
+// adding one is a one-line edit of fdc3-appd.json. They join the host's agent over the gRPC named pipe (the
+// default per-user pipe name) and reconnect until it is up.
+var appDirectory = Path.Combine(builder.AppHostDirectory, "..", "Bermuda", "fdc3-appd.json");
+foreach (var app in JsonDocument.Parse(File.ReadAllText(appDirectory), new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true })
+ .RootElement.GetProperty("applications").EnumerateArray())
+{
+ if (app.GetProperty("type").GetString() != "native"
+ || !app.TryGetProperty("details", out var details)
+ || !details.TryGetProperty("project", out var project)) continue;
+
+#pragma warning disable ASPIRECSHARPAPPS001 // AddCSharpApp is Aspire's new file/path-based project API (experimental)
+ var native = builder.AddCSharpApp(app.GetProperty("appId").GetString()!, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(appDirectory)!, project.GetString()!)))
+ .WaitFor(host);
+ if (!string.IsNullOrWhiteSpace(pipeName)) native.WithEnvironment("FDC3_GRPC_PIPE", pipeName);
+#pragma warning restore ASPIRECSHARPAPPS001
+}
builder.Build().Run();
diff --git a/src/Bermuda.AppHost/Bermuda.AppHost.csproj b/src/Bermuda.AppHost/Bermuda.AppHost.csproj
index 1bedc53..625a4cd 100644
--- a/src/Bermuda.AppHost/Bermuda.AppHost.csproj
+++ b/src/Bermuda.AppHost/Bermuda.AppHost.csproj
@@ -1,4 +1,4 @@
-
+Exe
diff --git a/src/Bermuda.Fdc3.Grpc.Generator/Bermuda.Fdc3.Grpc.Generator.csproj b/src/Bermuda.Fdc3.Grpc.Generator/Bermuda.Fdc3.Grpc.Generator.csproj
new file mode 100644
index 0000000..03c1da8
--- /dev/null
+++ b/src/Bermuda.Fdc3.Grpc.Generator/Bermuda.Fdc3.Grpc.Generator.csproj
@@ -0,0 +1,18 @@
+
+
+
+
+ Exe
+ net10.0
+ enable
+ enable
+
+
+
+
+
+
+
diff --git a/src/Bermuda.Fdc3.Grpc.Generator/Program.cs b/src/Bermuda.Fdc3.Grpc.Generator/Program.cs
new file mode 100644
index 0000000..bab602c
--- /dev/null
+++ b/src/Bermuda.Fdc3.Grpc.Generator/Program.cs
@@ -0,0 +1,468 @@
+using System.Text;
+using Google.Protobuf;
+using Google.Protobuf.Reflection;
+
+// Usage: Bermuda.Fdc3.Grpc.Generator
+//
+// Protos/fdc3.proto is the source of truth for Bermuda's FDC3 contract (the conventions are documented at the
+// top of that file). This tool reads protoc's descriptor set of it (with source info, for the doc comments) and
+// writes:
+// * the C# contract the in-process agent and the web bridge use: Fdc3* records and IFdc3Commands;
+// * the glue that serves it over gRPC: proto <-> record mapping and one service override per rpc.
+// A proto that breaks the conventions fails the build with the list of problems.
+if (args.Length != 3) throw new ArgumentException("Usage: ");
+
+// The `async` method option (field 50001 of google.protobuf.MethodOptions) is defined in fdc3.proto itself.
+var asyncOption = new Extension(50001, FieldCodec.ForBool(50001u << 3));
+var set = FileDescriptorSet.Parser
+ .WithExtensionRegistry(new ExtensionRegistry { asyncOption })
+ .ParseFrom(File.ReadAllBytes(args[0]));
+var file = set.File.Single(f => f.Name.EndsWith("fdc3.proto", StringComparison.Ordinal));
+
+var (model, errors) = ProtoModel.Build(file, asyncOption);
+if (errors.Count > 0)
+{
+ Console.Error.WriteLine("fdc3.proto breaks the generator's conventions:");
+ foreach (var error in errors) Console.Error.WriteLine(" - " + error);
+ return 1;
+}
+
+Write(args[1], new ContractWriter(model).Generate());
+Write(args[2], new GlueWriter(model).Generate());
+return 0;
+
+static void Write(string path, string content)
+{
+ Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
+ content = content.Replace("\r\n", "\n");
+ // Don't touch an unchanged file, so incremental builds stay incremental.
+ if (!File.Exists(path) || File.ReadAllText(path).Replace("\r\n", "\n") != content) File.WriteAllText(path, content);
+}
+
+enum Kind { String, Bool, Json, Message }
+
+/// Property name on the protoc-generated class.
+/// Property name on the contract record (and so the web JSON name).
+sealed record Field(string ProtoName, string ProtoCs, string Prop, Kind Kind, bool Repeated, bool Optional, string? Message)
+{
+ public bool Nullable => Optional && !Repeated;
+}
+
+sealed record Msg(string Name, string Record, List Fields, string? Doc);
+
+enum Shape { Void, Direct, Array, Nullable, NullableJson }
+
+/// Request message, null for google.protobuf.Empty.
+/// Result message (null for void / JSON); says how the contract returns it.
+sealed record Rpc(string Name, string? Request, string? Result, Shape Shape, bool Async, string? Wrapper, string? Doc);
+
+/// AgentEvent oneof field, which is also the web message type suffix ("fdc3.<field>").
+sealed record Ev(Msg Message, string Field, string ProtoCs);
+
+sealed class ProtoModel
+{
+ private static readonly HashSet Transport = ["SubscribeRequest", "Connected", "AgentEvent"];
+
+ public List Messages { get; } = [];
+ public List Rpcs { get; } = [];
+ public List Events { get; } = [];
+
+ public static (ProtoModel Model, List Errors) Build(FileDescriptorProto file, Extension asyncOption)
+ {
+ var model = new ProtoModel();
+ var errors = new List();
+ var prefix = "." + file.Package + ".";
+ string? Local(string typeName) => typeName.StartsWith(prefix, StringComparison.Ordinal) ? typeName[prefix.Length..] : null;
+
+ var docs = file.SourceCodeInfo?.Location
+ .Where(l => l.LeadingComments.Length > 0)
+ .ToDictionary(l => string.Join(',', l.Path), l => Clean(l.LeadingComments)) ?? [];
+ string? DocOf(params int[] path) => docs.GetValueOrDefault(string.Join(',', path));
+
+ var service = file.Service.SingleOrDefault(s => s.Name == "Fdc3Agent");
+ if (service is null) { errors.Add("service Fdc3Agent is missing."); return (model, errors); }
+ var serviceIndex = file.Service.IndexOf(service);
+
+ // Wrapper messages are named after the rpc whose result they carry.
+ var wrapperNames = service.Method.Select(m => m.Name + "Response").ToHashSet();
+ var byName = file.MessageType.ToDictionary(m => m.Name);
+
+ if (!service.Method.Any(m => m.Name == "Subscribe" && m.ServerStreaming && m.InputType == prefix + "SubscribeRequest" && m.OutputType == prefix + "AgentEvent"))
+ errors.Add("rpc Subscribe(SubscribeRequest) returns (stream AgentEvent) is required.");
+
+ // Events: AgentEvent's oneof alternatives other than `connected`.
+ var events = new List<(string Field, string Message)>();
+ if (!byName.TryGetValue("AgentEvent", out var agentEvent)) errors.Add("message AgentEvent is missing.");
+ else
+ {
+ if (agentEvent.OneofDecl.Count != 1 || agentEvent.Field.Any(f => !f.HasOneofIndex))
+ errors.Add("message AgentEvent must contain exactly one oneof holding all its fields.");
+ foreach (var f in agentEvent.Field.Where(f => f.Name != "connected"))
+ {
+ var type = f.Type == FieldDescriptorProto.Types.Type.Message ? Local(f.TypeName) : null;
+ if (type is null || !type.EndsWith("Event", StringComparison.Ordinal))
+ errors.Add($"AgentEvent.{f.Name} must be a message whose name ends in Event.");
+ else events.Add((f.Name, type));
+ }
+ }
+
+ // Messages
+ for (var i = 0; i < file.MessageType.Count; i++)
+ {
+ var m = file.MessageType[i];
+ if (Transport.Contains(m.Name) || wrapperNames.Contains(m.Name)) continue;
+ var fields = new List();
+ foreach (var f in m.Field)
+ {
+ var repeated = f.Label == FieldDescriptorProto.Types.Label.Repeated;
+ var optional = f.Proto3Optional;
+ string? message = null;
+ Kind kind;
+ switch (f.Type)
+ {
+ case FieldDescriptorProto.Types.Type.String when f.Name.EndsWith("_json", StringComparison.Ordinal):
+ kind = Kind.Json;
+ break;
+ case FieldDescriptorProto.Types.Type.String:
+ kind = Kind.String;
+ break;
+ case FieldDescriptorProto.Types.Type.Bool:
+ kind = Kind.Bool;
+ break;
+ case FieldDescriptorProto.Types.Type.Message when Local(f.TypeName) is { } local:
+ kind = Kind.Message;
+ message = local;
+ break;
+ default:
+ errors.Add($"{m.Name}.{f.Name}: unsupported type {f.Type} (use string, bool, a message of this package, or repeated message).");
+ continue;
+ }
+ if (repeated && kind != Kind.Message) errors.Add($"{m.Name}.{f.Name}: only message fields can be repeated.");
+ if (repeated && optional) errors.Add($"{m.Name}.{f.Name}: a repeated field cannot be optional.");
+ if (kind is Kind.Bool && optional) errors.Add($"{m.Name}.{f.Name}: optional bool is not supported.");
+
+ var json = string.IsNullOrEmpty(f.JsonName) ? Naming.Camel(f.Name) : f.JsonName;
+ if (kind == Kind.Json && json.EndsWith("Json", StringComparison.Ordinal)) json = json[..^4];
+ fields.Add(new Field(f.Name, Naming.Pascal(f.Name), char.ToUpperInvariant(json[0]) + json[1..], kind, repeated, optional, message));
+ }
+ model.Messages.Add(new Msg(m.Name, "Fdc3" + m.Name, fields, DocOf(4, i)));
+ }
+
+ var messages = model.Messages.ToDictionary(m => m.Name);
+ foreach (var (field, message) in events)
+ {
+ if (!messages.TryGetValue(message, out var msg)) { errors.Add($"event message {message} is missing."); continue; }
+ model.Events.Add(new Ev(msg, field, Naming.Pascal(field)));
+ }
+
+ // Rpcs
+ for (var i = 0; i < service.Method.Count; i++)
+ {
+ var rpc = service.Method[i];
+ if (rpc.Name == "Subscribe") continue;
+ if (rpc.ClientStreaming || rpc.ServerStreaming) errors.Add($"rpc {rpc.Name} must be unary.");
+
+ var request = rpc.InputType == ".google.protobuf.Empty" ? null : Local(rpc.InputType);
+ if (rpc.InputType != ".google.protobuf.Empty" && (request is null || !messages.ContainsKey(request)))
+ errors.Add($"rpc {rpc.Name}: request type {rpc.InputType} must be google.protobuf.Empty or a message of this package.");
+
+ var isAsync = rpc.Options is not null && rpc.Options.HasExtension(asyncOption) && rpc.Options.GetExtension(asyncOption);
+ string? result = null;
+ string? wrapper = null;
+ Shape shape;
+ if (rpc.OutputType == ".google.protobuf.Empty") shape = Shape.Void;
+ else if (Local(rpc.OutputType) is { } output && output == rpc.Name + "Response" && byName.TryGetValue(output, out var w))
+ {
+ wrapper = output;
+ var f = w.Field.Count == 1 ? w.Field[0] : null;
+ if (f is { Name: "items", Type: FieldDescriptorProto.Types.Type.Message } && f.Label == FieldDescriptorProto.Types.Label.Repeated && Local(f.TypeName) is { } item)
+ (shape, result) = (Shape.Array, item);
+ else if (f is { Name: "result", Type: FieldDescriptorProto.Types.Type.Message, Proto3Optional: true } && Local(f.TypeName) is { } single)
+ (shape, result) = (Shape.Nullable, single);
+ else if (f is { Name: "result_json", Type: FieldDescriptorProto.Types.Type.String, Proto3Optional: true })
+ shape = Shape.NullableJson;
+ else
+ {
+ errors.Add($"{output} must have exactly one field: `repeated Message items`, `optional Message result` or `optional string result_json`.");
+ shape = Shape.Direct;
+ }
+ }
+ else if (Local(rpc.OutputType) is { } direct && messages.ContainsKey(direct)) (shape, result) = (Shape.Direct, direct);
+ else
+ {
+ errors.Add($"rpc {rpc.Name}: response type {rpc.OutputType} must be google.protobuf.Empty or a message of this package.");
+ shape = Shape.Void;
+ }
+ model.Rpcs.Add(new Rpc(rpc.Name, request, result, shape, isAsync, wrapper, DocOf(6, serviceIndex, 2, i)));
+ }
+
+ // Every contract message must be reachable from an rpc or an event; otherwise it is dead weight.
+ var used = new HashSet();
+ void Use(string? name)
+ {
+ if (name is null || !used.Add(name) || !messages.TryGetValue(name, out var msg)) return;
+ foreach (var f in msg.Fields) Use(f.Message);
+ }
+ foreach (var r in model.Rpcs) { Use(r.Request); Use(r.Result); }
+ foreach (var e in model.Events) Use(e.Message.Name);
+ foreach (var m in model.Messages.Where(m => !used.Contains(m.Name)))
+ errors.Add($"message {m.Name} is not used by any rpc or event; remove it.");
+ foreach (var w in wrapperNames.Where(byName.ContainsKey).Where(n => model.Rpcs.All(r => r.Wrapper != n)))
+ errors.Add($"message {w} looks like a wrapper but rpc {w[..^8]} does not return it.");
+
+ return (model, errors);
+ }
+
+ private static string Clean(string comment) =>
+ string.Join("\n", comment.TrimEnd().Split('\n').Select(l => l.StartsWith(' ') ? l[1..] : l));
+}
+
+static class Naming
+{
+ /// protoc's C# property name for a proto field: "app_id" -> "AppId".
+ public static string Pascal(string snake) =>
+ string.Concat(snake.Split('_', StringSplitOptions.RemoveEmptyEntries).Select(s => char.ToUpperInvariant(s[0]) + s[1..]));
+
+ /// protoc's default json_name: "app_id" -> "appId".
+ public static string Camel(string snake)
+ {
+ var pascal = Pascal(snake);
+ return char.ToLowerInvariant(pascal[0]) + pascal[1..];
+ }
+}
+
+abstract class CodeWriter
+{
+ private readonly StringBuilder _sb = new();
+ private int _indent;
+
+ protected void L(string text = "") => _sb.Append(text.Length == 0 ? "" : new string(' ', _indent * 4) + text).Append('\n');
+ protected void Open() { L("{"); _indent++; }
+ protected void Close(string suffix = "") { _indent--; L("}" + suffix); }
+ protected string Result => _sb.ToString();
+
+ protected void Doc(string? comment)
+ {
+ if (string.IsNullOrWhiteSpace(comment)) return;
+ L("/// ");
+ foreach (var line in comment.Split('\n'))
+ L(("/// " + line.Replace("&", "&").Replace("<", "<").Replace(">", ">")).TrimEnd());
+ L("/// ");
+ }
+}
+
+/// Fdc3* records and IFdc3Commands: what DesktopAgent, Fdc3Connection and the web bridge are written against.
+sealed class ContractWriter(ProtoModel model) : CodeWriter
+{
+ public string Generate()
+ {
+ L("// ");
+ L("// Generated by Bermuda.Fdc3.Grpc.Generator from src/Bermuda.Fdc3.Proto/Protos/fdc3.proto. Do not edit:");
+ L("// change the proto and rebuild Bermuda.Fdc3.Proto.");
+ L("// ");
+ L("#nullable enable");
+ L("using System.Text.Json;");
+ L();
+ L("namespace Bermuda.IpcContract;");
+ L();
+
+ foreach (var m in model.Messages)
+ {
+ var ev = model.Events.FirstOrDefault(e => e.Message == m);
+ Doc(m.Doc);
+ if (ev is not null) L("[IpcType]");
+ L($"public sealed record {m.Record}({Parameters(m)}){(ev is null ? ";" : "")}");
+ if (ev is not null)
+ {
+ Open();
+ L($"public string Type => \"fdc3.{ev.Field}\";");
+ Close();
+ }
+ L();
+ }
+
+ L("/// ");
+ L("/// The fdc3.* commands: one per FDC3 DesktopAgent / Channel / PrivateChannel / IntentResolution call,");
+ L("/// plus SendIntentResult, which reports an intent handler's outcome back. Implemented per app instance");
+ L("/// by Bermuda.Fdc3.Fdc3Connection. Methods throw Fdc3Exception, whose message is the");
+ L("/// standard FDC3 error string.");
+ L("/// ");
+ L("[IpcCommands(\"fdc3\")]");
+ L("public interface IFdc3Commands");
+ Open();
+ foreach (var rpc in model.Rpcs)
+ {
+ Doc(rpc.Doc);
+ var returns = rpc.Shape switch
+ {
+ Shape.Void => rpc.Async ? "Task" : "void",
+ _ => rpc.Async ? $"Task<{ReturnType(rpc)}>" : ReturnType(rpc),
+ };
+ var parameter = rpc.Request is null ? "" : $"Fdc3{rpc.Request} request";
+ L($"{returns} {rpc.Name}{(rpc.Async ? "Async" : "")}({parameter});");
+ }
+ Close();
+ return Result;
+ }
+
+ private static string ReturnType(Rpc rpc) => rpc.Shape switch
+ {
+ Shape.Array => $"Fdc3{rpc.Result}[]",
+ Shape.Nullable => $"Fdc3{rpc.Result}?",
+ Shape.NullableJson => "JsonElement?",
+ _ => $"Fdc3{rpc.Result}",
+ };
+
+ private static string Parameters(Msg m)
+ {
+ var parts = m.Fields.Select(f => (Type: TypeOf(f), f.Prop, f.Nullable)).ToList();
+ var firstDefault = parts.Count;
+ while (firstDefault > 0 && parts[firstDefault - 1].Nullable) firstDefault--;
+ return string.Join(", ", parts.Select((p, i) => $"{p.Type} {p.Prop}{(i >= firstDefault ? " = null" : "")}"));
+ }
+
+ private static string TypeOf(Field f) => f.Kind switch
+ {
+ Kind.String => f.Nullable ? "string?" : "string",
+ Kind.Bool => "bool",
+ Kind.Json => f.Nullable ? "JsonElement?" : "JsonElement",
+ _ => "Fdc3" + f.Message + (f.Repeated ? "[]" : f.Nullable ? "?" : ""),
+ };
+}
+
+/// The gRPC side: proto message <-> record mapping, and the service overrides that call Fdc3Connection.
+sealed class GlueWriter(ProtoModel model) : CodeWriter
+{
+ public string Generate()
+ {
+ L("// ");
+ L("// Generated by Bermuda.Fdc3.Grpc.Generator from src/Bermuda.Fdc3.Proto/Protos/fdc3.proto. Do not edit.");
+ L("// ");
+ L("#nullable enable");
+ L("using Bermuda.IpcContract;");
+ L("using Google.Protobuf.WellKnownTypes;");
+ L("using Grpc.Core;");
+ L("using Proto = Bermuda.Fdc3.Grpc.Proto;");
+ L();
+ L("namespace Bermuda.Fdc3.Grpc;");
+ L();
+ L("internal static class GeneratedMapping");
+ Open();
+ foreach (var m in model.Messages)
+ {
+ if (model.Events.All(e => e.Message != m)) WriteToContract(m);
+ WriteToProto(m);
+ }
+
+ L("/// Maps what the agent posts to a sink; null for a message type this transport doesn't know.");
+ L("public static Proto.AgentEvent? ToProtoEvent(object message) => message switch");
+ Open();
+ foreach (var e in model.Events)
+ L($"{e.Message.Record} e => new Proto.AgentEvent {{ {e.ProtoCs} = ToProto(e) }},");
+ L("_ => null,");
+ Close(";");
+ Close();
+ L();
+
+ L("internal sealed partial class Fdc3AgentService");
+ Open();
+ foreach (var rpc in model.Rpcs) WriteRpc(rpc);
+ Close();
+ return Result;
+ }
+
+ private void WriteToContract(Msg m)
+ {
+ L($"public static {m.Record} ToContract(Proto.{m.Name}? p)");
+ Open();
+ L("if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments);");
+ L($"return new {m.Record}(");
+ for (var i = 0; i < m.Fields.Count; i++)
+ L(" " + ToContractArg(m.Fields[i]) + (i < m.Fields.Count - 1 ? "," : ");"));
+ Close();
+ L();
+ }
+
+ private static string ToContractArg(Field f)
+ {
+ var p = "p." + f.ProtoCs;
+ var has = "p.Has" + f.ProtoCs;
+ if (f.Repeated) return $"{p}.Select(ToContract).ToArray()";
+ return f.Kind switch
+ {
+ Kind.String => f.Optional ? $"{has} ? {p} : null" : p,
+ Kind.Bool => p,
+ Kind.Json => f.Optional ? $"{has} ? Mapping.ParseContext({p}) : null" : $"Mapping.ParseContext({p})",
+ _ => f.Optional ? $"{p} is null ? null : ToContract({p})" : $"ToContract({p})",
+ };
+ }
+
+ private void WriteToProto(Msg m)
+ {
+ L($"public static Proto.{m.Name} ToProto({m.Record} r)");
+ Open();
+ L($"var m = new Proto.{m.Name}();");
+ foreach (var f in m.Fields)
+ {
+ var r = "r." + f.Prop;
+ var target = "m." + f.ProtoCs;
+ if (f.Repeated) { L($"{target}.AddRange({r}.Select(ToProto));"); continue; }
+ switch (f.Kind)
+ {
+ case Kind.Json when f.Optional: L($"if ({r} is {{ }} {f.ProtoCs.ToLowerInvariant()}) {target} = {f.ProtoCs.ToLowerInvariant()}.GetRawText();"); break;
+ case Kind.Json: L($"{target} = {r}.GetRawText();"); break;
+ case Kind.Message when f.Optional: L($"if ({r} is not null) {target} = ToProto({r});"); break;
+ case Kind.Message: L($"{target} = ToProto({r});"); break;
+ default: L(f.Optional ? $"if ({r} is not null) {target} = {r};" : $"{target} = {r};"); break;
+ }
+ }
+ L("return m;");
+ Close();
+ L();
+ }
+
+ private void WriteRpc(Rpc rpc)
+ {
+ var requestType = rpc.Request is null ? "Empty" : "Proto." + rpc.Request;
+ var responseType = rpc.Shape == Shape.Void ? "Empty" : "Proto." + (rpc.Wrapper ?? rpc.Result);
+ var call = $"Caller(context).{rpc.Name}{(rpc.Async ? "Async" : "")}({(rpc.Request is null ? "" : "GeneratedMapping.ToContract(request)")})";
+
+ L($"public override {(rpc.Async ? "async " : "")}Task<{responseType}> {rpc.Name}({requestType} request, ServerCallContext context)");
+ Open();
+ if (rpc.Shape == Shape.Void)
+ {
+ L(rpc.Async ? $"await {call};" : $"{call};");
+ L(rpc.Async ? "return new Empty();" : "return Task.FromResult(new Empty());");
+ Close();
+ L();
+ return;
+ }
+
+ L($"var result = {(rpc.Async ? "await " : "")}{call};");
+ string response;
+ switch (rpc.Shape)
+ {
+ case Shape.Direct:
+ response = "GeneratedMapping.ToProto(result)";
+ break;
+ case Shape.Array:
+ L($"var response = new Proto.{rpc.Wrapper}();");
+ L("response.Items.AddRange(result.Select(GeneratedMapping.ToProto));");
+ response = "response";
+ break;
+ case Shape.Nullable:
+ L($"var response = new Proto.{rpc.Wrapper}();");
+ L("if (result is not null) response.Result = GeneratedMapping.ToProto(result);");
+ response = "response";
+ break;
+ default:
+ L($"var response = new Proto.{rpc.Wrapper}();");
+ L("if (result is { } value) response.ResultJson = value.GetRawText();");
+ response = "response";
+ break;
+ }
+ L(rpc.Async ? $"return {response};" : $"return Task.FromResult({response});");
+ Close();
+ L();
+ }
+}
diff --git a/src/Bermuda.Fdc3.Grpc.Tests/Bermuda.Fdc3.Grpc.Tests.csproj b/src/Bermuda.Fdc3.Grpc.Tests/Bermuda.Fdc3.Grpc.Tests.csproj
new file mode 100644
index 0000000..b31e311
--- /dev/null
+++ b/src/Bermuda.Fdc3.Grpc.Tests/Bermuda.Fdc3.Grpc.Tests.csproj
@@ -0,0 +1,25 @@
+
+
+
+ net10.0
+ enable
+ enable
+ false
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests.cs b/src/Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests.cs
new file mode 100644
index 0000000..3c7d746
--- /dev/null
+++ b/src/Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests.cs
@@ -0,0 +1,287 @@
+using System.Collections.Concurrent;
+using System.Text.Json;
+using Bermuda.Fdc3.Grpc.Proto;
+using Bermuda.IpcContract;
+using Google.Protobuf.WellKnownTypes;
+using Grpc.Core;
+
+namespace Bermuda.Fdc3.Grpc.Tests;
+
+/// Real named pipe, real Kestrel, real gRPC: native clients next to an in-process (web-window-style) connection.
+public sealed class PipeIntegrationTests : IAsyncLifetime
+{
+ private const string AppD = """
+ {
+ "applications": [
+ { "appId": "native-app", "title": "Native", "type": "native" },
+ {
+ "appId": "incidents",
+ "title": "Incidents",
+ "type": "native",
+ "interop": { "intents": { "listensFor": {
+ "ViewIncident": { "contexts": ["bermuda.incident"], "resultType": "fdc3.contact" }
+ } } }
+ },
+ {
+ "appId": "web-app",
+ "title": "Web",
+ "interop": { "intents": { "listensFor": {
+ "ViewMap": { "contexts": ["bermuda.incident"] }
+ } } }
+ }
+ ]
+ }
+ """;
+
+ private const string Incident = """{ "type": "bermuda.incident", "id": { "incidentId": "7" } }""";
+
+ private readonly PipeLauncher _launcher = new();
+ private readonly DesktopAgent _agent;
+ private readonly string _pipe = "bermuda-fdc3-test-" + Guid.NewGuid().ToString("N");
+ private readonly List _clients = [];
+ private Fdc3GrpcHost _host = null!;
+
+ public PipeIntegrationTests()
+ {
+ _agent = new DesktopAgent(AppDirectory.Parse(AppD), _launcher, launchTimeout: TimeSpan.FromSeconds(2));
+ }
+
+ /// Stands in for Bermuda's NativeAppHost: "starts" the native app, which connects with the instance id it was given.
+ private sealed class PipeLauncher : IFdc3AppLauncher
+ {
+ public Func? Start { get; set; }
+
+ public void Launch(AppDefinition app, string instanceId) => _ = Start?.Invoke(app, instanceId);
+ }
+
+ public async Task InitializeAsync() => _host = await Fdc3GrpcHost.StartAsync(_agent, _pipe);
+
+ public async Task DisposeAsync()
+ {
+ foreach (var client in _clients) await client.DisposeAsync();
+ await _host.DisposeAsync();
+ }
+
+ private async Task ConnectAsync(string appId, string? instanceId = null)
+ {
+ var client = await Fdc3PipeClient.ConnectAsync(_pipe, appId, instanceId: instanceId);
+ _clients.Add(client);
+ return client;
+ }
+
+ private static JsonElement Json(string json) => JsonSerializer.Deserialize(json);
+
+ [Fact]
+ public async Task Rejects_an_app_id_that_is_not_in_the_app_directory()
+ {
+ var ex = await Assert.ThrowsAsync(() => Fdc3PipeClient.ConnectAsync(_pipe, "nobody"));
+
+ Assert.Equal(StatusCode.NotFound, ex.StatusCode);
+ Assert.Equal(Fdc3Errors.AppNotFound, ex.Status.Detail);
+ }
+
+ [Fact]
+ public async Task Rejects_a_web_app_because_only_native_apps_use_the_pipe()
+ {
+ var ex = await Assert.ThrowsAsync(() => Fdc3PipeClient.ConnectAsync(_pipe, "web-app"));
+
+ Assert.Equal(StatusCode.PermissionDenied, ex.StatusCode);
+ Assert.Equal(Fdc3Errors.AccessDenied, ex.Status.Detail);
+ }
+
+ [Fact]
+ public async Task Open_launches_a_native_app_that_connects_with_the_instance_id_it_was_given()
+ {
+ _launcher.Start = async (app, instanceId) => await ConnectAsync(app.AppId, instanceId);
+ using var web = _agent.Connect("web-app", new RecordingSink());
+
+ var opened = await web.OpenAsync(new Fdc3OpenRequest(new Fdc3AppIdentifier("native-app", null), null));
+
+ Assert.Equal("native-app", opened.AppId);
+ Assert.NotNull(opened.InstanceId);
+ Assert.Contains(web.FindInstances(new Fdc3AppIdentifier("native-app", null)), i => i.InstanceId == opened.InstanceId);
+ }
+
+ [Fact]
+ public async Task Connecting_registers_an_instance_that_is_removed_when_the_client_goes_away()
+ {
+ var client = await ConnectAsync("native-app");
+ using var observer = _agent.Connect("web-app", new RecordingSink());
+
+ var instances = observer.FindInstances(new Fdc3AppIdentifier("native-app"));
+ Assert.Equal(client.InstanceId, Assert.Single(instances).InstanceId);
+
+ var info = await client.Rpc.GetInfoAsync(new Empty(), client.Headers);
+ Assert.Equal("2.2", info.Fdc3Version);
+ Assert.Equal("native-app", info.AppMetadata.AppId);
+ Assert.Equal(client.InstanceId, info.AppMetadata.InstanceId);
+
+ await client.DisposeAsync();
+ await EventuallyAsync(() => observer.FindInstances(new Fdc3AppIdentifier("native-app")).Length == 0);
+ }
+
+ [Fact]
+ public async Task Channel_broadcast_flows_between_a_pipe_client_and_an_in_process_connection()
+ {
+ var native = await ConnectAsync("native-app");
+ var webSink = new RecordingSink();
+ using var web = _agent.Connect("web-app", webSink);
+
+ await native.Rpc.JoinUserChannelAsync(new ChannelIdRequest { ChannelId = "fdc3.channel.1" }, native.Headers);
+ await native.Rpc.AddContextListenerAsync(
+ new AddContextListenerRequest { ListenerId = "n1", ContextType = "bermuda.incident" }, native.Headers);
+ web.JoinUserChannel(new Fdc3ChannelIdRequest("fdc3.channel.1"));
+ web.AddContextListener(new Fdc3AddContextListenerRequest("w1", null, "bermuda.incident"));
+
+ // web -> pipe
+ web.Broadcast(new Fdc3BroadcastRequest(null, Json(Incident)));
+ var received = (await native.NextEventAsync()).Context;
+ Assert.Equal("n1", received.ListenerId);
+ Assert.Equal("bermuda.incident", Json(received.ContextJson).GetProperty("type").GetString());
+ Assert.Equal("web-app", received.Source.AppId);
+
+ // pipe -> web
+ await native.Rpc.BroadcastAsync(new BroadcastRequest { ContextJson = """{ "type": "bermuda.incident", "id": { "incidentId": "9" } }""" }, native.Headers);
+ var delivered = await webSink.NextAsync();
+ Assert.Equal("w1", delivered.ListenerId);
+ Assert.Equal("9", delivered.Context.GetProperty("id").GetProperty("incidentId").GetString());
+ Assert.Equal("native-app", delivered.Source!.AppId);
+
+ // a late joiner on the channel sees the current context
+ var current = await native.Rpc.GetCurrentContextAsync(
+ new GetCurrentContextRequest { ChannelId = "fdc3.channel.1" }, native.Headers);
+ Assert.Contains("\"9\"", current.ResultJson);
+ }
+
+ [Fact]
+ public async Task Two_pipe_clients_share_a_channel()
+ {
+ var a = await ConnectAsync("native-app");
+ var b = await ConnectAsync("native-app");
+ foreach (var c in new[] { a, b })
+ {
+ await c.Rpc.JoinUserChannelAsync(new ChannelIdRequest { ChannelId = "fdc3.channel.2" }, c.Headers);
+ await c.Rpc.AddContextListenerAsync(new AddContextListenerRequest { ListenerId = "l" }, c.Headers);
+ }
+
+ await a.Rpc.BroadcastAsync(new BroadcastRequest { ContextJson = Incident }, a.Headers);
+
+ Assert.Equal("l", (await b.NextEventAsync()).Context.ListenerId);
+ }
+
+ [Fact]
+ public async Task Intent_round_trip_from_an_in_process_raiser_to_a_pipe_handler()
+ {
+ var native = await ConnectAsync("incidents");
+ using var web = _agent.Connect("web-app", new RecordingSink());
+ await native.Rpc.AddIntentListenerAsync(
+ new AddIntentListenerRequest { ListenerId = "i1", Intent = "ViewIncident" }, native.Headers);
+
+ var resolution = await web.RaiseIntentAsync(new Fdc3RaiseIntentRequest("ViewIncident", Json(Incident), null));
+ Assert.Equal("incidents", resolution.Source.AppId);
+
+ var e = (await native.NextEventAsync()).Intent;
+ Assert.Equal("i1", e.ListenerId);
+ Assert.Equal("ViewIncident", e.Intent);
+ Assert.Equal("web-app", e.Source.AppId);
+ Assert.Equal(resolution.ResultId, e.ResultId);
+
+ await native.Rpc.SendIntentResultAsync(new SendIntentResultRequest
+ {
+ ResultId = e.ResultId,
+ ContextJson = """{ "type": "fdc3.contact", "name": "Ann" }""",
+ }, native.Headers);
+
+ var result = await web.GetIntentResultAsync(new Fdc3ResultIdRequest(resolution.ResultId));
+ Assert.Equal("Ann", result.Context!.Value.GetProperty("name").GetString());
+ }
+
+ [Fact]
+ public async Task Intent_round_trip_from_a_pipe_raiser_to_an_in_process_handler()
+ {
+ var native = await ConnectAsync("native-app");
+ var webSink = new RecordingSink();
+ using var web = _agent.Connect("web-app", webSink);
+ web.AddIntentListener(new Fdc3AddIntentListenerRequest("h1", "ViewMap"));
+
+ var resolution = await native.Rpc.RaiseIntentAsync(
+ new RaiseIntentRequest { Intent = "ViewMap", ContextJson = Incident }, native.Headers);
+ Assert.Equal("ViewMap", resolution.Intent);
+
+ var delivered = await webSink.NextAsync();
+ Assert.Equal("native-app", delivered.Source!.AppId);
+ web.SendIntentResult(new Fdc3SendIntentResultRequest(
+ delivered.ResultId, Json("""{ "type": "fdc3.contact", "name": "Bo" }"""), null, null));
+
+ var result = await native.Rpc.GetIntentResultAsync(new ResultIdRequest { ResultId = resolution.ResultId }, native.Headers);
+ Assert.Equal("Bo", Json(result.ContextJson).GetProperty("name").GetString());
+ }
+
+ [Fact]
+ public async Task Errors_carry_the_fdc3_error_string_as_the_status_detail()
+ {
+ var native = await ConnectAsync("native-app");
+
+ var unknownChannel = await Assert.ThrowsAsync(async () =>
+ await native.Rpc.JoinUserChannelAsync(new ChannelIdRequest { ChannelId = "nope" }, native.Headers));
+ Assert.Equal(Fdc3Errors.NoChannelFound, unknownChannel.Status.Detail);
+
+ var noTarget = await Assert.ThrowsAsync(async () =>
+ await native.Rpc.RaiseIntentAsync(new RaiseIntentRequest { Intent = "Nothing", ContextJson = Incident }, native.Headers));
+ Assert.Equal(Fdc3Errors.NoAppsFound, noTarget.Status.Detail);
+
+ var malformed = await Assert.ThrowsAsync(async () =>
+ await native.Rpc.BroadcastAsync(new BroadcastRequest { ContextJson = "{ not json" }, native.Headers));
+ Assert.Equal(Fdc3Errors.MalformedContext, malformed.Status.Detail);
+ Assert.Equal(StatusCode.InvalidArgument, malformed.StatusCode);
+ }
+
+ [Fact]
+ public async Task Calls_without_a_valid_instance_header_are_denied()
+ {
+ var native = await ConnectAsync("native-app");
+
+ var missing = await Assert.ThrowsAsync(async () => await native.Rpc.GetInfoAsync(new Empty()));
+ Assert.Equal(Fdc3Errors.AccessDenied, missing.Status.Detail);
+
+ var wrong = await Assert.ThrowsAsync(async () =>
+ await native.Rpc.GetInfoAsync(new Empty(), new Metadata { { Fdc3Headers.Instance, "someone-else" } }));
+ Assert.Equal(StatusCode.PermissionDenied, wrong.StatusCode);
+ }
+
+ [Fact]
+ public async Task An_instance_id_does_not_work_from_another_pipe_connection()
+ {
+ var native = await ConnectAsync("native-app");
+ var other = await ConnectAsync("native-app");
+
+ var ex = await Assert.ThrowsAsync(async () =>
+ await other.Rpc.GetInfoAsync(new Empty(), native.Headers));
+
+ Assert.Equal(Fdc3Errors.AccessDenied, ex.Status.Detail);
+ }
+
+ private static async Task EventuallyAsync(Func condition)
+ {
+ var deadline = DateTime.UtcNow.AddSeconds(5);
+ while (!condition())
+ {
+ if (DateTime.UtcNow > deadline) throw new TimeoutException("Condition not met.");
+ await Task.Delay(25);
+ }
+ }
+
+ private sealed class RecordingSink : IFdc3AppSink
+ {
+ private readonly BlockingCollection
+
+
+
+
+
diff --git a/src/Bermuda.IpcContract/Fdc3Contract.cs b/src/Bermuda.IpcContract/Fdc3Contract.cs
deleted file mode 100644
index 4039ba8..0000000
--- a/src/Bermuda.IpcContract/Fdc3Contract.cs
+++ /dev/null
@@ -1,176 +0,0 @@
-using System.Text.Json;
-
-namespace Bermuda.IpcContract;
-
-// FDC3 2.2 Desktop Agent wire contract
-// ====================================
-// The frontend's window.fdc3 (src/Bermuda.Web/src/fdc3/) implements the
-// standard @finos/fdc3-standard DesktopAgent interface by calling the
-// fdc3.* commands of IFdc3Commands (bottom of this file) over the invoke()
-// channel; Bermuda.Fdc3 handles them on the host. Shapes mirror the FDC3 API types (AppIdentifier,
-// AppMetadata, AppIntent, ...) closely enough that the frontend shim can pass
-// them through with at most a light wrap (e.g. adding methods to a Channel).
-//
-// Contexts are carried as raw JsonElement (`unknown` in TS) — FDC3 contexts
-// are open-ended JSON objects whose only required field is `type`.
-//
-// Host → web push messages (Fdc3ContextEvent etc.) carry a constant `type`
-// discriminator so bridge/index.ts can tell them apart from HostResponses.
-
-public sealed record Fdc3AppIdentifier(string AppId, string? InstanceId = null);
-
-public sealed record Fdc3DisplayMetadata(string? Name, string? Color, string? Glyph);
-
-/// A user, app or private channel. Type is one of 'user' | 'app' | 'private'.
-public sealed record Fdc3ChannelInfo(string Id, string Type, Fdc3DisplayMetadata? DisplayMetadata);
-
-public sealed record Fdc3IntentMetadata(string Name, string? DisplayName);
-
-public sealed record Fdc3AppMetadata(
- string AppId,
- string? InstanceId,
- string? Name,
- string? Version,
- string? Title,
- string? Tooltip,
- string? Description,
- string? ResultType);
-
-public sealed record Fdc3AppIntent(Fdc3IntentMetadata Intent, Fdc3AppMetadata[] Apps);
-
-public sealed record Fdc3OptionalFeatures(
- bool OriginatingAppMetadata,
- bool UserChannelMembershipAPIs,
- bool DesktopAgentBridging);
-
-public sealed record Fdc3ImplementationMetadata(
- string Fdc3Version,
- string Provider,
- string? ProviderVersion,
- Fdc3OptionalFeatures OptionalFeatures,
- Fdc3AppMetadata AppMetadata);
-
-///
-/// What raiseIntent/raiseIntentForContext return. The frontend
-/// turns it into an FDC3 IntentResolution whose getResult() calls
-/// fdc3.getIntentResult with ResultId.
-///
-public sealed record Fdc3IntentResolutionInfo(Fdc3AppIdentifier Source, string Intent, string ResultId);
-
-/// An intent handler's result: a context, a channel, or neither (void).
-public sealed record Fdc3IntentResultInfo(JsonElement? Context, Fdc3ChannelInfo? Channel);
-
-// Requests ---------------------------------------------------------------
-
-public sealed record Fdc3ChannelIdRequest(string ChannelId);
-
-/// ChannelId null = the caller's current user channel.
-public sealed record Fdc3BroadcastRequest(string? ChannelId, JsonElement Context);
-
-public sealed record Fdc3GetCurrentContextRequest(string ChannelId, string? ContextType);
-
-///
-/// ListenerId is generated by the frontend and echoed back in every
-/// for this listener. ChannelId null =
-/// follow whichever user channel the caller is joined to (fdc3.addContextListener);
-/// non-null = a specific app/private channel (channel.addContextListener).
-///
-public sealed record Fdc3AddContextListenerRequest(string ListenerId, string? ChannelId, string? ContextType);
-
-public sealed record Fdc3AddIntentListenerRequest(string ListenerId, string Intent);
-
-///
-/// ChannelId null = desktop-agent events ('userChannelChanged');
-/// non-null = private channel events ('addContextListener' | 'unsubscribe' | 'disconnect').
-/// EventType null = all event types.
-///
-public sealed record Fdc3AddEventListenerRequest(string ListenerId, string? EventType, string? ChannelId);
-
-public sealed record Fdc3ListenerIdRequest(string ListenerId);
-
-public sealed record Fdc3FindIntentRequest(string Intent, JsonElement? Context, string? ResultType);
-
-public sealed record Fdc3FindIntentsByContextRequest(JsonElement Context, string? ResultType);
-
-public sealed record Fdc3OpenRequest(Fdc3AppIdentifier App, JsonElement? Context);
-
-public sealed record Fdc3RaiseIntentRequest(string Intent, JsonElement Context, Fdc3AppIdentifier? App);
-
-public sealed record Fdc3RaiseIntentForContextRequest(JsonElement Context, Fdc3AppIdentifier? App);
-
-public sealed record Fdc3ResultIdRequest(string ResultId);
-
-///
-/// Sent by the instance that handled an intent once its handler settles.
-/// At most one of Context/ChannelId is set (neither = void);
-/// Error is set instead if the handler threw/rejected.
-///
-public sealed record Fdc3SendIntentResultRequest(string ResultId, JsonElement? Context, string? ChannelId, string? Error);
-
-// Host → web push messages ----------------------------------------------------
-
-[IpcType]
-public sealed record Fdc3ContextEvent(string ListenerId, JsonElement Context, Fdc3AppIdentifier? Source)
-{
- public string Type => "fdc3.context";
-}
-
-[IpcType]
-public sealed record Fdc3IntentEvent(string ListenerId, string Intent, JsonElement Context, Fdc3AppIdentifier? Source, string ResultId)
-{
- public string Type => "fdc3.intent";
-}
-
-/// An FDC3 ApiEvent (EventType + Details) for a listener added via addEventListener.
-[IpcType]
-public sealed record Fdc3ApiEvent(string ListenerId, string EventType, object? Details)
-{
- public string Type => "fdc3.event";
-}
-
-// Commands -------------------------------------------------------------------
-
-///
-/// The fdc3.* commands: one per FDC3 DesktopAgent / Channel / PrivateChannel /
-/// IntentResolution call, plus , which reports an
-/// intent handler's outcome back. Implemented per app instance by
-/// Bermuda.Fdc3.Fdc3Connection. Methods throw Fdc3Exception, whose
-/// message is the standard FDC3 error string.
-///
-[IpcCommands("fdc3")]
-public interface IFdc3Commands
-{
- Fdc3ImplementationMetadata GetInfo();
- Fdc3AppMetadata GetAppMetadata(Fdc3AppIdentifier app);
- Fdc3AppIdentifier[] FindInstances(Fdc3AppIdentifier app);
- Task OpenAsync(Fdc3OpenRequest request);
-
- Fdc3ChannelInfo[] GetUserChannels();
- void JoinUserChannel(Fdc3ChannelIdRequest request);
- void LeaveCurrentChannel();
- Fdc3ChannelInfo? GetCurrentChannel();
- Fdc3ChannelInfo GetOrCreateChannel(Fdc3ChannelIdRequest request);
- Fdc3ChannelInfo CreatePrivateChannel();
- void DisconnectPrivateChannel(Fdc3ChannelIdRequest request);
-
- /// FDC3 broadcast() and channel.broadcast().
- void Broadcast(Fdc3BroadcastRequest request);
- JsonElement? GetCurrentContext(Fdc3GetCurrentContextRequest request);
- void AddContextListener(Fdc3AddContextListenerRequest request);
- void AddIntentListener(Fdc3AddIntentListenerRequest request);
- void AddEventListener(Fdc3AddEventListenerRequest request);
-
- /// Listener.unsubscribe(), for every kind of listener.
- void Unsubscribe(Fdc3ListenerIdRequest request);
-
- Fdc3AppIntent FindIntent(Fdc3FindIntentRequest request);
- Fdc3AppIntent[] FindIntentsByContext(Fdc3FindIntentsByContextRequest request);
- Task RaiseIntentAsync(Fdc3RaiseIntentRequest request);
- Task RaiseIntentForContextAsync(Fdc3RaiseIntentForContextRequest request);
-
- /// IntentResolution.getResult().
- Task GetIntentResultAsync(Fdc3ResultIdRequest request);
-
- /// Reports an intent handler's result back to the raiser.
- void SendIntentResult(Fdc3SendIntentResultRequest request);
-}
diff --git a/src/Bermuda.IpcContract/Generated/Fdc3Contract.g.cs b/src/Bermuda.IpcContract/Generated/Fdc3Contract.g.cs
new file mode 100644
index 0000000..f971fe7
--- /dev/null
+++ b/src/Bermuda.IpcContract/Generated/Fdc3Contract.g.cs
@@ -0,0 +1,155 @@
+//
+// Generated by Bermuda.Fdc3.Grpc.Generator from src/Bermuda.Fdc3.Proto/Protos/fdc3.proto. Do not edit:
+// change the proto and rebuild Bermuda.Fdc3.Proto.
+//
+#nullable enable
+using System.Text.Json;
+
+namespace Bermuda.IpcContract;
+
+public sealed record Fdc3AppIdentifier(string AppId, string? InstanceId = null);
+
+public sealed record Fdc3DisplayMetadata(string? Name = null, string? Color = null, string? Glyph = null);
+
+///
+/// A user, app or private channel. `type` is one of 'user' | 'app' | 'private'.
+///
+public sealed record Fdc3ChannelInfo(string Id, string Type, Fdc3DisplayMetadata? DisplayMetadata = null);
+
+public sealed record Fdc3IntentMetadata(string Name, string? DisplayName = null);
+
+public sealed record Fdc3AppMetadata(string AppId, string? InstanceId = null, string? Name = null, string? Version = null, string? Title = null, string? Tooltip = null, string? Description = null, string? ResultType = null);
+
+public sealed record Fdc3AppIntent(Fdc3IntentMetadata Intent, Fdc3AppMetadata[] Apps);
+
+public sealed record Fdc3OptionalFeatures(bool OriginatingAppMetadata, bool UserChannelMembershipAPIs, bool DesktopAgentBridging);
+
+public sealed record Fdc3ImplementationMetadata(string Fdc3Version, string Provider, string? ProviderVersion, Fdc3OptionalFeatures OptionalFeatures, Fdc3AppMetadata AppMetadata);
+
+///
+/// What raiseIntent/raiseIntentForContext return. The frontend turns it into an FDC3 IntentResolution whose
+/// getResult() calls getIntentResult with `result_id`.
+///
+public sealed record Fdc3IntentResolutionInfo(Fdc3AppIdentifier Source, string Intent, string ResultId);
+
+///
+/// An intent handler's result: a context, a channel, or neither (void).
+///
+public sealed record Fdc3IntentResultInfo(JsonElement? Context = null, Fdc3ChannelInfo? Channel = null);
+
+public sealed record Fdc3ChannelIdRequest(string ChannelId);
+
+///
+/// `channel_id` unset = the caller's current user channel.
+///
+public sealed record Fdc3BroadcastRequest(string? ChannelId, JsonElement Context);
+
+public sealed record Fdc3GetCurrentContextRequest(string ChannelId, string? ContextType = null);
+
+///
+/// `listener_id` is chosen by the caller and echoed back in every ContextEvent for this listener.
+/// `channel_id` unset = follow whichever user channel the caller is joined to (fdc3.addContextListener);
+/// set = a specific app/private channel (channel.addContextListener).
+///
+public sealed record Fdc3AddContextListenerRequest(string ListenerId, string? ChannelId = null, string? ContextType = null);
+
+public sealed record Fdc3AddIntentListenerRequest(string ListenerId, string Intent);
+
+///
+/// `channel_id` unset = desktop-agent events ('userChannelChanged'); set = private channel events
+/// ('addContextListener' | 'unsubscribe' | 'disconnect'). `event_type` unset = all event types.
+///
+public sealed record Fdc3AddEventListenerRequest(string ListenerId, string? EventType = null, string? ChannelId = null);
+
+public sealed record Fdc3ListenerIdRequest(string ListenerId);
+
+public sealed record Fdc3FindIntentRequest(string Intent, JsonElement? Context = null, string? ResultType = null);
+
+public sealed record Fdc3FindIntentsByContextRequest(JsonElement Context, string? ResultType = null);
+
+public sealed record Fdc3OpenRequest(Fdc3AppIdentifier App, JsonElement? Context = null);
+
+public sealed record Fdc3RaiseIntentRequest(string Intent, JsonElement Context, Fdc3AppIdentifier? App = null);
+
+public sealed record Fdc3RaiseIntentForContextRequest(JsonElement Context, Fdc3AppIdentifier? App = null);
+
+public sealed record Fdc3ResultIdRequest(string ResultId);
+
+///
+/// Sent by the instance that handled an intent once its handler settles. At most one of
+/// `context_json`/`channel_id` is set (neither = void); `error` is set instead if the handler threw/rejected.
+///
+public sealed record Fdc3SendIntentResultRequest(string ResultId, JsonElement? Context = null, string? ChannelId = null, string? Error = null);
+
+///
+/// Delivery to a listener added with AddContextListener.
+///
+[IpcType]
+public sealed record Fdc3ContextEvent(string ListenerId, JsonElement Context, Fdc3AppIdentifier? Source = null)
+{
+ public string Type => "fdc3.context";
+}
+
+///
+/// Delivery to an intent listener; the handler reports back with SendIntentResult(result_id).
+///
+[IpcType]
+public sealed record Fdc3IntentEvent(string ListenerId, string Intent, JsonElement Context, Fdc3AppIdentifier? Source, string ResultId)
+{
+ public string Type => "fdc3.intent";
+}
+
+///
+/// An FDC3 ApiEvent (`event_type` + `details`) for a listener added via AddEventListener.
+///
+[IpcType]
+public sealed record Fdc3ApiEvent(string ListenerId, string EventType, JsonElement? Details = null)
+{
+ public string Type => "fdc3.event";
+}
+
+///
+/// The fdc3.* commands: one per FDC3 DesktopAgent / Channel / PrivateChannel / IntentResolution call,
+/// plus SendIntentResult, which reports an intent handler's outcome back. Implemented per app instance
+/// by Bermuda.Fdc3.Fdc3Connection. Methods throw Fdc3Exception, whose message is the
+/// standard FDC3 error string.
+///
+[IpcCommands("fdc3")]
+public interface IFdc3Commands
+{
+ Fdc3ImplementationMetadata GetInfo();
+ Fdc3AppMetadata GetAppMetadata(Fdc3AppIdentifier request);
+ Fdc3AppIdentifier[] FindInstances(Fdc3AppIdentifier request);
+ Task OpenAsync(Fdc3OpenRequest request);
+ Fdc3ChannelInfo[] GetUserChannels();
+ void JoinUserChannel(Fdc3ChannelIdRequest request);
+ void LeaveCurrentChannel();
+ Fdc3ChannelInfo? GetCurrentChannel();
+ Fdc3ChannelInfo GetOrCreateChannel(Fdc3ChannelIdRequest request);
+ Fdc3ChannelInfo CreatePrivateChannel();
+ void DisconnectPrivateChannel(Fdc3ChannelIdRequest request);
+ ///
+ /// FDC3 broadcast() and channel.broadcast().
+ ///
+ void Broadcast(Fdc3BroadcastRequest request);
+ JsonElement? GetCurrentContext(Fdc3GetCurrentContextRequest request);
+ void AddContextListener(Fdc3AddContextListenerRequest request);
+ void AddIntentListener(Fdc3AddIntentListenerRequest request);
+ void AddEventListener(Fdc3AddEventListenerRequest request);
+ ///
+ /// Listener.unsubscribe(), for every kind of listener.
+ ///
+ void Unsubscribe(Fdc3ListenerIdRequest request);
+ Fdc3AppIntent FindIntent(Fdc3FindIntentRequest request);
+ Fdc3AppIntent[] FindIntentsByContext(Fdc3FindIntentsByContextRequest request);
+ Task RaiseIntentAsync(Fdc3RaiseIntentRequest request);
+ Task RaiseIntentForContextAsync(Fdc3RaiseIntentForContextRequest request);
+ ///
+ /// IntentResolution.getResult().
+ ///
+ Task GetIntentResultAsync(Fdc3ResultIdRequest request);
+ ///
+ /// Reports an intent handler's result back to the raiser.
+ ///
+ void SendIntentResult(Fdc3SendIntentResultRequest request);
+}
diff --git a/src/Bermuda.NativeApp/Bermuda.NativeApp.csproj b/src/Bermuda.NativeApp/Bermuda.NativeApp.csproj
new file mode 100644
index 0000000..c364a4c
--- /dev/null
+++ b/src/Bermuda.NativeApp/Bermuda.NativeApp.csproj
@@ -0,0 +1,25 @@
+
+
+
+
+ WinExe
+ net10.0
+ enable
+ enable
+
+
+
+
+
+
+
+
diff --git a/src/Bermuda.NativeApp/Program.cs b/src/Bermuda.NativeApp/Program.cs
new file mode 100644
index 0000000..81ca399
--- /dev/null
+++ b/src/Bermuda.NativeApp/Program.cs
@@ -0,0 +1,94 @@
+using System.Text.Json;
+using Bermuda.Fdc3.Grpc;
+using Bermuda.Fdc3.Grpc.Proto;
+using Google.Protobuf.WellKnownTypes;
+using Grpc.Core;
+
+// Native FDC3 side app for Bermuda.
+//
+// * joins user channel NATIVE_CHANNEL (default fdc3.channel.1)
+// * listens for `bermuda.incident` contexts there and answers each by
+// broadcasting `bermuda.native.ack` carrying the incident it saw
+// * handles the `AcknowledgeIncident` intent and returns the same ack as its result
+// (not `ViewIncident`: the dashboard handles that, and an untargeted raise must keep resolving to it)
+//
+// Config (environment): FDC3_GRPC_PIPE (default: Bermuda's per-user pipe), NATIVE_CHANNEL, and FDC3_INSTANCE_ID,
+// which Bermuda sets when it launches the app for fdc3.open or an intent.
+// It reconnects whenever the host goes away, so start order doesn't matter.
+
+const string AppId = "native-incidents";
+const string AckType = "bermuda.native.ack";
+
+var pipe = Environment.GetEnvironmentVariable("FDC3_GRPC_PIPE") is { Length: > 0 } p ? p : null;
+var launchInstance = Environment.GetEnvironmentVariable("FDC3_INSTANCE_ID") is { Length: > 0 } i ? i : null;
+var channel = Environment.GetEnvironmentVariable("NATIVE_CHANNEL") is { Length: > 0 } c ? c : "fdc3.channel.1";
+
+// One copy per user: Windows starts it at sign-in and Bermuda starts it too; a second copy just exits.
+using var singleInstance = new Mutex(true, @"Local\Bermuda.NativeApp." + AppId, out var first);
+if (!first) return;
+
+using var shutdown = new CancellationTokenSource();
+Console.CancelKeyPress += (_, e) => { e.Cancel = true; shutdown.Cancel(); };
+
+while (!shutdown.IsCancellationRequested)
+{
+ try
+ {
+ // The launch instance id is for the first connection only; a reconnect is a new instance.
+ await using var client = await Fdc3PipeClient.ConnectAsync(pipe, AppId, shutdown.Token, launchInstance);
+ launchInstance = null;
+ Console.WriteLine($"[{AppId}] connected as {client.InstanceId}");
+ await RunAsync(client, shutdown.Token);
+ }
+ catch (OperationCanceledException) when (shutdown.IsCancellationRequested)
+ {
+ }
+ // Any failure ends this connection, not the process: Bermuda only starts this exe again on demand.
+ catch (Exception ex)
+ {
+ Console.WriteLine($"[{AppId}] {ex.GetType().Name}: {ex.Message}");
+ }
+
+ try { await Task.Delay(TimeSpan.FromSeconds(1), shutdown.Token); }
+ catch (OperationCanceledException) { }
+}
+
+async Task RunAsync(Fdc3PipeClient client, CancellationToken cancellationToken)
+{
+ await client.Rpc.JoinUserChannelAsync(new ChannelIdRequest { ChannelId = channel }, client.Headers, cancellationToken: cancellationToken);
+ await client.Rpc.AddContextListenerAsync(
+ new AddContextListenerRequest { ListenerId = "incidents", ContextType = "bermuda.incident" },
+ client.Headers, cancellationToken: cancellationToken);
+ await client.Rpc.AddIntentListenerAsync(
+ new AddIntentListenerRequest { ListenerId = "ack", Intent = "AcknowledgeIncident" },
+ client.Headers, cancellationToken: cancellationToken);
+
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ var e = await client.NextEventAsync(Timeout.InfiniteTimeSpan, cancellationToken);
+ switch (e.KindCase)
+ {
+ case AgentEvent.KindOneofCase.Context:
+ Console.WriteLine($"[{AppId}] context from {e.Context.Source?.AppId}: {e.Context.ContextJson}");
+ await client.Rpc.BroadcastAsync(new BroadcastRequest { ContextJson = Ack(e.Context.ContextJson) },
+ client.Headers, cancellationToken: cancellationToken);
+ break;
+
+ case AgentEvent.KindOneofCase.Intent:
+ Console.WriteLine($"[{AppId}] {e.Intent.Intent} from {e.Intent.Source?.AppId}: {e.Intent.ContextJson}");
+ await client.Rpc.SendIntentResultAsync(
+ new SendIntentResultRequest { ResultId = e.Intent.ResultId, ContextJson = Ack(e.Intent.ContextJson) },
+ client.Headers, cancellationToken: cancellationToken);
+ break;
+ }
+ }
+}
+
+// A payload that is not JSON is acknowledged with of: null instead of tearing the app down.
+static string Ack(string contextJson)
+{
+ JsonElement? of = null;
+ try { of = JsonSerializer.Deserialize(contextJson); }
+ catch (JsonException) { }
+ return JsonSerializer.Serialize(new { type = AckType, of });
+}
diff --git a/src/Bermuda.Web/e2e/fixtures.ts b/src/Bermuda.Web/e2e/fixtures.ts
index f460d02..ecd2ac3 100644
--- a/src/Bermuda.Web/e2e/fixtures.ts
+++ b/src/Bermuda.Web/e2e/fixtures.ts
@@ -3,13 +3,13 @@ import type { Page } from '@playwright/test'
/**
* Override the default `page` fixture to connect to the live WebView2 instance
- * via CDP on port 9222. This lets tests run against the fully wired app
+ * via CDP on port CDP_PORT (default 9222). This lets tests run against the fully wired app
* (Aspire-managed Vite + GraphQL API) without needing a separate web server.
*/
export const test = base.extend<{ page: Page }>({
// biome-ignore lint/correctness/noEmptyPattern: Playwright's fixture signature requires this shape.
page: async ({}, provide: (page: Page) => Promise) => {
- const browser = await chromium.connectOverCDP('http://localhost:9222')
+ const browser = await chromium.connectOverCDP(`http://localhost:${process.env.CDP_PORT ?? '9222'}`)
const context = browser.contexts()[0]
const page = context.pages()[0]
diff --git a/src/Bermuda.Web/e2e/native-app.spec.ts b/src/Bermuda.Web/e2e/native-app.spec.ts
new file mode 100644
index 0000000..a7edd2c
--- /dev/null
+++ b/src/Bermuda.Web/e2e/native-app.spec.ts
@@ -0,0 +1,107 @@
+import type { Page } from '@playwright/test'
+import type { DesktopAgent, Listener } from '@finos/fdc3-standard'
+import type { Context } from '../src/fdc3'
+import { test, expect } from './fixtures'
+
+// Exercises the native side app (src/Bermuda.NativeApp), which Aspire starts
+// next to the host. It connects to the host's gRPC named pipe as
+// "native-incidents", joins fdc3.channel.1 and answers every
+// bermuda.incident context / AcknowledgeIncident intent with a bermuda.native.ack
+// that carries the incident it saw. So a round trip here proves both
+// directions: web -> native (the incident arrives) and native -> web (the ack).
+
+const NATIVE = 'native-incidents'
+const channelButtons = (page: Page) => page.locator('fieldset[aria-label="FDC3 channel"] button')
+
+const incident = (id: string) => ({ type: 'bermuda.incident', id: { incidentId: id } }) as Context
+
+type Ack = { type: string; of: { id: { incidentId: string } } }
+
+test.describe('FDC3 native side app (gRPC named pipe)', () => {
+ test.beforeEach(async ({ page }) => {
+ // Aspire starts the native app after the host, so give it time to connect.
+ await expect
+ .poll(
+ () => page.evaluate(async (appId) => (await (window.fdc3 as DesktopAgent).findInstances({ appId })).length, NATIVE),
+ { timeout: 60_000, message: 'native app never connected to the host agent' },
+ )
+ .toBe(1)
+ })
+
+ test('is in the app directory and reports its metadata', async ({ page }) => {
+ const metadata = await page.evaluate(async (appId) => {
+ const [instance] = await (window.fdc3 as DesktopAgent).findInstances({ appId })
+ return (window.fdc3 as DesktopAgent).getAppMetadata(instance)
+ }, NATIVE)
+ expect(metadata).toMatchObject({ appId: NATIVE, title: 'Native Incidents' })
+ expect(metadata.instanceId).toBeTruthy()
+ })
+
+ test('a web broadcast reaches the native app, which answers on the channel', async ({ page }) => {
+ const first = channelButtons(page).first()
+ await first.click()
+ await expect(first).toHaveAttribute('aria-pressed', 'true')
+
+ try {
+ await page.evaluate(async () => {
+ const w = window as unknown as { acks: { ack: unknown; source?: string }[]; ackListener: Listener }
+ w.acks = []
+ w.ackListener = await (window.fdc3 as DesktopAgent).addContextListener('bermuda.native.ack', (ack, metadata) => {
+ w.acks.push({ ack, source: (metadata?.source as { appId?: string } | undefined)?.appId })
+ })
+ })
+
+ await page.evaluate((ctx) => (window.fdc3 as DesktopAgent).broadcast(ctx), incident('native-1'))
+
+ // The listener may first be replayed an older ack the channel still holds
+ // (no source); the one for this broadcast is the one to look for.
+ const ackFor = () =>
+ page.evaluate(
+ () =>
+ (window as unknown as { acks: { ack: Ack; source?: string }[] }).acks.find(
+ (a) => a.ack.of?.id?.incidentId === 'native-1',
+ ),
+ )
+ await expect.poll(ackFor).toBeDefined()
+ const received = (await ackFor())!
+ expect(received.source).toBe(NATIVE)
+ expect(received.ack.type).toBe('bermuda.native.ack')
+ } finally {
+ await page.evaluate(() => (window as unknown as { ackListener?: Listener }).ackListener?.unsubscribe())
+ await first.click() // leave the channel again
+ await expect(first).toHaveAttribute('aria-pressed', 'false')
+ }
+ })
+
+ test('an intent raised at the native app returns its result', async ({ page }) => {
+ const result = await page.evaluate(
+ async ([ctx, appId]) => {
+ const agent = window.fdc3 as DesktopAgent
+ const [instance] = await agent.findInstances({ appId })
+ const resolution = await agent.raiseIntent('AcknowledgeIncident', ctx as Context, instance)
+ return { source: resolution.source, intent: resolution.intent, result: await resolution.getResult() }
+ },
+ [incident('native-2'), NATIVE] as const,
+ )
+
+ expect(result.source.appId).toBe(NATIVE)
+ expect(result.intent).toBe('AcknowledgeIncident')
+ expect(result.result).toMatchObject({ type: 'bermuda.native.ack', of: { id: { incidentId: 'native-2' } } })
+ })
+
+ test('findIntent lists the native app for its own intent, and the dashboard for ViewIncident', async ({ page }) => {
+ // A running app is listed once per instance and once more as launchable, so compare the distinct app ids.
+ const appsFor = (intent: string) =>
+ page.evaluate(async (name) => [...new Set((await (window.fdc3 as DesktopAgent).findIntent(name)).apps.map((a) => a.appId))], intent)
+ expect(await appsFor('AcknowledgeIncident')).toEqual([NATIVE])
+ expect(await appsFor('ViewIncident')).toEqual(['bermuda-incidents'])
+ })
+
+ test('an untargeted ViewIncident still resolves to the dashboard while the native app is connected', async ({ page }) => {
+ const source = await page.evaluate(async (ctx) => {
+ const resolution = await (window.fdc3 as DesktopAgent).raiseIntent('ViewIncident', ctx as Context)
+ return resolution.source.appId
+ }, incident('native-3'))
+ expect(source).toBe('bermuda-incidents')
+ })
+})
diff --git a/src/Bermuda.Web/playwright.config.ts b/src/Bermuda.Web/playwright.config.ts
index 2b0b9cc..753f81a 100644
--- a/src/Bermuda.Web/playwright.config.ts
+++ b/src/Bermuda.Web/playwright.config.ts
@@ -1,5 +1,9 @@
import { defineConfig } from '@playwright/test'
+// CI picks free ports per run (CDP_PORT, WEB_PORT) so it cannot collide with, or accidentally test, another
+// Bermuda or Aspire instance on the same machine; locally the defaults apply.
+const cdpPort = process.env.CDP_PORT ?? '9222'
+
export default defineConfig({
testDir: './e2e',
fullyParallel: false,
@@ -14,8 +18,9 @@ export default defineConfig({
command: 'aspire run',
cwd: '../..',
// Wait for the WPF host's CDP endpoint — it's the last resource to start
- url: 'http://localhost:9222/json',
- reuseExistingServer: true,
+ url: `http://localhost:${cdpPort}/json`,
+ // Locally an already running `aspire run` is reused; CI always starts its own.
+ reuseExistingServer: !process.env.CI,
timeout: 120_000,
},
projects: [
diff --git a/src/Bermuda.Web/src/fdc3/hostDesktopAgent.ts b/src/Bermuda.Web/src/fdc3/hostDesktopAgent.ts
index c854fb1..334a338 100644
--- a/src/Bermuda.Web/src/fdc3/hostDesktopAgent.ts
+++ b/src/Bermuda.Web/src/fdc3/hostDesktopAgent.ts
@@ -3,7 +3,7 @@
// The Desktop Agent itself lives in the host (src/Bermuda.Fdc3/DesktopAgent.cs);
// this class implements the standard @finos/fdc3-standard DesktopAgent
// interface by forwarding each call as an fdc3.* invoke() command (shapes
-// generated into ipc/__generated__/ipc.d.ts from src/Bermuda.IpcContract/Fdc3Contract.cs)
+// generated into ipc/__generated__/ipc.d.ts from src/Bermuda.Fdc3.Proto/Protos/fdc3.proto)
// and dispatching the host's fdc3.context / fdc3.intent / fdc3.event pushes to
// the handlers registered here. Errors reject with `new Error()`
// (e.g. 'NoAppsFound'), as the standard specifies.
diff --git a/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts b/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts
index 1a29c10..b20e37f 100644
--- a/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts
+++ b/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts
@@ -22,7 +22,7 @@ export interface Fdc3AddIntentListenerRequest {
}
export interface Fdc3ApiEvent {
- details: unknown | null;
+ details?: unknown | null;
eventType: string;
listenerId: string;
type: string;
diff --git a/src/Bermuda/App.xaml.cs b/src/Bermuda/App.xaml.cs
index 8d32507..217b515 100644
--- a/src/Bermuda/App.xaml.cs
+++ b/src/Bermuda/App.xaml.cs
@@ -1,6 +1,7 @@
using System.IO;
using System.Windows;
using Bermuda.Fdc3;
+using Bermuda.Fdc3.Grpc;
using Microsoft.Extensions.Configuration;
namespace Bermuda;
@@ -25,12 +26,69 @@ protected override void OnStartup(StartupEventArgs e)
var fdc3 = new DesktopAgent(directory, launcher);
launcher.Agent = fdc3;
+ StartGrpcHost(config, fdc3);
+ if (_grpcHost is not null)
+ {
+ _nativeApps = new NativeAppHost(_grpcHost.PipeName);
+ launcher.NativeApps = _nativeApps;
+ StartNativeApps(config, directory);
+ }
+
var window = new MainWindow(config, fdc3, MainAppId);
window.Show();
}
+ ///
+ /// Lets native apps join the agent over gRPC on a named pipe. Config:
+ /// FDC3_GRPC_ENABLED (default true) and FDC3_GRPC_PIPE (default per-user,
+ /// see ). A failure to listen
+ /// (e.g. the pipe name is taken) must not stop the app.
+ ///
+ private void StartGrpcHost(IConfiguration config, DesktopAgent agent)
+ {
+ if (bool.TryParse(config["FDC3_GRPC_ENABLED"], out var enabled) && !enabled) return;
+ try
+ {
+ _grpcHost = Task.Run(() => Fdc3GrpcHost.StartAsync(agent, config["FDC3_GRPC_PIPE"])).GetAwaiter().GetResult();
+ }
+ catch (Exception ex)
+ {
+ System.Diagnostics.Debug.WriteLine($"FDC3 gRPC pipe host failed to start: {ex}");
+ }
+ }
+
+ private Fdc3GrpcHost? _grpcHost;
+ private NativeAppHost? _nativeApps;
+
+ ///
+ /// Starts every native side app in the App Directory so they run whenever Bermuda does, however Bermuda was
+ /// started. They ship in the same package. NATIVE_APP_AUTOSTART=false turns this off. An app that is down
+ /// later is started again on demand, when fdc3.open or an intent needs it (see ).
+ ///
+ private void StartNativeApps(IConfiguration config, AppDirectory directory)
+ {
+ if (bool.TryParse(config["NATIVE_APP_AUTOSTART"], out var enabled) && !enabled) return;
+ foreach (var app in directory.Apps.Where(a => NativeAppHost.ResolvePath(a) is not null))
+ {
+ try
+ {
+ _nativeApps!.Start(app);
+ }
+ catch (Exception ex)
+ {
+ System.Diagnostics.Debug.WriteLine($"Native FDC3 app {app.AppId} failed to start: {ex}");
+ }
+ }
+ }
+
protected override void OnExit(ExitEventArgs e)
{
+ _nativeApps?.Dispose();
+
+ if (_grpcHost is { } grpcHost)
+ {
+ Task.Run(() => grpcHost.DisposeAsync().AsTask()).Wait(TimeSpan.FromSeconds(6));
+ }
NotificationService.Clear();
base.OnExit(e);
}
diff --git a/src/Bermuda/Bermuda.csproj b/src/Bermuda/Bermuda.csproj
index 79f0b00..a5a0644 100644
--- a/src/Bermuda/Bermuda.csproj
+++ b/src/Bermuda/Bermuda.csproj
@@ -108,13 +108,30 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -146,14 +167,10 @@
-
-
- <_ManifestText>$([System.IO.File]::ReadAllText('$(MSBuildProjectDirectory)\Package.appxmanifest'))
- <_ManifestText>$([System.Text.RegularExpressions.Regex]::Replace('$(_ManifestText)', '(?s)(<Identity[^>]*?Version=")[^"]*(")', '${1}$(MsixVersion)${2}'))
-
-
+ The tool stamps the Identity Version from MsixVersion (Windows compares that value, not the
+ file name, to decide whether an .appinstaller update is newer) and adds one per native
+ app in fdc3-appd.json. -->
+
@@ -171,15 +188,7 @@
-
- <_AppInstallerPath>$(MsixOutputDir)Bermuda.appinstaller
- <_IdentityName>$([System.Text.RegularExpressions.Regex]::Match('$(_ManifestText)', 'Name="([^"]*)"').Groups[1].Value)
- <_IdentityPublisher>$([System.Text.RegularExpressions.Regex]::Match('$(_ManifestText)', 'Publisher="([^"]*)"').Groups[1].Value)
- <_AppInstallerText>$([System.IO.File]::ReadAllText('$(MSBuildProjectDirectory)\Bermuda.appinstaller.template'))
- <_AppInstallerText>$(_AppInstallerText.Replace('@VERSION@', '$(MsixVersion)').Replace('@NAME@', '$(_IdentityName)').Replace('@PUBLISHER@', '$(_IdentityPublisher)').Replace('@MSIX_URL@', '$(MsixUrl)').Replace('@APPINSTALLER_URL@', '$(AppInstallerUrl)'))
-
-
-
+
diff --git a/src/Bermuda/NativeAppHost.cs b/src/Bermuda/NativeAppHost.cs
new file mode 100644
index 0000000..5829670
--- /dev/null
+++ b/src/Bermuda/NativeAppHost.cs
@@ -0,0 +1,67 @@
+using System.Diagnostics;
+using System.IO;
+using Bermuda.Fdc3;
+
+namespace Bermuda;
+
+///
+/// Starts the native side apps of the App Directory (type "native", details.path relative to this exe) and stops
+/// the ones it started when Bermuda exits. Used at startup and by when
+/// fdc3.open or an intent needs an app that is not running. Each app allows one copy per user, so starting one
+/// that is already running is harmless.
+///
+public sealed class NativeAppHost(string? pipeName) : IDisposable
+{
+ private readonly List _processes = [];
+
+ /// Resolves details.path; it must stay inside the folder Bermuda runs from.
+ public static string? ResolvePath(AppDefinition app)
+ {
+ if (app.Type != "native" || app.Details?.Path is not { Length: > 0 } path) return null;
+ var root = Path.GetFullPath(AppContext.BaseDirectory);
+ var full = Path.GetFullPath(Path.Combine(root, path));
+ return full.StartsWith(root, StringComparison.OrdinalIgnoreCase) && File.Exists(full) ? full : null;
+ }
+
+ /// Starts the app with the pipe name (and, when launched for FDC3, the instance id) in its environment.
+ public void Start(AppDefinition app, string? instanceId = null)
+ {
+ var exe = ResolvePath(app) ?? throw new InvalidOperationException($"App '{app.AppId}' has no native exe inside the package.");
+ var info = new ProcessStartInfo(exe, app.Details!.Arguments ?? "")
+ {
+ UseShellExecute = false,
+ WorkingDirectory = Path.GetDirectoryName(exe)!,
+ };
+ if (!string.IsNullOrWhiteSpace(pipeName)) info.Environment["FDC3_GRPC_PIPE"] = pipeName;
+ if (instanceId is not null) info.Environment["FDC3_INSTANCE_ID"] = instanceId;
+
+ if (Process.Start(info) is { } process)
+ {
+ lock (_processes) _processes.Add(process);
+ }
+ }
+
+ ///
+ /// Closes the apps this host started. One that was already running (so its copy exited at once) or that
+ /// someone else started has a dead handle here and nothing is killed.
+ ///
+ public void Dispose()
+ {
+ lock (_processes)
+ {
+ foreach (var process in _processes)
+ {
+ try
+ {
+ if (!process.HasExited) process.Kill();
+ process.Dispose();
+ }
+ catch (Exception ex)
+ {
+ Debug.WriteLine($"Native FDC3 app did not stop: {ex.Message}");
+ }
+ }
+ _processes.Clear();
+ }
+ }
+}
diff --git a/src/Bermuda/Package.appxmanifest b/src/Bermuda/Package.appxmanifest
index 1c1d414..4d1c6da 100644
--- a/src/Bermuda/Package.appxmanifest
+++ b/src/Bermuda/Package.appxmanifest
@@ -59,6 +59,7 @@
+
diff --git a/src/Bermuda/WindowAppLauncher.cs b/src/Bermuda/WindowAppLauncher.cs
index 20a76e4..f92afaf 100644
--- a/src/Bermuda/WindowAppLauncher.cs
+++ b/src/Bermuda/WindowAppLauncher.cs
@@ -14,9 +14,19 @@ public sealed class WindowAppLauncher(IConfiguration configuration) : IFdc3AppLa
{
public DesktopAgent? Agent { get; set; }
+ /// Starts native apps; null while the gRPC pipe is off, because they could not connect anyway.
+ public NativeAppHost? NativeApps { get; set; }
+
public void Launch(AppDefinition app, string instanceId)
{
if (Agent is null) throw new InvalidOperationException("Launcher not attached to a desktop agent.");
+ if (app.Type == "native" && NativeApps is not null)
+ {
+ // The app connects over the pipe with this instance id (FDC3_INSTANCE_ID), which completes the open.
+ NativeApps.Start(app, instanceId);
+ return;
+ }
+
if (app.Type != "web" || app.Details?.Url is not { Length: > 0 } url)
throw new InvalidOperationException($"App '{app.AppId}' has no web URL to launch.");
diff --git a/src/Bermuda/appsettings.json b/src/Bermuda/appsettings.json
index b9e9841..cba3c3f 100644
--- a/src/Bermuda/appsettings.json
+++ b/src/Bermuda/appsettings.json
@@ -1,5 +1,7 @@
{
"WEB_URL": "http://localhost:5555",
"CDP_PORT": 9222,
- "TITLE_BAR": "client"
+ "TITLE_BAR": "client",
+ "FDC3_GRPC_ENABLED": true,
+ "NATIVE_APP_AUTOSTART": true
}
diff --git a/src/Bermuda/fdc3-appd.json b/src/Bermuda/fdc3-appd.json
index fcfc2bc..6724eed 100644
--- a/src/Bermuda/fdc3-appd.json
+++ b/src/Bermuda/fdc3-appd.json
@@ -1,5 +1,31 @@
{
"applications": [
+ {
+ "appId": "native-incidents",
+ "name": "native-incidents",
+ "title": "Native Incidents",
+ "description": "Sample native side app (Bermuda.NativeApp) connected over gRPC on a named pipe. Acknowledges incidents it receives.",
+ "type": "native",
+ "details": {
+ "path": "Bermuda.NativeApp.exe",
+ "project": "../Bermuda.NativeApp/Bermuda.NativeApp.csproj"
+ },
+ "interop": {
+ "intents": {
+ "listensFor": {
+ "AcknowledgeIncident": {
+ "displayName": "Acknowledge Incident (native)",
+ "contexts": ["bermuda.incident"],
+ "resultType": "bermuda.native.ack"
+ }
+ }
+ },
+ "userChannels": {
+ "broadcasts": ["bermuda.native.ack"],
+ "listensFor": ["bermuda.incident"]
+ }
+ }
+ },
{
"appId": "fdc3-probe",
"name": "fdc3-probe",
diff --git a/src/Bermuda/tools/native-apps.cs b/src/Bermuda/tools/native-apps.cs
new file mode 100644
index 0000000..ca83455
--- /dev/null
+++ b/src/Bermuda/tools/native-apps.cs
@@ -0,0 +1,183 @@
+#:property NuGetAudit=false
+#:property PublishAot=false
+
+// Packaging steps for Bermuda's MSIX that depend on the FDC3 App Directory (fdc3-appd.json).
+// A .NET file-based app, run by the CreateMsix and PublishNativeApps targets in src/Bermuda/Bermuda.csproj:
+//
+// dotnet run --file tools/native-apps.cs -- publish
+// publishes every native app's project (self-contained, win-x64) into outDir, next to Bermuda,
+// and checks that each app's exe is there afterwards
+// dotnet run --file tools/native-apps.cs -- manifest
+// writes dest: the manifest with Identity/@Version = version and one per native app
+// dotnet run --file tools/native-apps.cs -- appinstaller
+// writes the .appinstaller, taking the package name and publisher from the manifest
+//
+// A native app is an entry with "type": "native". It needs details.path (its exe, relative to Bermuda's folder)
+// and, to be built into the package, details.project (the .csproj, relative to the directory file).
+// Every problem is reported as one "native-apps: ..." error line and exit code 1.
+
+using System.Diagnostics;
+using System.Text.Json;
+using System.Text.RegularExpressions;
+using System.Xml;
+using System.Xml.Linq;
+
+try
+{
+ return args switch
+ {
+ ["publish", var appd, var outDir, var configuration] => Publish(LoadApps(appd), outDir, configuration),
+ ["manifest", var appd, var source, var dest, var version] => WriteManifest(LoadApps(appd), source, dest, version),
+ ["appinstaller", var manifest, var template, var dest, var version, var msixUrl, var appInstallerUrl] =>
+ WriteAppInstaller(manifest, template, dest, version, msixUrl, appInstallerUrl),
+ _ => throw new ToolException("usage: publish | manifest | appinstaller "),
+ };
+}
+catch (Exception ex) when (ex is ToolException or JsonException or XmlException or IOException)
+{
+ Console.Error.WriteLine("native-apps: " + ex.Message);
+ return 1;
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+
+static List LoadApps(string appdPath)
+{
+ var baseDir = Path.GetDirectoryName(Path.GetFullPath(appdPath))!;
+ var options = new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true };
+ using var document = JsonDocument.Parse(File.ReadAllText(appdPath), options);
+
+ if (!document.RootElement.TryGetProperty("applications", out var applications) || applications.ValueKind != JsonValueKind.Array)
+ throw new ToolException($"{appdPath} has no \"applications\" array.");
+
+ var apps = new List();
+ foreach (var app in applications.EnumerateArray())
+ {
+ if (Text(app, "type") != "native") continue;
+
+ var id = Text(app, "appId") ?? throw new ToolException("A native app in fdc3-appd.json has no appId.");
+ var details = app.TryGetProperty("details", out var d) && d.ValueKind == JsonValueKind.Object ? d : (JsonElement?)null;
+
+ var exe = details is { } dd ? Text(dd, "path") : null;
+ if (string.IsNullOrWhiteSpace(exe)) throw new ToolException($"Native app '{id}' needs details.path (its exe in the package).");
+ if (Path.IsPathRooted(exe) || exe.Split('/', '\\').Contains(".."))
+ throw new ToolException($"Native app '{id}': details.path '{exe}' must be relative and stay inside Bermuda's folder.");
+
+ string? project = null;
+ if (details is { } pd && Text(pd, "project") is { Length: > 0 } relative)
+ {
+ project = Path.GetFullPath(Path.Combine(baseDir, relative));
+ if (!File.Exists(project)) throw new ToolException($"Native app '{id}': details.project '{relative}' does not exist ({project}).");
+ }
+
+ // Manifest Application ids are letters and digits only, and must be unique.
+ var key = "Native" + Regex.Replace(id, "[^A-Za-z0-9]", "");
+ if (apps.Any(a => a.Key.Equals(key, StringComparison.OrdinalIgnoreCase)))
+ throw new ToolException($"Native app '{id}' maps to the manifest application id '{key}', which another native app already uses.");
+
+ var title = Text(app, "title") ?? id;
+ apps.Add(new NativeApp(id, key, title, Text(app, "description") ?? title, exe.Replace('/', '\\'), project));
+ }
+
+ return apps;
+}
+
+static int Publish(List apps, string outDir, string configuration)
+{
+ foreach (var app in apps)
+ {
+ if (app.Project is null)
+ throw new ToolException($"Native app '{app.AppId}' has no details.project, so it cannot be built into the package.");
+
+ var info = new ProcessStartInfo("dotnet") { UseShellExecute = false };
+ foreach (var arg in new[]
+ {
+ "publish", app.Project, "--configuration", configuration, "--runtime", "win-x64", "--self-contained", "true",
+ "--output", Path.GetFullPath(outDir), "-p:PublishSingleFile=false", "-p:PublishReadyToRun=false", "--nologo",
+ })
+ info.ArgumentList.Add(arg);
+
+ using var process = Process.Start(info) ?? throw new ToolException("Could not start dotnet.");
+ process.WaitForExit();
+ if (process.ExitCode != 0) throw new ToolException($"Publishing '{app.AppId}' ({app.Project}) failed with exit code {process.ExitCode}.");
+ }
+
+ foreach (var app in apps)
+ {
+ if (!File.Exists(Path.Combine(outDir, app.Exe)))
+ throw new ToolException($"'{outDir}' has no {app.Exe} after publishing '{app.AppId}': details.path must be the exe its project produces.");
+ }
+
+ return 0;
+}
+
+static int WriteManifest(List apps, string sourcePath, string destPath, string version)
+{
+ if (!Regex.IsMatch(version, @"^\d+\.\d+\.\d+\.\d+$"))
+ throw new ToolException($"MsixVersion must have four parts (e.g. 1.2.3.0), got '{version}'.");
+
+ var manifest = XDocument.Load(sourcePath, LoadOptions.PreserveWhitespace);
+ var root = manifest.Root ?? throw new ToolException($"{sourcePath} is empty.");
+ XNamespace foundation = root.Name.Namespace;
+ var uap = root.GetNamespaceOfPrefix("uap") ?? throw new ToolException($"{sourcePath} does not declare the uap namespace.");
+
+ // The Identity Version is stamped from the build: Windows compares it, not the file name, to decide whether an
+ // .appinstaller update is newer.
+ (root.Element(foundation + "Identity") ?? throw new ToolException($"{sourcePath} has no Identity element.")).SetAttributeValue("Version", version);
+
+ var applications = root.Element(foundation + "Applications") ?? throw new ToolException($"{sourcePath} has no Applications element.");
+ foreach (var app in apps)
+ {
+ if (applications.Elements(foundation + "Application").Any(a => (string?)a.Attribute("Id") == app.Key))
+ throw new ToolException($"{sourcePath} already declares an application with id '{app.Key}'; it is generated from fdc3-appd.json.");
+
+ // A background app: no Start menu entry (Bermuda starts and stops it), and no startup task of its own.
+ var application = new XElement(foundation + "Application",
+ new XAttribute("Id", app.Key),
+ new XAttribute("Executable", app.Exe),
+ new XAttribute("EntryPoint", "Windows.FullTrustApplication"),
+ new XText("\n "),
+ new XElement(uap + "VisualElements",
+ new XAttribute("DisplayName", app.Title),
+ new XAttribute("Description", app.Description),
+ new XAttribute("BackgroundColor", "transparent"),
+ new XAttribute("Square150x150Logo", @"Assets\Square150x150Logo.png"),
+ new XAttribute("Square44x44Logo", @"Assets\Square44x44Logo.png"),
+ new XAttribute("AppListEntry", "none")),
+ new XText("\n "));
+
+ applications.Add(new XText("\n "), new XComment($" Native FDC3 side app {app.AppId}, from fdc3-appd.json "), new XText("\n "), application, new XText("\n "));
+ }
+
+ Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(destPath))!);
+ using var writer = XmlWriter.Create(destPath, new XmlWriterSettings { Encoding = new System.Text.UTF8Encoding(false) });
+ manifest.Save(writer);
+ return 0;
+}
+
+static int WriteAppInstaller(string manifestPath, string templatePath, string destPath, string version, string msixUrl, string appInstallerUrl)
+{
+ if (string.IsNullOrWhiteSpace(msixUrl)) throw new ToolException("AppInstallerUrl needs MsixUrl as well.");
+
+ var manifest = XDocument.Load(manifestPath);
+ var identity = manifest.Root?.Elements().FirstOrDefault(e => e.Name.LocalName == "Identity")
+ ?? throw new ToolException($"{manifestPath} has no Identity element.");
+
+ var text = File.ReadAllText(templatePath)
+ .Replace("@VERSION@", version)
+ .Replace("@NAME@", (string?)identity.Attribute("Name") ?? throw new ToolException("The manifest Identity has no Name."))
+ .Replace("@PUBLISHER@", System.Security.SecurityElement.Escape((string?)identity.Attribute("Publisher") ?? throw new ToolException("The manifest Identity has no Publisher.")))
+ .Replace("@MSIX_URL@", msixUrl)
+ .Replace("@APPINSTALLER_URL@", appInstallerUrl);
+
+ Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(destPath))!);
+ File.WriteAllText(destPath, text);
+ return 0;
+}
+
+static string? Text(JsonElement element, string name) =>
+ element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
+
+record NativeApp(string AppId, string Key, string Title, string Description, string Exe, string? Project);
+
+sealed class ToolException(string message) : Exception(message);