feat(agent): SSE-based AgentBus for external-tool UI control
Adds an opt-in agent integration surface that lets a trusted external
tool (running as the same logged-in user) drive the running WWV browser
session — fly the globe, toggle layers, focus entities — by POSTing
JSON actions to the server, which fans them out over SSE to every
connected browser tab belonging to that user.
The motivating use case is an MCP server (a Model Context Protocol
adapter): an LLM agent calls a tool like `globe_fly_to({lat, lon})`,
the MCP server posts to `/api/agent/publish`, the browser subscriber
re-emits the action onto the existing client-side `dataBus`, and the
React + Cesium app handles it the same way it would handle any UI
button click. Read-only camera / engine queries already work via the
existing REST surface — this PR adds the missing write path.
What's added:
- `src/lib/agent/bus.ts` — process-local AgentBus singleton, scoped
per user. Subscriptions live in a `Map<userId, Map<connId, sub>>`
so user A's publish never reaches user B's stream, even though
both run on the same Node process.
- `src/app/api/agent/stream/route.ts` — SSE channel. Auth-gated. Sends
initial `:connected` + `retry:3000` directives and a `:hb` heartbeat
every 25s so intermediary proxies (Caddy, Nginx, CDNs) don't tear
down a "stalled" connection.
- `src/app/api/agent/publish/route.ts` — POST endpoint. Accepts JSON
AgentAction shapes (`fly_to`, `face_towards`, `layer_toggle`,
`highlight_layer`, `select_entity`, `ping`), broadcasts only to the
publishing user's bus bucket. Returns `{delivered, subscribers}` so
the caller knows how many tabs received the command.
- `src/components/layout/AgentBusSubscriber.tsx` — browser EventSource
client. Re-emits received actions onto `dataBus` (`cameraGoTo`,
`cameraFaceTowards`, `layerToggled`, `entitySelected`) — every plugin
is already listening on those channels, so no plugin changes needed.
- `AppShell.tsx` — mounts `AgentBusSubscriber` next to the existing
`DataBusSubscriber`. Two lines.
- `src/app/api/build/route.ts` — `/api/build` returns build id +
timestamp + public flag state. Pairs with a one-line console.log
the subscriber prints on mount so a stale-bundle / config-mismatch
is visible at a glance instead of looking like a feature regression.
Default off via `NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED=true`. An unintended
deployment doesn't open a remote-control channel for users who didn't
opt in.
What's changed in the Dockerfile:
- Adds ARG declarations for the new vars (`NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED`,
`NEXT_PUBLIC_WWV_BUILD_ID`, `NEXT_PUBLIC_WWV_BUILD_AT`).
- Stamps the build with millisecond-precision id + ISO timestamp
(`/app/.build-id`, `/app/.build-at`); both copied into the runner
stage for `/api/build` to read.
- Writes `/app/.env.production.local` from declared ARGs *before*
`next build` runs. Docker doesn't reliably promote ARGs into the
Node child-process environment for the build command, so
`process.env.NEXT_PUBLIC_*` references that previously inlined
through Webpack's DefinePlugin sometimes fell back to runtime
polyfill access (`tV.env.NEXT_PUBLIC_X`) that resolves to `undefined`
in the browser. Writing the env file is the documented Next.js path
and behaves the same on every host.
Default-off, no schema changes, no plugin changes, fully backwards-compatible
on operators who don't opt in.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
This commit is contained in:
1 parent
e6305ca92f
commit
1845a1ced9
7 files changed
+447
No files matched your search
+42
@@ -30,6 +30,9 @@ ARG NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL
|
||||
ARG NEXT_PUBLIC_ADSENSE_CLIENT_ID
|
||||
ARG NEXT_PUBLIC_SUPABASE_URL
|
||||
ARG NEXT_PUBLIC_SUPABASE_ANON_KEY
|
||||
ARG NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED
|
||||
ARG NEXT_PUBLIC_WWV_BUILD_ID
|
||||
ARG NEXT_PUBLIC_WWV_BUILD_AT
|
||||
|
||||
# Run our pregenerate schema swap script and then generate Prisma client
|
||||
RUN NEXT_PUBLIC_WWV_EDITION=$NEXT_PUBLIC_WWV_EDITION pnpm run generate
|
||||
@@ -37,6 +40,41 @@ RUN NEXT_PUBLIC_WWV_EDITION=$NEXT_PUBLIC_WWV_EDITION pnpm run generate
|
||||
# Database migrations run at container startup via docker-entrypoint.sh
|
||||
# DATABASE_URL must be set to a PostgreSQL connection string
|
||||
|
||||
# Stamp the build with a millisecond-precision id + iso timestamp. If the
|
||||
# operator hasn't passed NEXT_PUBLIC_WWV_BUILD_ID via build args, generate
|
||||
# one here so /api/build and the client console.log both carry a unique
|
||||
# value per `docker build`.
|
||||
RUN if [ -z "$NEXT_PUBLIC_WWV_BUILD_ID" ]; then \
|
||||
NEXT_PUBLIC_WWV_BUILD_ID="$(date +%s%3N 2>/dev/null || node -e 'process.stdout.write(String(Date.now()))')" ; \
|
||||
fi && \
|
||||
if [ -z "$NEXT_PUBLIC_WWV_BUILD_AT" ]; then \
|
||||
NEXT_PUBLIC_WWV_BUILD_AT="$(node -e 'process.stdout.write(new Date().toISOString())')" ; \
|
||||
fi && \
|
||||
echo "$NEXT_PUBLIC_WWV_BUILD_ID" > /app/.build-id && \
|
||||
echo "$NEXT_PUBLIC_WWV_BUILD_AT" > /app/.build-at
|
||||
|
||||
# Write .env.production.local so Next.js sees every NEXT_PUBLIC_* var
|
||||
# whose ARG was passed in. Docker doesn't reliably promote ARGs into the
|
||||
# build process's environment for `next build` to inline references with
|
||||
# Webpack's DefinePlugin — `process.env.NEXT_PUBLIC_X` either gets the
|
||||
# inlined literal value (when set) or stays as a runtime polyfill access
|
||||
# that resolves to undefined in the browser. Writing the file is the
|
||||
# documented Next.js path and behaves the same on every host.
|
||||
RUN set +e ; { \
|
||||
echo "NEXT_PUBLIC_WWV_BUILD_ID=$(cat /app/.build-id)" ; \
|
||||
echo "NEXT_PUBLIC_WWV_BUILD_AT=$(cat /app/.build-at)" ; \
|
||||
if [ -n "$NEXT_PUBLIC_WWV_EDITION" ]; then echo "NEXT_PUBLIC_WWV_EDITION=$NEXT_PUBLIC_WWV_EDITION" ; fi ; \
|
||||
if [ -n "$NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED" ]; then echo "NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED=$NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED" ; fi ; \
|
||||
if [ -n "$NEXT_PUBLIC_CESIUM_ION_TOKEN" ]; then echo "NEXT_PUBLIC_CESIUM_ION_TOKEN=$NEXT_PUBLIC_CESIUM_ION_TOKEN" ; fi ; \
|
||||
if [ -n "$NEXT_PUBLIC_GOOGLE_MAPS_API_KEY" ]; then echo "NEXT_PUBLIC_GOOGLE_MAPS_API_KEY=$NEXT_PUBLIC_GOOGLE_MAPS_API_KEY" ; fi ; \
|
||||
if [ -n "$NEXT_PUBLIC_BING_MAPS_KEY" ]; then echo "NEXT_PUBLIC_BING_MAPS_KEY=$NEXT_PUBLIC_BING_MAPS_KEY" ; fi ; \
|
||||
if [ -n "$NEXT_PUBLIC_WS_ENGINE_URL" ]; then echo "NEXT_PUBLIC_WS_ENGINE_URL=$NEXT_PUBLIC_WS_ENGINE_URL" ; fi ; \
|
||||
if [ -n "$NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL" ]; then echo "NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL=$NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL" ; fi ; \
|
||||
if [ -n "$NEXT_PUBLIC_ADSENSE_CLIENT_ID" ]; then echo "NEXT_PUBLIC_ADSENSE_CLIENT_ID=$NEXT_PUBLIC_ADSENSE_CLIENT_ID" ; fi ; \
|
||||
if [ -n "$NEXT_PUBLIC_SUPABASE_URL" ]; then echo "NEXT_PUBLIC_SUPABASE_URL=$NEXT_PUBLIC_SUPABASE_URL" ; fi ; \
|
||||
if [ -n "$NEXT_PUBLIC_SUPABASE_ANON_KEY" ]; then echo "NEXT_PUBLIC_SUPABASE_ANON_KEY=$NEXT_PUBLIC_SUPABASE_ANON_KEY" ; fi ; \
|
||||
} > /app/.env.production.local
|
||||
|
||||
# Run Next.js build with Webpack cache mounted
|
||||
RUN --mount=type=cache,target=/app/.next/cache NODE_OPTIONS="--max_old_space_size=3072" pnpm run build
|
||||
RUN node scripts/copy-cesium.mjs
|
||||
@@ -80,6 +118,10 @@ COPY --from=builder /app/public ./public
|
||||
COPY --from=builder /app/scripts/https-proxy.mjs ./scripts/https-proxy.mjs
|
||||
COPY --from=builder /app/scripts/migrate-legacy.mjs ./scripts/migrate-legacy.mjs
|
||||
|
||||
# Build stamp — read by /api/build at runtime.
|
||||
COPY --from=builder /app/.build-id ./.build-id
|
||||
COPY --from=builder /app/.build-at ./.build-at
|
||||
|
||||
# Entrypoint: migrate DB on first run, then start server
|
||||
COPY docker-entrypoint.sh ./docker-entrypoint.sh
|
||||
RUN sed -i 's/\r$//' ./docker-entrypoint.sh
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { agentBus, type AgentAction } from "@/lib/agent/bus";
|
||||
|
||||
/**
|
||||
* POST /api/agent/publish
|
||||
*
|
||||
* Accept an AgentAction from a trusted caller (an external tool acting as
|
||||
* the logged-in user) and broadcast it to every subscriber currently
|
||||
* listening on /api/agent/stream *for the same user*. The browser subscriber
|
||||
* routes the action onto the client-side dataBus, which the React + Cesium
|
||||
* app already drives off of.
|
||||
*
|
||||
* Returns the number of clients the action reached.
|
||||
*
|
||||
* Auth: same session-cookie gate as /stream — only the same user's
|
||||
* sessions can publish or subscribe, and per-user routing is enforced
|
||||
* inside the bus.
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
const userId = session.user.id;
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!isAgentAction(body)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Body must be an AgentAction with a recognized `action` field" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const result = agentBus.publish(userId, body);
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
delivered: result.delivered,
|
||||
subscribers: agentBus.subscribersFor(userId),
|
||||
});
|
||||
}
|
||||
|
||||
function isAgentAction(v: unknown): v is AgentAction {
|
||||
if (!v || typeof v !== "object") return false;
|
||||
const a = (v as { action?: unknown }).action;
|
||||
return (
|
||||
a === "fly_to" ||
|
||||
a === "face_towards" ||
|
||||
a === "layer_toggle" ||
|
||||
a === "highlight_layer" ||
|
||||
a === "select_entity" ||
|
||||
a === "ping"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { agentBus } from "@/lib/agent/bus";
|
||||
|
||||
/**
|
||||
* GET /api/agent/stream
|
||||
*
|
||||
* Server-Sent Events channel that the browser subscribes to. Each connected
|
||||
* client receives every action `/api/agent/publish` broadcasts *for the
|
||||
* same authenticated user*. Multi-tenant safe: user A's stream never sees
|
||||
* user B's publishes.
|
||||
*
|
||||
* Auth-gated via Auth.js session.
|
||||
*/
|
||||
export async function GET() {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return new Response("Unauthorized", { status: 401 });
|
||||
}
|
||||
const userId = session.user.id;
|
||||
|
||||
let unsubscribe = () => {};
|
||||
const id = `${userId}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
// Initial comment + retry hint so EventSource has something to ack
|
||||
// immediately and reconnects fast if the connection drops.
|
||||
controller.enqueue(encoder.encode(":connected\nretry: 3000\n\n"));
|
||||
|
||||
unsubscribe = agentBus.subscribe(userId, {
|
||||
id,
|
||||
write: (chunk) => controller.enqueue(encoder.encode(chunk)),
|
||||
close: () => {
|
||||
try { controller.close(); } catch { /* already closed */ }
|
||||
},
|
||||
});
|
||||
|
||||
// Heartbeat every 25s so intermediaries (Caddy, nginx, CDNs) don't
|
||||
// tear down a "stalled" connection. SSE-aware proxies typically
|
||||
// need a comment line every <30s to keep the channel alive.
|
||||
const heartbeat = setInterval(() => {
|
||||
try {
|
||||
controller.enqueue(encoder.encode(`:hb ${Date.now()}\n\n`));
|
||||
} catch {
|
||||
clearInterval(heartbeat);
|
||||
}
|
||||
}, 25_000);
|
||||
|
||||
(controller as any)._cleanup = () => {
|
||||
clearInterval(heartbeat);
|
||||
unsubscribe();
|
||||
};
|
||||
},
|
||||
cancel() {
|
||||
unsubscribe();
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
/**
|
||||
* GET /api/build
|
||||
*
|
||||
* Lightweight build identification — lets you confirm exactly which build
|
||||
* the running browser tab is talking to. Pair with the `[wwv build] ...`
|
||||
* client-side console log so a refresh mismatch (browser holding stale
|
||||
* chunks) becomes obvious instead of looking like a feature regression.
|
||||
*
|
||||
* Public — no secrets here, just a build stamp + a few public flags useful
|
||||
* for diagnostics.
|
||||
*/
|
||||
|
||||
function readMaybe(p: string): string | null {
|
||||
try {
|
||||
return fs.readFileSync(p, "utf-8").trim();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const BUILD_ID =
|
||||
process.env.NEXT_PUBLIC_WWV_BUILD_ID ??
|
||||
readMaybe(path.join(process.cwd(), ".build-id")) ??
|
||||
"dev";
|
||||
const BUILD_AT =
|
||||
process.env.NEXT_PUBLIC_WWV_BUILD_AT ??
|
||||
readMaybe(path.join(process.cwd(), ".build-at")) ??
|
||||
null;
|
||||
|
||||
export async function GET() {
|
||||
return NextResponse.json({
|
||||
build_id: BUILD_ID,
|
||||
built_at: BUILD_AT,
|
||||
public_flags: {
|
||||
agent_bus_enabled:
|
||||
process.env.NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED === "true",
|
||||
edition: process.env.NEXT_PUBLIC_WWV_EDITION ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* Subscribes to the server's agent SSE channel and re-emits actions onto
|
||||
* the client-side `dataBus`, so an external tool posting to
|
||||
* /api/agent/publish lands on the same event surface the rest of the app
|
||||
* already drives off of. Renders nothing — purely a side-effect component,
|
||||
* paired with `DataBusSubscriber`.
|
||||
*
|
||||
* Disabled unless `NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED === "true"` so an
|
||||
* unintended deployment doesn't open a remote-control channel for users
|
||||
* who didn't opt in.
|
||||
*/
|
||||
|
||||
import { useEffect } from "react";
|
||||
import { dataBus } from "@/core/data/DataBus";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
|
||||
interface FlyToMessage {
|
||||
action: "fly_to";
|
||||
lat: number;
|
||||
lon: number;
|
||||
alt?: number;
|
||||
heading?: number;
|
||||
distance?: number;
|
||||
}
|
||||
interface FaceTowardsMessage {
|
||||
action: "face_towards";
|
||||
lat: number;
|
||||
lon: number;
|
||||
alt?: number;
|
||||
}
|
||||
interface LayerToggleMessage {
|
||||
action: "layer_toggle";
|
||||
pluginId: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
interface HighlightMessage {
|
||||
action: "highlight_layer";
|
||||
pluginId: string;
|
||||
}
|
||||
interface SelectEntityMessage {
|
||||
action: "select_entity";
|
||||
pluginId: string;
|
||||
entityId: string;
|
||||
}
|
||||
interface PingMessage {
|
||||
action: "ping";
|
||||
ts: number;
|
||||
}
|
||||
type AgentMessage =
|
||||
| FlyToMessage
|
||||
| FaceTowardsMessage
|
||||
| LayerToggleMessage
|
||||
| HighlightMessage
|
||||
| SelectEntityMessage
|
||||
| PingMessage;
|
||||
|
||||
function applyAction(msg: AgentMessage): void {
|
||||
switch (msg.action) {
|
||||
case "fly_to":
|
||||
dataBus.emit("cameraGoTo", {
|
||||
lat: msg.lat,
|
||||
lon: msg.lon,
|
||||
alt: msg.alt ?? 0,
|
||||
distance: msg.distance,
|
||||
heading: msg.heading,
|
||||
});
|
||||
return;
|
||||
case "face_towards":
|
||||
dataBus.emit("cameraFaceTowards", {
|
||||
lat: msg.lat,
|
||||
lon: msg.lon,
|
||||
alt: msg.alt ?? 0,
|
||||
});
|
||||
return;
|
||||
case "layer_toggle": {
|
||||
const managed = pluginManager.getPlugin(msg.pluginId);
|
||||
if (!managed) return;
|
||||
if (managed.enabled === msg.enabled) return;
|
||||
pluginManager.togglePlugin(msg.pluginId);
|
||||
return;
|
||||
}
|
||||
case "highlight_layer":
|
||||
dataBus.emit("layerToggled", { pluginId: msg.pluginId, enabled: true });
|
||||
return;
|
||||
case "select_entity": {
|
||||
const entities = pluginManager.getEntities(msg.pluginId);
|
||||
const entity = entities.find((e) => e.id === msg.entityId);
|
||||
if (entity) dataBus.emit("entitySelected", { entity });
|
||||
return;
|
||||
}
|
||||
case "ping":
|
||||
// No-op — useful for an external tool to verify the channel is alive.
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
export function AgentBusSubscriber() {
|
||||
useEffect(() => {
|
||||
// Log build-id + agent-bus state once on mount. A stale-bundle / config
|
||||
// mismatch becomes visible at a glance in the browser console instead
|
||||
// of looking like a feature regression.
|
||||
const buildId = process.env.NEXT_PUBLIC_WWV_BUILD_ID ?? "dev";
|
||||
const builtAt = process.env.NEXT_PUBLIC_WWV_BUILD_AT ?? "";
|
||||
const agentBusEnabled =
|
||||
process.env.NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED === "true";
|
||||
console.log(
|
||||
`[wwv build] id=${buildId} built_at=${builtAt} agent_bus=${agentBusEnabled ? "on" : "off"}`,
|
||||
);
|
||||
|
||||
if (!agentBusEnabled) return;
|
||||
if (typeof EventSource === "undefined") return;
|
||||
|
||||
const es = new EventSource("/api/agent/stream", { withCredentials: true });
|
||||
es.onmessage = (event) => {
|
||||
try {
|
||||
const msg = JSON.parse(event.data) as AgentMessage;
|
||||
applyAction(msg);
|
||||
} catch (err) {
|
||||
console.warn("[AgentBus] malformed message", err);
|
||||
}
|
||||
};
|
||||
es.onerror = (err) => {
|
||||
// EventSource auto-reconnects on its own with the `retry:` value
|
||||
// we send from the server. Just log; don't tear down.
|
||||
console.debug("[AgentBus] stream error (auto-reconnecting)", err);
|
||||
};
|
||||
|
||||
return () => {
|
||||
es.close();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import { useBootSequence } from "@/core/hooks/useBootSequence";
|
||||
import { useIsMobile } from "@/core/hooks/useIsMobile";
|
||||
import { useMarketplaceSync } from "@/core/hooks/useMarketplaceSync";
|
||||
import { DataBusSubscriber } from "./DataBusSubscriber";
|
||||
import { AgentBusSubscriber } from "./AgentBusSubscriber";
|
||||
import { MobileHudBar } from "./MobileHudBar";
|
||||
import { MobileCameraStats } from "./MobileCameraStats";
|
||||
import dynamic from "next/dynamic";
|
||||
@@ -150,6 +151,7 @@ export function AppShell() {
|
||||
|
||||
<TimelineSync />
|
||||
<DataBusSubscriber />
|
||||
<AgentBusSubscriber />
|
||||
|
||||
<Header />
|
||||
{isMobile && <MobileHudBar />}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Server-side AgentBus, scoped per user.
|
||||
*
|
||||
* Holds the set of currently-connected SSE clients keyed by Auth.js user id
|
||||
* and broadcasts agent actions (`fly_to`, `layer_toggle`, etc.) published
|
||||
* via `/api/agent/publish` only to subscribers belonging to the same user
|
||||
* as the publisher. The browser-side subscriber dispatches the received
|
||||
* actions onto the existing `dataBus` so the running React + Cesium app
|
||||
* picks them up the same way it picks up any other UI event.
|
||||
*
|
||||
* Per-user scoping: in a multi-tenant WWV deployment, user A's external
|
||||
* tool publishing to /api/agent/publish must NOT reach user B's open
|
||||
* browser tab. The publish + subscribe routes pass `session.user.id`,
|
||||
* the bus routes deliveries to that user's subscriber set only.
|
||||
*
|
||||
* Process-local in-memory only. Multi-instance deployments would need a
|
||||
* Redis pub/sub adapter; a self-hosted single-process WWV is the primary
|
||||
* target — extending this is straightforward when needed.
|
||||
*/
|
||||
|
||||
export type AgentAction =
|
||||
| { action: "fly_to"; lat: number; lon: number; alt?: number; heading?: number; distance?: number }
|
||||
| { action: "face_towards"; lat: number; lon: number; alt?: number }
|
||||
| { action: "layer_toggle"; pluginId: string; enabled: boolean }
|
||||
| { action: "highlight_layer"; pluginId: string }
|
||||
| { action: "select_entity"; pluginId: string; entityId: string }
|
||||
| { action: "ping"; ts: number };
|
||||
|
||||
interface Subscriber {
|
||||
id: string;
|
||||
write: (chunk: string) => void;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
class AgentBus {
|
||||
/** userId → (connId → Subscriber). Empty inner maps are pruned on unsubscribe. */
|
||||
private byUser = new Map<string, Map<string, Subscriber>>();
|
||||
|
||||
subscribe(userId: string, sub: Subscriber): () => void {
|
||||
let bucket = this.byUser.get(userId);
|
||||
if (!bucket) {
|
||||
bucket = new Map();
|
||||
this.byUser.set(userId, bucket);
|
||||
}
|
||||
bucket.set(sub.id, sub);
|
||||
return () => {
|
||||
const b = this.byUser.get(userId);
|
||||
if (!b) return;
|
||||
b.delete(sub.id);
|
||||
if (b.size === 0) this.byUser.delete(userId);
|
||||
};
|
||||
}
|
||||
|
||||
/** Broadcast an action only to subscribers belonging to the publisher's user. */
|
||||
publish(userId: string, message: AgentAction): { delivered: number } {
|
||||
const bucket = this.byUser.get(userId);
|
||||
if (!bucket) return { delivered: 0 };
|
||||
const payload = `data: ${JSON.stringify(message)}\n\n`;
|
||||
let delivered = 0;
|
||||
for (const sub of bucket.values()) {
|
||||
try {
|
||||
sub.write(payload);
|
||||
delivered++;
|
||||
} catch {
|
||||
bucket.delete(sub.id);
|
||||
}
|
||||
}
|
||||
if (bucket.size === 0) this.byUser.delete(userId);
|
||||
return { delivered };
|
||||
}
|
||||
|
||||
/** Count of currently-subscribed connections for a given user. */
|
||||
subscribersFor(userId: string): number {
|
||||
return this.byUser.get(userId)?.size ?? 0;
|
||||
}
|
||||
|
||||
/** Total connections across all users (for diagnostics). */
|
||||
get totalSubscribers(): number {
|
||||
let n = 0;
|
||||
for (const bucket of this.byUser.values()) n += bucket.size;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
// Module-level singleton. Next.js dev mode hot-reloads modules; using a
|
||||
// global ensures the SSE state survives editor saves so connected browsers
|
||||
// don't drop and reconnect on every code change in development.
|
||||
declare global {
|
||||
// eslint-disable-next-line no-var
|
||||
var __WWV_AGENT_BUS__: AgentBus | undefined;
|
||||
}
|
||||
|
||||
export const agentBus: AgentBus =
|
||||
globalThis.__WWV_AGENT_BUS__ ?? (globalThis.__WWV_AGENT_BUS__ = new AgentBus());
|
||||
Reference in new issue
Block a user