From 443fa9cf667c32743e4d666ef050b124b7f06e1a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 5 Jun 2026 17:06:15 +0100 Subject: [PATCH] Move overview composition from Odin to Gjallar --- README.md | 6 +- docs/architecture.md | 6 +- docs/gjallar.md | 6 +- src/Gjallar/Program.cs | 336 ++++++++++++++++++++++++++++++++++++++++- src/odin/state.cjs | 10 +- src/odin/surface.cjs | 6 +- src/odin/websocket.cjs | 158 ++++++++++++++++--- 7 files changed, 491 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index b9612b5..1555460 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ Eve/CultUI deck and renders the live display. ## Gjallar Gjallar is the herald display daemon that runs on Nightwing. Odin sees the -Verses, accepts provider surfaces, and publishes the `odin.allseer` deck. +Verses, accepts provider surfaces, and publishes the `odin.providers` catalog. Gjallar talks to Odin, enumerates active providers, composes the multi-scale tiled dashboard, owns the marquee and dense character-level update behavior, and writes the visible framebuffer. @@ -60,7 +60,7 @@ Local package surfaces: ## Authority Map -- Owner: Odin owns the network-wide Verse registry, schema catalog index, translation map, and the accepted `odin.allseer` Eve surface. +- Owner: Odin owns the network-wide Verse registry, schema catalog index, translation map, and accepted provider catalog/proxy surfaces. - Inputs: CultMesh/CultNet peer announcements, schema catalog responses, local host probes, Docker/ADB host facts, SSH-reachable ops hosts, Mimir's normalized Eve observation ledger, and later direct Verse subscriptions. - Outputs: CultCache-backed Odin state, CultMesh documents, CultNet schema/catalog messages, and an Eve-compatible `/eve/deck` surface for dashboards. - Derived state: Gjallar's attached Nightwing display, browser dashboards, and future Eve clients are projections of Odin state and provider-owned Eve/CultUI surfaces. @@ -93,7 +93,7 @@ State and logs live under ignored `scratch/odin/`. The first executable is deliberately narrow: -- publishes provider `odin.allseer`; +- publishes provider catalog `odin.providers`; - writes the latest surface to `scratch/odin/latest-surface.json`; - persists the same document through local CultMesh/CultCache when `CultLib` packages are available at `E:\Projects\CultLib\packages`; - observes Starfire Docker, Periwinkle ADB, Nightwing services/GPU, Raven, EVE, and Yggdrasil reachability; diff --git a/docs/architecture.md b/docs/architecture.md index eb568b9..cb31251 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -68,7 +68,7 @@ Odin's executable body is split by ownership: - `src/odin/interfaces.cjs`: Eve provider manifest discovery, provider WebSocket fetches, provider advertisements, and CultMesh interface bindings. - `src/odin/layout.cjs`: `odin.interface_layout.v1` read/write and merge policy. - `src/odin/surface.cjs`: `gamecult.eve.surface.v1` tree projection. -- `src/odin/state.cjs`: one refresh's input records into `odin.allseer` dashboard state. +- `src/odin/state.cjs`: one refresh's input records into Odin's provider catalog/proxy state. - `src/odin/websocket.cjs`: Eve deck HTTP/WebSocket serving and client WebSocket helpers. The entrypoint is not allowed to grow new probe, surface, provider, layout, or renderer policy. If a new owner is needed, name the owner and its invariant before adding code. @@ -217,7 +217,7 @@ asgard../ Examples: ```text -asgard.starfire.odin/eve/allseer +asgard.starfire.odin/eve/providers asgard.starfire.bifrost/eve/tui asgard.starfire.bifrost/eve/gui asgard.yggdrasil.streampixels/eve/tui @@ -248,7 +248,7 @@ tree has children. ## Current Observation Surface -Odin tails Mimir's normalized observation JSONL at `E:\Projects\Mimir\artifacts\runtime\periwinkle-cultmesh-sensors.out.log` by default. It accepts the typed CultMesh records `mimir.eve_sensor_observation.v1` and `mimir.eve_media_observation.v1`, keeps only the latest record for each `(deviceId, streamId, kind)`, and publishes those summaries as `observation-stream` nodes inside `odin.allseer`. Streams are considered active for 120 seconds by default so a compact dashboard refresh does not turn a briefly quiet sensor into false red noise. +Odin tails Mimir's normalized observation JSONL at `E:\Projects\Mimir\artifacts\runtime\periwinkle-cultmesh-sensors.out.log` by default. It accepts the typed CultMesh records `mimir.eve_sensor_observation.v1` and `mimir.eve_media_observation.v1`, keeps only the latest record for each `(deviceId, streamId, kind)`, and publishes those summaries as provider-catalog observation records. Streams are considered active for 120 seconds by default so a compact dashboard refresh does not turn a briefly quiet sensor into false red noise. This is an ingest projection, not a new capture authority. Device clients still own capture, Mimir still owns the evidence ledger, and Odin only publishes the dashboard-ready state that the Eve GUI and Nightwing TUI lower. diff --git a/docs/gjallar.md b/docs/gjallar.md index 4217b51..35e6625 100644 --- a/docs/gjallar.md +++ b/docs/gjallar.md @@ -36,8 +36,8 @@ body they are being lowered into. - `src/Gjallar` is Gjallar's executable C# runtime. - `Gjallar.csproj` builds the Nightwing framebuffer compositor. -- Gjallar consumes Odin's deck over WebSocket, defaulting to - `ws://192.168.1.66:8797/eve/deck` and provider `odin.allseer`. +- Gjallar consumes Odin's provider catalog over HTTP/WebSocket, defaulting to + `ws://192.168.1.66:8797/eve/deck` with no fixed provider id. - The old Rust `crates/gjallar-daemon` and `gjallar.overview` records were cut because they created an intermediate composition owner that did nothing Odin and Gjallar's live renderer could not explain directly. @@ -61,7 +61,7 @@ dotnet publish .\src\Gjallar\Gjallar.csproj -c Release -r linux-x64 --self-conta ```text provider-owned Eve/CultUI surfaces - -> Odin discovery and allseer deck + -> Odin discovery and provider catalog/proxy surfaces -> Gjallar provider enumeration, packing, marquee, and framebuffer lowering -> Nightwing visible display ``` diff --git a/src/Gjallar/Program.cs b/src/Gjallar/Program.cs index 2cbfd99..e89a225 100644 --- a/src/Gjallar/Program.cs +++ b/src/Gjallar/Program.cs @@ -17,6 +17,7 @@ internal sealed record GjallarConfig( string Url, string ProviderId, int RefreshHz, + int CatalogRefreshSeconds, string StatusPath, string FrameDumpPath, int Frames, @@ -27,8 +28,9 @@ internal sealed record GjallarConfig( public static GjallarConfig Parse(IReadOnlyList args) => new( StringArg(args, "--fb", "/dev/fb0"), StringArg(args, "--url", "ws://192.168.1.66:8797/eve/deck"), - StringArg(args, "--provider", "odin.allseer"), + StringArg(args, "--provider", ""), IntArg(args, "--refresh-hz", 2), + IntArg(args, "--catalog-refresh-seconds", 5), StringArg(args, "--stats-path", "/var/log/gjallar.status"), StringArg(args, "--frame-dump-path", ""), IntArg(args, "--frames", 0), @@ -56,6 +58,7 @@ internal sealed record GjallarConfig( internal sealed class GjallarRenderer : IDisposable { private static readonly JsonSerializerOptions StatusJson = new() { WriteIndented = true }; + private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true }; private readonly GjallarConfig config; private readonly FramebufferDevice framebuffer; private readonly FontAtlas fonts; @@ -66,6 +69,10 @@ internal sealed class GjallarRenderer : IDisposable private int frameIndex; private long lastStatusTick; private int lastStatusFrame; + private int latestCatalogProviders; + private int latestComposedProviders; + private string lastReceiveStatus = "starting"; + private string lastReceiveError = ""; private SceneCache? sceneCache; private FrameTimings lastTimings; @@ -132,6 +139,12 @@ internal sealed class GjallarRenderer : IDisposable private async Task ConnectReceiveLoopAsync(CancellationToken token) { + if (string.IsNullOrWhiteSpace(config.ProviderId)) + { + await ConnectCatalogReceiveLoopAsync(token).ConfigureAwait(false); + return; + } + var target = ProviderUri(config.Url, config.ProviderId); while (!token.IsCancellationRequested) { @@ -139,19 +152,274 @@ internal sealed class GjallarRenderer : IDisposable { using var socket = new ClientWebSocket(); await socket.ConnectAsync(target, token).ConfigureAwait(false); + lastReceiveStatus = $"connected:{config.ProviderId}"; + lastReceiveError = ""; await ReceiveLoopAsync(socket, token).ConfigureAwait(false); } catch (OperationCanceledException) when (token.IsCancellationRequested) { return; } - catch when (!token.IsCancellationRequested) + catch (Exception error) when (!token.IsCancellationRequested) { + lastReceiveStatus = $"connect-error:{config.ProviderId}"; + lastReceiveError = error.Message; await Task.Delay(TimeSpan.FromSeconds(2), token).ConfigureAwait(false); } } } + private async Task ConnectCatalogReceiveLoopAsync(CancellationToken token) + { + while (!token.IsCancellationRequested) + { + try + { + var catalog = await ReadProviderCatalogAsync(token).ConfigureAwait(false); + latestCatalogProviders = catalog.Providers.Count; + var states = new List(); + foreach (var provider in catalog.Providers.Where(IsDisplayProvider)) + { + var frame = await TryFetchProviderFrameAsync(provider, token).ConfigureAwait(false); + if (frame != null) + { + states.Add(frame); + } + } + + Interlocked.Exchange(ref latestStateJson, BuildGjallarSurface(catalog, states)); + latestComposedProviders = states.Count; + lastReceiveStatus = "catalog-composed"; + lastReceiveError = ""; + } + catch (Exception error) when (!token.IsCancellationRequested) + { + lastReceiveStatus = "catalog-error"; + lastReceiveError = error.Message; + // A missed catalog pass should make the display stale, not kill the horn. + } + + await Task.Delay(TimeSpan.FromSeconds(Math.Max(1, config.CatalogRefreshSeconds)), token).ConfigureAwait(false); + } + } + + private async Task ReadProviderCatalogAsync(CancellationToken token) + { + using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(5) }; + var json = await client.GetStringAsync(ProviderCatalogUri(), token).ConfigureAwait(false); + return JsonSerializer.Deserialize(json, JsonOptions) ?? new ProviderCatalog([]); + } + + private static bool IsDisplayProvider(ProviderCatalogEntry provider) => + !string.IsNullOrWhiteSpace(provider.Id) && + ((provider.Capabilities?.Any(static capability => string.Equals(capability, "cultui-surface", StringComparison.OrdinalIgnoreCase)) ?? false) || + string.Equals(provider.Endpoint, $"/eve/deck/{Uri.EscapeDataString(provider.Id)}", StringComparison.OrdinalIgnoreCase) || + string.Equals(provider.TransportEndpoint, $"/eve/deck/{Uri.EscapeDataString(provider.Id)}", StringComparison.OrdinalIgnoreCase)); + + private Uri ProviderCatalogUri() + { + var uri = new Uri(config.Url.Replace("ws://", "http://", StringComparison.OrdinalIgnoreCase).Replace("wss://", "https://", StringComparison.OrdinalIgnoreCase)); + var builder = new UriBuilder(uri) + { + Path = "/eve/deck/providers", + Query = "", + }; + return builder.Uri; + } + + private async Task TryFetchProviderFrameAsync(ProviderCatalogEntry provider, CancellationToken token) + { + try + { + using var socket = new ClientWebSocket(); + await socket.ConnectAsync(ProviderDeckUri(provider), token).ConfigureAwait(false); + var bytes = await ReadTextFrameAsync(socket, token).ConfigureAwait(false); + using var state = JsonDocument.Parse(bytes); + if (!state.RootElement.TryGetProperty("surface", out var surface) || + !surface.TryGetProperty("root", out var root)) + { + return null; + } + + return new ProviderFrame(provider, state.RootElement.Clone(), root.Clone()); + } + catch when (!token.IsCancellationRequested) + { + return ProviderFrame.Unavailable(provider); + } + } + + private Uri ProviderDeckUri(ProviderCatalogEntry provider) + { + var endpoint = !string.IsNullOrWhiteSpace(provider.TransportEndpoint) + ? provider.TransportEndpoint + : provider.Endpoint; + if (string.IsNullOrWhiteSpace(endpoint)) + { + endpoint = $"/eve/deck/{Uri.EscapeDataString(provider.Id)}"; + } + + if (Uri.TryCreate(endpoint, UriKind.Absolute, out var absolute)) + { + return absolute.Scheme is "http" or "https" + ? new Uri(endpoint.Replace("http://", "ws://", StringComparison.OrdinalIgnoreCase).Replace("https://", "wss://", StringComparison.OrdinalIgnoreCase)) + : absolute; + } + + var baseUri = new Uri(config.Url); + var builder = new UriBuilder(baseUri) + { + Path = endpoint.StartsWith("/", StringComparison.Ordinal) ? endpoint : $"/{endpoint}", + Query = "", + }; + return builder.Uri; + } + + private static async Task ReadTextFrameAsync(ClientWebSocket socket, CancellationToken token) + { + var buffer = ArrayPool.Shared.Rent(1024 * 1024); + try + { + using var body = new MemoryStream(); + WebSocketReceiveResult result; + do + { + result = await socket.ReceiveAsync(buffer, token).ConfigureAwait(false); + if (result.MessageType == WebSocketMessageType.Close) + { + return []; + } + + body.Write(buffer, 0, result.Count); + } + while (!result.EndOfMessage); + + return result.MessageType == WebSocketMessageType.Text ? body.ToArray() : []; + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + private static byte[] BuildGjallarSurface(ProviderCatalog catalog, IReadOnlyList frames) + { + var children = frames.Select(frame => new + { + id = $"gjallar-interface-{StableId(frame.Provider.Id)}", + kind = "interface", + props = new + { + title = frame.Provider.Title ?? frame.Provider.Id, + providerId = frame.Provider.Id, + status = frame.Provider.Status ?? "unknown", + source = frame.Provider.Endpoint ?? "", + updatedAt = frame.State.TryGetProperty("updatedAt", out var updatedAt) ? ValueString(updatedAt) : "", + layout = new + { + density = "dense", + viewportMode = "nested-scroll", + }, + }, + children = new[] { frame.Root }, + }).ToArray(); + + var document = new + { + type = "dashboard-state", + schema = "gamecult.gjallar.overview.v1", + providerId = "gjallar.overview", + title = "Gjallar", + version = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), + updatedAt = DateTimeOffset.UtcNow.ToString("O", CultureInfo.InvariantCulture), + providerCatalog = catalog.Providers, + surface = new + { + schema = "gamecult.eve.surface.v1", + id = "gjallar.overview.surface", + title = "Gjallar", + root = new + { + id = "gjallar-overview-root", + kind = "dashboard", + props = new + { + title = "Gjallar", + summary = $"{frames.Count} provider surfaces", + marqueeText = MarqueeText(frames), + }, + children, + }, + assets = Array.Empty(), + }, + }; + return JsonSerializer.SerializeToUtf8Bytes(document, JsonOptions); + } + + private static string MarqueeText(IEnumerable frames) => + string.Join(" / ", frames + .Select(frame => SurfaceText(frame.Root)) + .Where(static text => !string.IsNullOrWhiteSpace(text)) + .Take(24)); + + private static string SurfaceText(JsonElement root) + { + var parts = new List(); + Visit(root, node => + { + if (!node.TryGetProperty("props", out var props) || props.ValueKind != JsonValueKind.Object) + { + return; + } + foreach (var key in new[] { "marqueeText", "title", "text", "summary", "value" }) + { + if (props.TryGetProperty(key, out var value)) + { + var text = ValueString(value); + if (!string.IsNullOrWhiteSpace(text)) + { + parts.Add(text); + } + } + } + }); + return string.Join(" ", parts).Trim(); + } + + private static void Visit(JsonElement node, Action visitor) + { + if (node.ValueKind != JsonValueKind.Object) + { + return; + } + visitor(node); + if (!node.TryGetProperty("children", out var children) || children.ValueKind != JsonValueKind.Array) + { + return; + } + foreach (var child in children.EnumerateArray()) + { + Visit(child, visitor); + } + } + + private static string StableId(string value) => + string.Join("-", value + .Trim() + .ToLowerInvariant() + .Split() + .Select(part => new string(part.Select(static ch => char.IsLetterOrDigit(ch) ? ch : '-').ToArray()).Trim('-')) + .Where(static part => part.Length > 0)); + + private static string ValueString(JsonElement value) => value.ValueKind switch + { + JsonValueKind.String => value.GetString() ?? "", + JsonValueKind.Number => value.ToString(), + JsonValueKind.True => "true", + JsonValueKind.False => "false", + _ => "", + }; + private async Task ReceiveLoopAsync(ClientWebSocket socket, CancellationToken token) { var buffer = ArrayPool.Shared.Rent(1024 * 1024); @@ -264,6 +532,19 @@ internal sealed class GjallarRenderer : IDisposable framebuffer = new { framebuffer.Width, framebuffer.Height, bytes = framebuffer.BufferBytes }, refreshHz = config.RefreshHz, measuredFps = Math.Round(measuredFps, 2), + receive = new + { + status = lastReceiveStatus, + error = lastReceiveError, + catalogProviders = latestCatalogProviders, + composedProviders = latestComposedProviders, + stateBytes = Volatile.Read(ref latestStateJson)?.Length ?? 0, + }, + scene = new + { + panels = sceneCache?.Panels.Count ?? 0, + gutterCells = sceneCache?.GutterCells.Count ?? 0, + }, cultMathNative = Voronoi.NativeAvailable, paintMs = Math.Round(paintMs, 2), timings = new @@ -316,6 +597,57 @@ internal sealed class GjallarRenderer : IDisposable internal sealed record SceneCache(byte[] StateJson, IReadOnlyList Panels, IReadOnlyList GutterCells, string MarqueeTape); internal readonly record struct FrameTimings(double CopyMs, double DecorMs, double GutterMs, double PresentMs); +internal sealed record ProviderCatalog(IReadOnlyList Providers); +internal sealed record ProviderCatalogEntry( + string Id, + string? Title, + string? Description, + string? Version, + string? Endpoint, + string? TransportEndpoint, + IReadOnlyList? Capabilities, + string? Status, + string? UpdatedAt); + +internal sealed record ProviderFrame(ProviderCatalogEntry Provider, JsonElement State, JsonElement Root) +{ + public static ProviderFrame Unavailable(ProviderCatalogEntry provider) + { + var document = JsonDocument.Parse(JsonSerializer.Serialize(new + { + type = "dashboard-state", + providerId = provider.Id, + title = provider.Title ?? provider.Id, + updatedAt = DateTimeOffset.UtcNow.ToString("O", CultureInfo.InvariantCulture), + surface = new + { + root = new + { + id = $"unavailable-{provider.Id}", + kind = "pane", + props = new + { + title = provider.Title ?? provider.Id, + status = "unavailable", + }, + children = new[] + { + new + { + id = $"unavailable-detail-{provider.Id}", + kind = "text", + props = new { text = "provider surface unavailable" }, + children = Array.Empty(), + }, + }, + }, + }, + })); + var state = document.RootElement.Clone(); + var root = document.RootElement.GetProperty("surface").GetProperty("root").Clone(); + return new ProviderFrame(provider, state, root); + } +} internal sealed class FrameDocument { diff --git a/src/odin/state.cjs b/src/odin/state.cjs index d0d8455..4f14f9a 100644 --- a/src/odin/state.cjs +++ b/src/odin/state.cjs @@ -23,8 +23,8 @@ function createStateBuilder({ cachePath, interfaceDiscovery, layoutStore, observ return { type: "dashboard-state", schema: "mimir.eve_dashboard_state.v1", - providerId: "odin.allseer", - title: "Odin All-Seer", + providerId: "odin.providers", + title: "Odin Provider Catalog", version, updatedAt: new Date().toISOString(), selectedNodeId: "coordinator-starting", @@ -43,7 +43,7 @@ function createStateBuilder({ cachePath, interfaceDiscovery, layoutStore, observ adbSnapshot(), hostChecks(), remoteServices("ygg", ["nginx", "streampixels-web", "streampixels-service", "heimdall", "repixelizer-gui", "bifrost"]), - remoteServices("nightwing", ["ssh", "nightwing-eve-dashboard", "nightwing-eve-browser-reference", "gamecult-visible-ops", "docker"]), + remoteServices("nightwing", ["ssh", "nightwing-eve-dashboard", "nightwing-eve-browser-reference", "gjallar", "docker"]), remoteGpu("nightwing"), interfaceDiscovery.discoverInterfaces(), interfaceDiscovery.discoverProviderAdvertisements(), @@ -88,8 +88,8 @@ function createStateBuilder({ cachePath, interfaceDiscovery, layoutStore, observ return { type: "dashboard-state", schema: "mimir.eve_dashboard_state.v1", - providerId: "odin.allseer", - title: "Odin All-Seer", + providerId: "odin.providers", + title: "Odin Provider Catalog", version, updatedAt: observedAt, selectedNodeId: "verse-starfire.local", diff --git a/src/odin/surface.cjs b/src/odin/surface.cjs index 2dcbb3b..6ca43e3 100644 --- a/src/odin/surface.cjs +++ b/src/odin/surface.cjs @@ -15,16 +15,16 @@ function buildSurface({ observedAt, docker, adb, hosts, yggdrasilServices, verse id: "network-root", kind: "dashboard", props: { - title: "Odin All-Seer", + title: "Odin Provider Catalog", observedAt, summary: `${activeInterfaces.length} Eve surfaces / ${activeObservationStreams.length} live streams`, marqueeText: marketMarqueeText(interfaces), - layout: fullscreenLayoutIntent("odin.allseer", -100), + layout: fullscreenLayoutIntent("odin.providers", -100), presentation: { theme: "bifrost-pride", frame: "animated-rainbow", dividerMotion: "bifrost-rainbow-dance", - intent: "Nightwing Odin Overview should render with an animated rainbow frame and dancing dividers; renderer owns lowering, Odin owns truth.", + intent: "Odin preserves provider-owned surfaces for catalog/proxy access; Gjallar owns Nightwing overview composition and lowering.", }, }, children: [ diff --git a/src/odin/websocket.cjs b/src/odin/websocket.cjs index af1cfd0..7b09208 100644 --- a/src/odin/websocket.cjs +++ b/src/odin/websocket.cjs @@ -25,16 +25,7 @@ function handleHttp(req, res, getCurrentState, getHealth) { if (req.url === "/eve/deck/providers") { res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify({ - providers: [{ - id: currentState.providerId, - title: currentState.title, - description: "Odin central coordinator for GameCult Verse discovery, schema awareness, translation, and network status.", - version: String(currentState.version), - endpoint: "/eve/deck", - capabilities: ["network-status", "cultmesh-verses", "cultui-surface"], - usesCultMesh: true, - transport: "CultMesh durable surface + Eve WebSocket", - }, ...providerCatalogFromState(currentState)], + providers: providerCatalogFromState(currentState), })); return; } @@ -57,23 +48,24 @@ function providerCatalogFromState(state) { ) { const props = child.props || {}; const embeddedRoot = Array.isArray(child.children) ? child.children[0] : null; - providers.set(String(props.providerId), { - id: String(props.providerId), + const providerId = String(props.providerId); + providers.set(providerId, { + id: providerId, title: String(props.title || props.providerId), description: String(props.detail || "Provider-owned Eve/CultUI interface discovered by Odin."), version: String(props.version || 0), - endpoint: props.cultMeshAddress || props.locatedService || props.source || "/eve/deck", + endpoint: `/eve/deck/${encodeURIComponent(providerId)}`, canonicalService: props.canonicalService || null, locatedService: props.locatedService || null, cultMeshAddress: props.cultMeshAddress || null, endpoints: Array.isArray(props.endpoints) ? props.endpoints : [], routes: Array.isArray(props.routes) ? props.routes : [], - transportEndpoint: transportEndpoint(props), + transportEndpoint: `/eve/deck/${encodeURIComponent(providerId)}`, capabilities: providerCapabilities(embeddedRoot), usesCultMesh: String(props.source || "").startsWith("cultmesh:"), transport: String(props.source || "").startsWith("cultmesh:") - ? "CultMesh Eve interface binding" - : "Eve WebSocket provider", + ? "Odin provider proxy from CultMesh Eve interface binding" + : "Odin provider proxy from Eve WebSocket provider", status: props.status || "unknown", updatedAt: props.updatedAt || state.updatedAt, source: props.source || "", @@ -131,13 +123,143 @@ function handleUpgrade(req, socket, clients, getCurrentState, applyClientCommand "Connection: Upgrade\r\n" + `Sec-WebSocket-Accept: ${accept}\r\n\r\n`, ); + socket.odinRequestUrl = req.url; clients.add(socket); - sendFrame(socket, 0x1, Buffer.from(JSON.stringify(getCurrentState()), "utf8")); + sendFrame(socket, 0x1, Buffer.from(JSON.stringify(stateForRequest(getCurrentState(), req.url)), "utf8")); socket.on("data", (chunk) => handleClientFrame(socket, chunk, clients, applyClientCommand)); socket.on("close", () => clients.delete(socket)); socket.on("error", () => clients.delete(socket)); } +function stateForRequest(currentState, requestUrl) { + const providerId = providerIdFromDeckUrl(requestUrl); + if (!providerId) { + return odinCatalogState(currentState); + } + const providerState = providerStateFromCurrentState(currentState, providerId); + return providerState || unavailableProviderState(providerId, "provider not present in Odin catalog"); +} + +function providerIdFromDeckUrl(requestUrl) { + const path = String(requestUrl || "").split("?")[0].replace(/\/+$/, ""); + if (path === "/eve/deck") { + return ""; + } + const prefix = "/eve/deck/"; + if (!path.startsWith(prefix)) { + return ""; + } + return decodeURIComponent(path.slice(prefix.length)); +} + +function odinCatalogState(currentState) { + const providers = providerCatalogFromState(currentState); + return { + type: "dashboard-state", + schema: "gamecult.odin.provider_catalog.v1", + providerId: "odin.providers", + title: "Odin Provider Catalog", + version: currentState.version, + updatedAt: currentState.updatedAt, + providerCatalog: providers, + surface: { + schema: "gamecult.eve.surface.v1", + id: "odin.provider-catalog.surface", + title: "Odin Provider Catalog", + root: { + id: "odin-provider-catalog-root", + kind: "dashboard", + props: { + title: "Odin Providers", + summary: `${providers.length} provider surfaces discovered`, + }, + children: providers.map((provider) => ({ + id: `provider-${stableSurfaceId(provider.id)}`, + kind: "text", + props: { + text: `${provider.id} ${provider.status || "unknown"} ${provider.title || ""}`.trim(), + providerId: provider.id, + }, + children: [], + })), + }, + assets: [], + }, + }; +} + +function providerStateFromCurrentState(currentState, providerId) { + const child = providerInterfaceChild(currentState, providerId); + if (!child) { + return null; + } + const props = child.props || {}; + const root = Array.isArray(child.children) ? child.children[0] : null; + if (!root) { + return null; + } + return { + type: "dashboard-state", + schema: "gamecult.eve.provider_surface_proxy.v1", + providerId, + title: props.title || providerId, + version: props.version || currentState.version, + updatedAt: props.updatedAt || currentState.updatedAt, + surface: { + schema: "gamecult.eve.surface.v1", + id: `proxied-${providerId}`, + title: props.title || providerId, + root, + assets: [], + }, + }; +} + +function providerInterfaceChild(currentState, providerId) { + const root = currentState?.surface?.root; + const children = Array.isArray(root?.children) ? root.children : []; + return children.find((child) => child?.kind === "interface" && String(child.props?.providerId || "") === providerId); +} + +function unavailableProviderState(providerId, detail) { + return { + type: "dashboard-state", + schema: "gamecult.eve.provider_surface_proxy.v1", + providerId, + title: providerId, + version: 0, + updatedAt: new Date().toISOString(), + surface: { + schema: "gamecult.eve.surface.v1", + id: `unavailable-${stableSurfaceId(providerId)}`, + title: providerId, + root: { + id: `unavailable-${stableSurfaceId(providerId)}-root`, + kind: "pane", + props: { + title: providerId, + status: "unavailable", + }, + children: [{ + id: `unavailable-${stableSurfaceId(providerId)}-detail`, + kind: "text", + props: { text: detail }, + children: [], + }], + }, + assets: [], + }, + }; +} + +function stableSurfaceId(value) { + return String(value || "provider") + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") || "provider"; +} + function handleClientFrame(socket, chunk, clients, applyClientCommand) { const frame = tryReadFrame(chunk); const opcode = frame?.opcode ?? (chunk[0] & 0x0f); @@ -158,9 +280,9 @@ function handleClientFrame(socket, chunk, clients, applyClientCommand) { } function broadcastState(clients, state) { - const payload = Buffer.from(JSON.stringify(state), "utf8"); for (const client of [...clients]) { try { + const payload = Buffer.from(JSON.stringify(stateForRequest(state, client.odinRequestUrl || "/eve/deck")), "utf8"); sendFrame(client, 0x1, payload); } catch { clients.delete(client);