diff --git a/Dockerfile b/Dockerfile index a9e3054c..e07030de 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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 diff --git a/src/app/api/agent/publish/route.ts b/src/app/api/agent/publish/route.ts new file mode 100644 index 00000000..dd91b284 --- /dev/null +++ b/src/app/api/agent/publish/route.ts @@ -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" + ); +} diff --git a/src/app/api/agent/stream/route.ts b/src/app/api/agent/stream/route.ts new file mode 100644 index 00000000..074f53d4 --- /dev/null +++ b/src/app/api/agent/stream/route.ts @@ -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({ + 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", + }, + }); +} diff --git a/src/app/api/build/route.ts b/src/app/api/build/route.ts new file mode 100644 index 00000000..777ee686 --- /dev/null +++ b/src/app/api/build/route.ts @@ -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, + }, + }); +} diff --git a/src/components/layout/AgentBusSubscriber.tsx b/src/components/layout/AgentBusSubscriber.tsx new file mode 100644 index 00000000..1816ec98 --- /dev/null +++ b/src/components/layout/AgentBusSubscriber.tsx @@ -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; +} diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsx index 69349b65..011fd50d 100644 --- a/src/components/layout/AppShell.tsx +++ b/src/components/layout/AppShell.tsx @@ -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() { +
{isMobile && } diff --git a/src/lib/agent/bus.ts b/src/lib/agent/bus.ts new file mode 100644 index 00000000..c84be609 --- /dev/null +++ b/src/lib/agent/bus.ts @@ -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>(); + + 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());