From 6494ac1a5cc4828083105974c13db550c885c7ab Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 18 Oct 2026 07:17:45 +0000 Subject: [PATCH 1/4] =?UTF-8?q?feat(mesh):=20Settings=20=E2=80=BA=20Nodes?= =?UTF-8?q?=20and=20Network=20in=20the=20web=20app?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nodes adds a machine (role, optional name and namespaces, Enter submits) and shows its install line once with Copy and how long it works; lists every machine, this one first, with its address, when it was last seen, Nebula, its Lens version, machine, certificate, namespaces and log; renames in place, removes without a dialog with Undo, and withdraws unused join tokens. Network shows whether the mesh is off, running, or on without its container (with the line to start it where there's no upgrade agent), the CA and this machine's mesh address, the mesh settings and what Nebula said. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01GTrHPwWHtEvFJFq3M1YpH4 --- docs/mesh.md | 21 +- .../__tests__/settings-mesh.test.tsx | 300 +++++++++++++ .../components/settings/bodies.tsx | 138 +++++- nextjs-frontend/components/settings/find.ts | 1 + .../components/settings/mesh-nodes.tsx | 399 ++++++++++++++++++ nextjs-frontend/components/settings/model.ts | 98 +++++ .../components/settings/section.tsx | 2 +- .../components/settings/settings-shell.tsx | 4 + 8 files changed, 957 insertions(+), 6 deletions(-) create mode 100644 nextjs-frontend/__tests__/settings-mesh.test.tsx create mode 100644 nextjs-frontend/components/settings/mesh-nodes.tsx diff --git a/docs/mesh.md b/docs/mesh.md index 09d2862c..598e9df4 100644 --- a/docs/mesh.md +++ b/docs/mesh.md @@ -2,9 +2,9 @@ Status: **in progress**. Built: Lens as the mesh's certificate authority, join tokens, joining without sending the token, each machine's Nebula config, a node's renewals and reports, removing a node, the `mesh` settings, the API -under `/api/v1/mesh`, Nebula running on the primary in the `mesh` container, relaying the database and the API, and -`lens node` with the install line that joins another machine, and worker nodes running jobs. Coming in their own pull -requests: Settings › Network and Nodes in the web app, and running code on compute nodes. +under `/api/v1/mesh`, Nebula running on the primary in the `mesh` container, relaying the database and the API, +`lens node` with the install line that joins another machine, worker nodes running jobs, and Settings › Network and +Nodes in the web app. Coming in its own pull request: running code on compute nodes. Lens runs on one machine until you add another: a Mac with a GPU to transcribe on, a box to run the assistant's code on, a server with more disk. Those machines talk to this install over a private network of Lens's own, a @@ -186,6 +186,21 @@ out, last report, and the job workers running on it. `PATCH` renames a node or c removes it (undo with `POST /nodes/{id}/restore` while its certificate is good). Tokens: `GET`, `POST`, `DELETE /api/v1/mesh/tokens`. +In the web app: + +- **Settings › Network** says whether the mesh is off (until a node is added), on and running, or on while the `mesh` + container isn't running (with the line that starts it, where the machine has no upgrade agent), and Nebula's error. + It shows this machine's mesh address and the CA's fingerprint and expiry, the settings above (all but `enabled` + folded away), and what Nebula said last. +- **Settings › Nodes** adds a node: pick Worker or Compute, optionally a name and the namespaces it serves, and press + Enter. The install line is shown once, with a Copy button and how long it works ("works once, for 24 hours"); the + machine shows in the list when it joins. Every machine is listed, this one first, with its role, mesh address, + online or when it was last seen (offline after three minutes without a report), Nebula, its Lens version, its + processors, memory and system, when its certificate runs out, the namespaces it serves (ticked in place), its + workers and Nebula's last lines. Click the pencil to rename a node (Enter saves, Escape keeps the name). Remove + asks nothing: the row stays, dimmed and marked Removed, with Undo while its certificate is good. Join tokens not + used yet are listed under it, each with Withdraw. The list refreshes every 15 seconds. + ## What keeps it safe - Nothing listens until an admin adds a node, and single-machine installs never do. diff --git a/nextjs-frontend/__tests__/settings-mesh.test.tsx b/nextjs-frontend/__tests__/settings-mesh.test.tsx new file mode 100644 index 00000000..46b3a996 --- /dev/null +++ b/nextjs-frontend/__tests__/settings-mesh.test.tsx @@ -0,0 +1,300 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import "@testing-library/jest-dom"; + +import { Mesh, Updates } from "@/app/openapi-client"; +import { machineText, seenText, tokenTerms } from "@/components/settings/mesh-nodes"; +import { crossErrors, type SettingsView } from "@/components/settings/model"; +import { SettingsSection } from "@/components/settings/section"; +import { TooltipProvider } from "@/components/ui/tooltip"; + +jest.mock("@/app/openapi-client", () => ({ + Admin: { updateSettings: jest.fn() }, + Metadata: {}, + Mesh: { + meshStatus: jest.fn(), + meshNodes: jest.fn(), + meshTokens: jest.fn(), + makeMeshToken: jest.fn(), + changeNode: jest.fn(), + removeNode: jest.fn(), + restoreNode: jest.fn(), + withdrawMeshToken: jest.fn(), + }, + Updates: { listServices: jest.fn() }, +})); +jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) })); +jest.mock("next/navigation", () => ({ useRouter: () => ({ push: jest.fn() }) })); +jest.mock("@/lib/hooks/session", () => ({ + useArchive: () => ({ namespaces: [{ name: "podcasts" }, { name: "calls" }] }), +})); +jest.mock("@/components/ui/toast", () => ({ useToast: () => jest.fn() })); + +const ok = (data: unknown) => Promise.resolve({ data, response: { ok: true, status: 200 } }); +const refused = (detail: string) => + Promise.resolve({ error: { detail }, response: { ok: false, status: 400, statusText: "Bad Request" } }); + +const later = new Date(Date.now() + 20 * 86400_000).toISOString(); +const PRIMARY = { id: 1, name: "This machine", role: "primary", ip: "10.73.0.1", namespaces: [], status: {} }; +const GPU = { + id: 2, + name: "mac-studio", + role: "worker", + ip: "10.73.0.2", + namespaces: [], + not_after: later, + last_seen: new Date(Date.now() - 2 * 60_000).toISOString(), + status: { + nebula: "running", + version: "0.14.0", + machine: { os: "Darwin", arch: "arm64", cpus: 12, memory: 32 * 1024 ** 3 }, + }, + workers: [], + revoked_at: null, +}; +let rows: Record[] = []; + +function show(id: "nodes" | "network", view: SettingsView = {} as SettingsView) { + const qc = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }); + return render( + + + undefined} /> + + , + ); +} + +beforeAll(() => { + // the namespace checkboxes measure themselves + globalThis.ResizeObserver ??= class { + observe() {} + unobserve() {} + disconnect() {} + } as unknown as typeof ResizeObserver; +}); + +beforeEach(() => { + rows = [PRIMARY, GPU]; + (Mesh.meshNodes as jest.Mock).mockReset().mockImplementation(() => ok(rows)); + (Mesh.meshTokens as jest.Mock).mockReset().mockImplementation(() => ok([])); + (Mesh.makeMeshToken as jest.Mock).mockReset(); + (Mesh.changeNode as jest.Mock).mockReset(); + (Mesh.removeNode as jest.Mock).mockReset(); + (Mesh.restoreNode as jest.Mock).mockReset(); + (Mesh.meshStatus as jest.Mock).mockReset(); + (Updates.listServices as jest.Mock).mockReset().mockImplementation(() => ok({ services: [] })); +}); + +describe("Settings › Nodes", () => { + it("adds a node with Enter and shows the install line once, with its terms", async () => { + const line = + "curl -fsSL https://raw.githubusercontent.com/adeelahmad/lense/main/install.sh | LENS_JOIN=http://lens.home:3000 LENS_JOIN_TOKEN=lensjoin1.7.abc sh"; + const created = new Date().toISOString(); + (Mesh.makeMeshToken as jest.Mock).mockImplementation(() => + ok({ + token: { + id: 7, + role: "compute", + name: "sandbox-box", + namespaces: ["calls"], + uses: 1, + used: 0, + created_at: created, + expires_at: new Date(Date.parse(created) + 24 * 3.6e6).toISOString(), + }, + secret: "lensjoin1.7.abc", + join_url: "http://lens.home:3000", + install_line: line, + }), + ); + show("nodes"); + const name = screen.getByPlaceholderText("the machine’s own name"); + expect(name).toHaveFocus(); + fireEvent.click(screen.getByRole("radio", { name: /Compute/ })); + fireEvent.change(name, { target: { value: "sandbox-box" } }); + fireEvent.click(within(screen.getByRole("group", { name: "Namespaces it serves" })).getByLabelText("calls")); + fireEvent.submit(name.closest("form")!); + expect(await screen.findByText(line)).toBeInTheDocument(); + expect(screen.getByText(/Run it on the machine; it shows here when it joins/)).toBeInTheDocument(); + expect(screen.getByText(/works once, for 24 hours/)).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Copy the install line" })).toBeInTheDocument(); + expect((Mesh.makeMeshToken as jest.Mock).mock.calls[0][0]).toMatchObject({ + body: { role: "compute", name: "sandbox-box", namespaces: ["calls"] }, + }); + }); + + it("shows why a worker node is refused on the embedded database", async () => { + (Mesh.makeMeshToken as jest.Mock).mockImplementation(() => + refused( + "a worker on another machine needs this install's database to be a SurrealDB server (Docker installs have one); add a compute node instead", + ), + ); + show("nodes"); + fireEvent.submit(screen.getByPlaceholderText("the machine’s own name").closest("form")!); + expect( + await screen.findByText(/A worker on another machine needs .* add a compute node instead/), + ).toBeInTheDocument(); + }); + + it("lists each machine with how it's doing", async () => { + show("nodes"); + const row = await screen.findByRole("listitem", { name: "mac-studio" }); + expect(within(row).getByText("Worker")).toBeInTheDocument(); + expect(within(row).getByText(/Online · seen 2 minutes ago/)).toBeInTheDocument(); + expect(within(row).getByText("10.73.0.2")).toBeInTheDocument(); + expect(within(row).getByText(/Lens 0.14.0/)).toBeInTheDocument(); + expect(within(row).getByText(/12 CPUs · 32 GB · Darwin arm64/)).toBeInTheDocument(); + // this machine first, and it can't be removed + const primary = screen.getByRole("listitem", { name: "This machine" }); + expect(within(primary).queryByRole("button", { name: "Remove" })).not.toBeInTheDocument(); + }); + + it("removes a node without asking, and undoes it", async () => { + (Mesh.removeNode as jest.Mock).mockImplementation(() => { + rows = [PRIMARY, { ...GPU, revoked_at: new Date().toISOString(), revoked_by: "admin@lens" }]; + return ok(rows[1]); + }); + (Mesh.restoreNode as jest.Mock).mockImplementation(() => { + rows = [PRIMARY, GPU]; + return ok(GPU); + }); + show("nodes"); + const row = await screen.findByRole("listitem", { name: "mac-studio" }); + fireEvent.click(within(row).getByRole("button", { name: "Remove" })); + expect(await within(row).findByText("Removed")).toBeInTheDocument(); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + expect((Mesh.removeNode as jest.Mock).mock.calls[0][0]).toMatchObject({ path: { node_id: 2 } }); + fireEvent.click(within(row).getByRole("button", { name: "Undo" })); + await waitFor(() => expect(within(row).queryByText("Removed")).not.toBeInTheDocument()); + expect((Mesh.restoreNode as jest.Mock).mock.calls[0][0]).toMatchObject({ path: { node_id: 2 } }); + expect(within(row).getByRole("button", { name: "Remove" })).toBeInTheDocument(); + }); + + it("renames a node with Enter", async () => { + (Mesh.changeNode as jest.Mock).mockImplementation(({ body }: { body: { name: string } }) => { + rows = [PRIMARY, { ...GPU, name: body.name }]; + return ok(rows[1]); + }); + show("nodes"); + const row = await screen.findByRole("listitem", { name: "mac-studio" }); + fireEvent.click(within(row).getByRole("button", { name: "Rename node" })); + const input = within(row).getByRole("textbox", { name: "Node name" }); + fireEvent.change(input, { target: { value: "gpu-box" } }); + fireEvent.submit(input.closest("form")!); + expect(await screen.findByRole("listitem", { name: "gpu-box" })).toBeInTheDocument(); + expect((Mesh.changeNode as jest.Mock).mock.calls[0][0]).toMatchObject({ + path: { node_id: 2 }, + body: { name: "gpu-box" }, + }); + }); + + it("says when a node was last seen, and its machine", () => { + const now = Date.parse("2026-10-18T12:00:00Z"); + expect(seenText("2026-10-18T11:58:00Z", now)).toEqual({ online: true, text: "Online · seen 2 minutes ago" }); + expect(seenText("2026-10-18T11:50:00Z", now).online).toBe(false); + expect(seenText(null, now).text).toBe("Not seen yet"); + expect(machineText({ cpus: 4, memory: 8 * 1024 ** 3, arch: "aarch64", os: "Linux" })).toBe( + "4 CPUs · 8 GB · Linux aarch64", + ); + expect( + tokenTerms({ + id: 1, + role: "worker", + uses: 3, + created_at: "2026-10-18T12:00:00Z", + expires_at: "2026-10-25T12:00:00Z", + }), + ).toBe("works 3 times, for 7 days"); + }); +}); + +const MESH = { + enabled: false, + network: "10.73.0.0/16", + port: 4242, + hosts: [], + cipher: "aes", + cert_days: 30, + relay: true, + mtu: 1300, + log_level: "info", +}; +const STATUS = { + enabled: false, + network: "10.73.0.0/16", + port: 4242, + hosts: [], + primary_ip: "10.73.0.1", + ca: null, + nodes: 0, + removed: 0, + tokens: 0, + nebula: "1.9.5", + tools: false, + service: { + available: true, + state: null, + nebula: false, + restarts: 0, + relays: [], + log: [], + seen_at: null, + manual: "docker compose -f docker-compose.prod.yml --profile mesh up -d", + }, +}; + +describe("Settings › Network", () => { + it("is off until a node is added", async () => { + (Mesh.meshStatus as jest.Mock).mockImplementation(() => ok(STATUS)); + show("network", { mesh: { values: MESH } } as unknown as SettingsView); + expect(await screen.findByText(/Off until you add a node: a single machine needs no mesh/)).toBeInTheDocument(); + expect(screen.getByText("Made when you add the first node.")).toBeInTheDocument(); + expect(screen.getByText("Run the mesh")).toBeInTheDocument(); + }); + + it("gives the line that starts the mesh container where there's no upgrade agent", async () => { + (Mesh.meshStatus as jest.Mock).mockImplementation(() => + ok({ + ...STATUS, + enabled: true, + nodes: 1, + ca: { fingerprint: "ab12cd34", not_after: later }, + }), + ); + (Updates.listServices as jest.Mock).mockImplementation(() => + ok({ services: [{ profile: "mesh", agent: null, manual: STATUS.service.manual }] }), + ); + show("network", { mesh: { values: { ...MESH, enabled: true } } } as unknown as SettingsView); + expect(await screen.findByText("On, but the mesh container isn’t running.")).toBeInTheDocument(); + expect(screen.getByText(STATUS.service.manual)).toBeInTheDocument(); + expect(screen.getByText("ab12cd34")).toBeInTheDocument(); + }); + + it("shows that it runs, and what Nebula said", async () => { + (Mesh.meshStatus as jest.Mock).mockImplementation(() => + ok({ + ...STATUS, + enabled: true, + nodes: 2, + service: { + ...STATUS.service, + state: "running", + nebula: true, + seen_at: new Date().toISOString(), + log: ['level=info msg="Nebula interface is active"'], + }, + }), + ); + show("network", { mesh: { values: { ...MESH, enabled: true } } } as unknown as SettingsView); + expect(await screen.findByText("On, and running.")).toBeInTheDocument(); + expect(screen.getByText(/with 2 nodes/)).toBeInTheDocument(); + expect(screen.getByText("What Nebula said")).toBeInTheDocument(); + }); + + it("checks the network and the hosts as the server does", () => { + expect(crossErrors({ "mesh.network": "10.73.0.0/16", "mesh.hosts": ["lens.example.com:4242"] })).toEqual({}); + expect(crossErrors({ "mesh.network": "10.73.0.0/30" })["mesh.network"]).toMatch(/\/8 to \/28/); + expect(crossErrors({ "mesh.hosts": ["bad host"] })["mesh.hosts"]).toMatch(/isn’t a host name/); + }); +}); diff --git a/nextjs-frontend/components/settings/bodies.tsx b/nextjs-frontend/components/settings/bodies.tsx index 0004f89f..f265c39d 100644 --- a/nextjs-frontend/components/settings/bodies.tsx +++ b/nextjs-frontend/components/settings/bodies.tsx @@ -5,11 +5,13 @@ import { PlugZap, RefreshCw, Terminal } from "lucide-react"; import Link from "next/link"; import { useEffect, useRef, useState, type ReactNode } from "react"; -import { Admin, Fedora, Metadata, Sensors, Shares, Sources, Users } from "@/app/openapi-client"; +import { Admin, Fedora, Mesh, Metadata, Sensors, Shares, Sources, Users } from "@/app/openapi-client"; import type { HttpsStatus, MatterbridgeStatus } from "@/app/openapi-client/types.gen"; import { MonitoringSwitch } from "@/components/admin/monitoring-switch"; +import { useServices } from "@/components/admin/service-switch"; import { BackupsPanel } from "@/components/settings/backups-panel"; import { ComponentsStatus } from "@/components/settings/components-status"; +import { NodesBody } from "@/components/settings/mesh-nodes"; import { EditionChoice, NetworkReach } from "@/components/settings/install-settings"; import { LogViewer } from "@/components/settings/log-viewer"; import { McpServers } from "@/components/settings/mcp-servers"; @@ -48,8 +50,9 @@ import { import { Banner } from "@/components/ui/banner"; import { Button } from "@/components/ui/button"; import { Field, Input, Select, Switch, Textarea } from "@/components/ui/field"; -import { Skeleton } from "@/components/ui/states"; +import { CodeBlock, Skeleton } from "@/components/ui/states"; import { data, useApiClient } from "@/lib/api/browser"; +import { relative, shortDate } from "@/lib/format"; import { useArchive } from "@/lib/hooks/session"; import { cn } from "@/lib/utils"; @@ -481,6 +484,10 @@ export function SectionBody({ ctx }: { ctx: BodyCtx }) { return ; case "https": return ; + case "nodes": + return ; + case "network": + return ; case "components": return ( <> @@ -2266,6 +2273,133 @@ function TunnelBody({ ctx }: { ctx: BodyCtx }) { ); } +/** Settings › Network: the Nebula mesh between Lens's machines (docs/mesh.md), how it runs on this machine right now, + * and its settings. */ +function NetworkBody({ ctx }: { ctx: BodyCtx }) { + const client = useApiClient(); + const m = ctx.view.mesh; + const status = useQuery({ + queryKey: ["mesh", m?.updated_at ?? null], + queryFn: () => data(Mesh.meshStatus({ client })), + refetchInterval: (q) => (!q.state.data?.enabled ? false : q.state.data.service.nebula ? 15_000 : 3_000), + }); + const services = useServices(); + const s = status.data; + const svc = s?.service; + const agent = services.data?.services?.find((x) => x.profile === "mesh")?.agent; + // the container says how it runs every few seconds; a minute without a word and it isn't running + const stale = !svc?.seen_at || Date.now() - Date.parse(svc.seen_at) > 60_000; + const down = Boolean(s?.enabled && svc && !svc.nebula && svc.available && !svc.error && stale); + const log = svc?.log ?? []; + return ( + <> + {status.isError ? ( + {status.error.message} + ) : !s ? ( + + ) : !s.enabled ? ( + + Off until you add a node: a single machine needs no mesh. Adding one in{" "} + + Settings › Nodes + {" "} + turns it on. + + ) : svc?.nebula ? ( + + This machine is {s.primary_ip} on the mesh + {svc.since ? `, Nebula started ${relative(svc.since)}` : ""}, with {s.nodes} node{s.nodes === 1 ? "" : "s"}. + + ) : !svc?.available ? ( + + The mesh runs in a container of its own, which Docker installs have and this install doesn’t, so other + machines can’t reach it. + + ) : svc.error ? ( + + {svc.error} + + ) : down ? ( + + {agent + ? "The machine’s upgrade agent starts it; that takes a minute or so." + : "This machine has no upgrade agent to start it: run the line below on the machine."} + + ) : ( + + The mesh container starts Nebula within a few seconds + {svc.state === "waiting" ? ", once Lens has signed its key" : ""}. + + )} + {down && !agent && svc && } + {s && ( +
+
This machine on the mesh
+
{s.primary_ip}
+
Certificate authority
+
+ {s.ca ? ( + <> + {s.ca.fingerprint} + {s.ca.not_after ? ` · until ${shortDate(s.ca.not_after)}` : ""} + + ) : ( + "Made when you add the first node." + )} +
+
Machines
+
+ {s.nodes} node{s.nodes === 1 ? "" : "s"} + {s.removed ? `, ${s.removed} removed` : ""} + {s.tokens ? `, ${s.tokens} join token${s.tokens === 1 ? "" : "s"} not used yet` : ""} ·{" "} + + Nodes + +
+
Nebula
+
{s.nebula}
+
+ )} + + + +
+ + +
+ +
+ + +
+ + +
+ {log.length > 0 && ( +
+ What Nebula said +
+            {log.join("\n")}
+          
+
+ )} + + ); +} + function BridgeBody({ ctx }: { ctx: BodyCtx }) { const client = useApiClient(); const b = ctx.view.bridge; diff --git a/nextjs-frontend/components/settings/find.ts b/nextjs-frontend/components/settings/find.ts index aad10f90..1d517496 100644 --- a/nextjs-frontend/components/settings/find.ts +++ b/nextjs-frontend/components/settings/find.ts @@ -23,6 +23,7 @@ export const SETTINGS_GROUPS: { label: string; sections: SectionId[] }[] = [ sections: ["sign-in", "tokens", "encryption", "secrets", "access", "remote-access", "https"], }, { label: "Files and devices", sections: ["storage", "shares", "smb", "nfs", "fedora", "sensors"] }, + { label: "Nodes and network", sections: ["nodes", "network"] }, { label: "System", sections: [ diff --git a/nextjs-frontend/components/settings/mesh-nodes.tsx b/nextjs-frontend/components/settings/mesh-nodes.tsx new file mode 100644 index 00000000..1fe850a0 --- /dev/null +++ b/nextjs-frontend/components/settings/mesh-nodes.tsx @@ -0,0 +1,399 @@ +"use client"; + +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { Plus, Undo2 } from "lucide-react"; +import { useState, type FormEvent } from "react"; + +import { Mesh } from "@/app/openapi-client"; +import type { MeshNode, MeshToken, MeshTokenCreated } from "@/app/openapi-client/types.gen"; +import { ChoiceCards } from "@/components/settings/controls"; +import { Badge } from "@/components/ui/badge"; +import { Banner } from "@/components/ui/banner"; +import { Button } from "@/components/ui/button"; +import { Checkbox, Input } from "@/components/ui/field"; +import { RenameTitle } from "@/components/ui/rename-title"; +import { CodeBlock, Skeleton } from "@/components/ui/states"; +import { data, useApiClient } from "@/lib/api/browser"; +import { absolute, relative, shortDate } from "@/lib/format"; +import { useArchive } from "@/lib/hooks/session"; +import { cn } from "@/lib/utils"; + +/** + * Settings › Nodes (docs/mesh.md): adding another machine with the line to run on it, every machine on the mesh with + * how it's doing, renaming and removing one (with undo), and the join tokens not used yet. + */ + +/** A node reports every minute, so one not heard from for three is offline. */ +export const OFFLINE_AFTER_MS = 3 * 60_000; + +const ROLES = [ + { + value: "worker", + label: "Worker", + hint: "Runs jobs (transcription, OCR, model steps) against this install’s database.", + }, + { + value: "compute", + label: "Compute", + hint: "Runs the assistant’s code in sandboxes, and gets nothing of Lens’s: no database, no keys.", + }, +]; +const ROLE_LABEL: Record = { primary: "This machine", worker: "Worker", compute: "Compute" }; + +type Machine = { os?: string | null; arch?: string | null; cpus?: number | null; memory?: number | null }; +type Report = { + nebula?: string | boolean | null; + version?: string | null; + machine?: Machine | null; + info?: Machine | null; + error?: string | null; + log?: string[] | null; +}; + +const upper = (s: string) => (s ? s[0].toUpperCase() + s.slice(1) : s); + +/** "Online · seen 2 minutes ago", or offline once it hasn't reported for three minutes. */ +export function seenText(lastSeen: string | null | undefined, now = Date.now()): { online: boolean; text: string } { + const t = lastSeen ? Date.parse(lastSeen) : NaN; + if (Number.isNaN(t)) return { online: false, text: "Not seen yet" }; + const online = now - t < OFFLINE_AFTER_MS; + const ago = relative(lastSeen, now); + return { online, text: online ? `Online · seen ${ago}` : `Offline · last seen ${ago}` }; +} + +/** "8 CPUs · 16 GB · Linux arm64" from what a node reports about its machine. */ +export function machineText(m: Machine | null | undefined): string | null { + if (!m) return null; + const parts: string[] = []; + if (m.cpus) parts.push(`${m.cpus} CPU${m.cpus === 1 ? "" : "s"}`); + if (m.memory) { + const gb = m.memory / 1024 ** 3; + parts.push(`${gb < 10 ? Math.round(gb * 10) / 10 : Math.round(gb)} GB`); + } + const sys = [m.os, m.arch].filter(Boolean).join(" "); + if (sys) parts.push(sys); + return parts.length ? parts.join(" · ") : null; +} + +function nebulaText(n: Report["nebula"]): string | null { + if (n === true) return "Nebula running"; + if (n === false) return "Nebula not running"; + return n ? `Nebula ${n}` : null; +} + +/** "works once, for 24 hours" from a token just made. */ +export function tokenTerms(t: MeshToken, now = Date.now()): string { + const uses = t.uses ?? 1; + const times = uses === 1 ? "once" : `${uses} times`; + if (!t.expires_at) return `works ${times}`; + const from = t.created_at ? Date.parse(t.created_at) : now; + const h = Math.max(1, Math.round((Date.parse(t.expires_at) - from) / 3.6e6)); + const span = h === 1 ? "an hour" : h <= 48 ? `${h} hours` : `${Math.round(h / 24)} days`; + return `works ${times}, for ${span}`; +} + +const stillGood = (n: MeshNode, now = Date.now()) => !n.not_after || Date.parse(n.not_after) > now; + +export function NodesBody() { + const client = useApiClient(); + const nodes = useQuery({ + queryKey: ["mesh-nodes"], + queryFn: () => data(Mesh.meshNodes({ client })), + refetchInterval: 15_000, + }); + const tokens = useQuery({ + queryKey: ["mesh-tokens"], + queryFn: () => data(Mesh.meshTokens({ client })), + refetchInterval: 15_000, + }); + // removed nodes stay listed, dimmed, while their certificate is still good (until then a removal can be undone) + const shown = (nodes.data ?? []).filter((n) => !n.revoked_at || stillGood(n)); + return ( + <> + +
+

Machines

+ {nodes.isPending ? ( + + ) : nodes.isError ? ( + {nodes.error.message} + ) : ( +
    + {shown.map((n) => ( + + ))} +
+ )} +
+ {(tokens.data ?? []).length > 0 && } +

+ Agents do the same over /api/v1/mesh: nodes, tokens and the network. In + progress: worker nodes taking this install’s jobs, and compute nodes running the assistant’s code. Today a node + joins, renews its certificate and reports here. +

+ + ); +} + +function AddNode() { + const client = useApiClient(); + const qc = useQueryClient(); + const { namespaces } = useArchive(); + const [role, setRole] = useState("worker"); + const [name, setName] = useState(""); + const [picked, setPicked] = useState([]); + const [made, setMade] = useState(null); + const add = useMutation({ + mutationFn: () => + data( + Mesh.makeMeshToken({ + client, + body: { role: role as "worker" | "compute", name: name.trim() || null, namespaces: picked }, + }), + ), + onSuccess: (r) => { + setMade(r); + setName(""); + setPicked([]); + void qc.invalidateQueries({ queryKey: ["mesh-nodes"] }); + void qc.invalidateQueries({ queryKey: ["mesh-tokens"] }); + void qc.invalidateQueries({ queryKey: ["mesh"] }); + // adding a node turns the mesh on (mesh.enabled) + void qc.invalidateQueries({ queryKey: ["settings"] }); + }, + }); + const submit = (e: FormEvent) => { + e.preventDefault(); + if (!add.isPending) add.mutate(); + }; + return ( +
+

Add a node

+
+ + + {namespaces.length > 0 && ( +
+ + Namespaces it serves none ticked: every one + +
+ {namespaces.map((n) => ( + setPicked((p) => (on ? [...p, n.name] : p.filter((x) => x !== n.name)))} + /> + ))} +
+
+ )} +
+ +
+ + {add.isError && {upper(add.error.message)}} + {made && ( +
+

+ Run it on the machine; it shows here when it joins. The line {tokenTerms(made.token)} (until{" "} + {absolute(made.token.expires_at)}) and isn’t shown again. +

+ +
+ +
+
+ )} +
+ ); +} + +function NodeRow({ node: n }: { node: MeshNode }) { + const client = useApiClient(); + const qc = useQueryClient(); + const { namespaces } = useArchive(); + const put = (next: MeshNode) => { + qc.setQueryData(["mesh-nodes"], (list) => list?.map((x) => (x.id === next.id ? next : x))); + void qc.invalidateQueries({ queryKey: ["mesh-nodes"] }); + void qc.invalidateQueries({ queryKey: ["mesh"] }); + }; + const remove = useMutation({ + mutationFn: () => data(Mesh.removeNode({ client, path: { node_id: n.id } })), + onSuccess: put, + }); + const restore = useMutation({ + mutationFn: () => data(Mesh.restoreNode({ client, path: { node_id: n.id } })), + onSuccess: put, + }); + const serve = useMutation({ + mutationFn: (list: string[]) => + data(Mesh.changeNode({ client, path: { node_id: n.id }, body: { namespaces: list } })), + onSuccess: put, + }); + const primary = n.role === "primary"; + const removed = Boolean(n.revoked_at); + const onMesh = Boolean(n.ip); // before the first node there is no mesh, and this machine has no row to rename + const r = (n.status ?? {}) as Report; + const seen = seenText(n.last_seen); + const facts = [ + n.ip, + nebulaText(r.nebula), + r.version && !primary ? `Lens ${r.version}` : null, + machineText(r.machine ?? r.info), + n.not_after ? `certificate until ${shortDate(n.not_after)}` : null, + n.workers?.length ? `${n.workers.length} worker${n.workers.length === 1 ? "" : "s"}` : null, + ].filter(Boolean); + const served = n.namespaces ?? []; + const error = remove.error ?? restore.error ?? serve.error; + return ( +
  • +
    + + put(await data(Mesh.changeNode({ client, path: { node_id: n.id }, body: { name } }))) + : undefined + } + /> + + {ROLE_LABEL[n.role] ?? n.role} + {removed ? ( + Removed + ) : ( + !primary && ( + + + {seen.text} + + ) + )} + + {removed ? ( + + ) : ( + !primary && ( + + ) + )} + +
    + {facts.length > 0 && ( +

    + {facts.map((f, i) => ( + + {i > 0 && " · "} + {f} + + ))} +

    + )} + {removed && ( +

    + Removed {relative(n.revoked_at)} + {n.revoked_by ? ` by ${n.revoked_by}` : ""}: its certificates are blocked on every machine. Undo while its + certificate is still good{n.not_after ? `, until ${shortDate(n.not_after)}` : ""}. +

    + )} + {!primary && !removed && namespaces.length > 0 && ( +
    + + {served.length ? "Serves" : "Serves every namespace, or only"} + + {namespaces.map((ns) => ( + serve.mutate(on ? [...served, ns.name] : served.filter((x) => x !== ns.name))} + /> + ))} +
    + )} + {r.error && {r.error}} + {error && {upper(error.message)}} + {(r.log ?? []).length > 0 && ( +
    + What Nebula said +
    +            {(r.log ?? []).join("\n")}
    +          
    +
    + )} +
  • + ); +} + +function Tokens({ list }: { list: MeshToken[] }) { + const client = useApiClient(); + const qc = useQueryClient(); + const withdraw = useMutation({ + mutationFn: (id: number) => data(Mesh.withdrawMeshToken({ client, path: { token_id: id } })), + onSuccess: () => { + void qc.invalidateQueries({ queryKey: ["mesh-tokens"] }); + void qc.invalidateQueries({ queryKey: ["mesh"] }); + }, + }); + return ( +
    +

    Join tokens not used yet

    +
      + {list.map((t) => ( +
    • + {ROLE_LABEL[t.role] ?? t.role} + {t.name || "named by the machine"} + + {t.expired + ? "expired" + : `${(t.uses ?? 1) - (t.used ?? 0)} use${(t.uses ?? 1) - (t.used ?? 0) === 1 ? "" : "s"} left, until ${absolute(t.expires_at)}`} + {t.namespaces?.length ? ` · ${t.namespaces.join(", ")}` : ""} + + +
    • + ))} +
    + {withdraw.isError && {upper(withdraw.error.message)}} +
    + ); +} diff --git a/nextjs-frontend/components/settings/model.ts b/nextjs-frontend/components/settings/model.ts index c95c9cc8..e3eec78b 100644 --- a/nextjs-frontend/components/settings/model.ts +++ b/nextjs-frontend/components/settings/model.ts @@ -80,6 +80,8 @@ export type SectionId = | "access" | "remote-access" | "https" + | "nodes" + | "network" | "sign-in" | "encryption" | "secrets" @@ -270,6 +272,20 @@ export const SECTIONS: SectionSpec[] = [ description: "Off unless you turn it on. Serve Lens at your own domain over https://, with certificates from Let’s Encrypt or ZeroSSL that Lens gets and renews itself.", }, + { + id: "nodes", + label: "Nodes", + backend: [], + description: + "Other machines Lens runs on, joined over its own private network: add one with a line to run on it, see how each is doing, rename or remove it. A single machine needs none.", + }, + { + id: "network", + label: "Network", + backend: ["mesh"], + description: + "The private network between Lens’s machines, a Nebula mesh Lens issues the certificates for: every packet between them is encrypted. Off until you add a node.", + }, { id: "mail", label: "Email", @@ -1343,6 +1359,76 @@ export const FIELDS: FieldSpec[] = [ placeholder: "as installed", hint: "Where cloudflared reaches the web app from the server. Leave empty unless you moved it.", }, + // Network (the Nebula mesh between Lens's machines, docs/mesh.md) + { + section: "mesh", + key: "enabled", + label: "Run the mesh", + kind: "switch", + hint: "On when you add a node; off stops the mesh on this machine.", + }, + { + section: "mesh", + key: "network", + label: "Mesh addresses", + kind: "text", + mono: true, + placeholder: "10.73.0.0/16", + hint: "A private IPv4 range from /8 to /28; this machine is its first address. It can’t change once machines have addresses in it.", + }, + { + section: "mesh", + key: "port", + label: "UDP port", + kind: "int", + min: 1, + max: 65535, + hint: "The port nodes reach this machine at: the one Docker publishes (LENS_MESH_PORT), unless a router forwards another.", + }, + { + section: "mesh", + key: "hosts", + label: "Where nodes reach it", + kind: "lines", + mono: true, + placeholder: "lens.example.com:4242", + hint: "One per line, a host or host:port, up to 8. Empty: the address each node joined this install at.", + }, + { + section: "mesh", + key: "cipher", + label: "Cipher", + kind: "select", + options: [ + { value: "aes", label: "AES-256-GCM" }, + { value: "chachapoly", label: "ChaCha20-Poly1305" }, + ], + hint: "The same on every machine. ChaCha20-Poly1305 is faster on machines without AES hardware, such as some Raspberry Pis.", + }, + { + section: "mesh", + key: "cert_days", + label: "Certificates last", + kind: "int", + min: 2, + max: 365, + unit: "days", + hint: "Each machine renews its certificate at two thirds of this.", + }, + { section: "mesh", key: "relay", label: "Relay for machines that can’t reach each other directly", kind: "switch" }, + { section: "mesh", key: "mtu", label: "MTU", kind: "int", min: 1200, max: 9000, hint: "The mesh interface’s MTU." }, + { + section: "mesh", + key: "log_level", + label: "Nebula’s log level", + kind: "select", + options: [ + { value: "error", label: "Errors" }, + { value: "warning", label: "Warnings" }, + { value: "info", label: "Info" }, + { value: "debug", label: "Debug" }, + ], + }, // HTTPS (Caddy run by Lens, certificates over ACME) { section: "https", key: "enabled", label: "Serve Lens over HTTPS", kind: "switch" }, { @@ -4036,6 +4122,8 @@ export function parse(f: FieldSpec, ui: unknown): Parsed { const HOST_RX = /^(\*|\[[0-9a-f:]+\]|[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*)$/i; const ENTITY_TYPES = ["PERSON", "ORG", "PRODUCT", "PLACE", "EVENT", "WORK", "TERM"]; const URL_RX = /^https?:\/\/[^\s]+$/; +/** mesh.hosts: a host name or address, with or without :port (mesh.HOST_RX on the server). */ +const MESH_HOST_RX = /^(\[[0-9A-Fa-f:]+\]|[A-Za-z0-9][A-Za-z0-9.-]{0,252})(:\d{1,5})?$/; const TUNNEL_HOST_RX = /^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}\.?$/i; /** "Line 4: missing “|” between name and type" for the custom vocabulary. */ @@ -4169,6 +4257,16 @@ export function crossErrors(values: Record): Record !/^[0-9a-f.:]+(\/\d{1,3})?$/i.test(x)); if (badSNet) e["sensors.syslog_networks"] = `“${badSNet}” isn’t a network like 192.168.1.0/24`; + const meshNet = values["mesh.network"] as string | undefined; + if (meshNet !== undefined) { + const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\/(\d{1,2})$/.exec(meshNet); + if (!m || m.slice(1, 5).some((x) => Number(x) > 255) || Number(m[5]) < 8 || Number(m[5]) > 28) + e["mesh.network"] = "Use a private IPv4 range from /8 to /28, like 10.73.0.0/16"; + } + const meshHosts = values["mesh.hosts"] as string[] | undefined; + const badMeshHost = meshHosts?.find((x) => !MESH_HOST_RX.test(x)); + if (meshHosts && meshHosts.length > 8) e["mesh.hosts"] = "Up to 8 addresses"; + else if (badMeshHost) e["mesh.hosts"] = `“${badMeshHost}” isn’t a host name or address, with or without :port`; const mode = values["tunnel.mode"] as string | undefined; const tHost = values["tunnel.hostname"] as string | undefined; if ((mode === "token" || mode === "managed") && "tunnel.hostname" in values && !TUNNEL_HOST_RX.test(tHost ?? "")) diff --git a/nextjs-frontend/components/settings/section.tsx b/nextjs-frontend/components/settings/section.tsx index 8c322676..605fb4d1 100644 --- a/nextjs-frontend/components/settings/section.tsx +++ b/nextjs-frontend/components/settings/section.tsx @@ -267,7 +267,7 @@ export function SettingsSection({

    {spec.label}

    {spec.description}

    - {id !== "startup" && ( + {spec.backend.length > 0 && ( {updatedAt ? `Last saved by ${updatedBy ?? "someone"} on ${absolute(updatedAt)}` diff --git a/nextjs-frontend/components/settings/settings-shell.tsx b/nextjs-frontend/components/settings/settings-shell.tsx index 07e093a4..7b53ade2 100644 --- a/nextjs-frontend/components/settings/settings-shell.tsx +++ b/nextjs-frontend/components/settings/settings-shell.tsx @@ -49,7 +49,9 @@ import { RefreshCw, Network, ScrollText, + Server, WandSparkles, + Waypoints, Workflow, } from "lucide-react"; import Link from "next/link"; @@ -100,6 +102,8 @@ const ICON: Record = { access: ShieldCheck, "remote-access": Cloud, https: Lock, + nodes: Server, + network: Waypoints, "sign-in": LockKeyhole, encryption: FileLock, secrets: KeySquare, From db2e80cffaa9476392a8aaa653f7969a7533a9d3 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 18 Oct 2026 09:14:07 +0000 Subject: [PATCH 2/4] fix(mesh): the worker role's description says what a worker node runs and reads Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01GTrHPwWHtEvFJFq3M1YpH4 --- nextjs-frontend/components/settings/mesh-nodes.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nextjs-frontend/components/settings/mesh-nodes.tsx b/nextjs-frontend/components/settings/mesh-nodes.tsx index 1fe850a0..27920a96 100644 --- a/nextjs-frontend/components/settings/mesh-nodes.tsx +++ b/nextjs-frontend/components/settings/mesh-nodes.tsx @@ -30,7 +30,7 @@ const ROLES = [ { value: "worker", label: "Worker", - hint: "Runs jobs (transcription, OCR, model steps) against this install’s database.", + hint: "Transcribes and tells voices apart with its own models, against this install’s database, which it can read in full.", }, { value: "compute", @@ -128,8 +128,8 @@ export function NodesBody() { {(tokens.data ?? []).length > 0 && }

    Agents do the same over /api/v1/mesh: nodes, tokens and the network. In - progress: worker nodes taking this install’s jobs, and compute nodes running the assistant’s code. Today a node - joins, renews its certificate and reports here. + progress: compute nodes running the assistant’s code. Today a node joins, renews its certificate and reports + here, and a worker node takes this install’s jobs.

    ); From 6e37e6dab7c7014a5fc070081fbf5ee44d4b7a52 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 18 Oct 2026 12:30:45 +0000 Subject: [PATCH 3/4] feat(mesh): a worker node's row shows its worker's log, and the pages' changelog fragment Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01GTrHPwWHtEvFJFq3M1YpH4 --- changelog.d/mesh-node.md | 4 ++-- changelog.d/mesh-settings.md | 6 ++++++ nextjs-frontend/__tests__/settings-mesh.test.tsx | 3 +++ nextjs-frontend/components/settings/mesh-nodes.tsx | 4 +++- 4 files changed, 14 insertions(+), 3 deletions(-) create mode 100644 changelog.d/mesh-settings.md diff --git a/changelog.d/mesh-node.md b/changelog.d/mesh-node.md index 48a16d66..1b3ce890 100644 --- a/changelog.d/mesh-node.md +++ b/changelog.d/mesh-node.md @@ -1,4 +1,4 @@ - **Joining a node** (in progress). Another machine joins with the install line and `LENS_JOIN` and `LENS_JOIN_TOKEN`: it asks nothing, publishes no port, and runs Nebula and `lens node`, which joins once and then follows the primary's - config, renews its certificate and reports over the mesh. Adding a node token now returns that install line. The - Settings pages follow in their own pull request ([On a node](docs/mesh.md#on-a-node)). + config, renews its certificate and reports over the mesh. Adding a node token now returns that install line + ([On a node](docs/mesh.md#on-a-node)). diff --git a/changelog.d/mesh-settings.md b/changelog.d/mesh-settings.md new file mode 100644 index 00000000..8ba5952b --- /dev/null +++ b/changelog.d/mesh-settings.md @@ -0,0 +1,6 @@ +- **Settings › Nodes and Network** (in progress). Nodes adds a machine (its role, and optionally a name and + namespaces) and shows the install line once, with Copy and how long it works. It lists every machine, this one + first, with its mesh address, when it was last seen, Nebula, its Lens version, certificate, namespaces, worker and + log, renames in place, and removes a machine with Undo instead of a dialog. Network shows whether the mesh is off or + running, the CA, this machine's mesh address, the mesh settings and what Nebula said + ([the mesh](docs/mesh.md)). diff --git a/nextjs-frontend/__tests__/settings-mesh.test.tsx b/nextjs-frontend/__tests__/settings-mesh.test.tsx index 46b3a996..97735ced 100644 --- a/nextjs-frontend/__tests__/settings-mesh.test.tsx +++ b/nextjs-frontend/__tests__/settings-mesh.test.tsx @@ -48,6 +48,7 @@ const GPU = { nebula: "running", version: "0.14.0", machine: { os: "Darwin", arch: "arm64", cpus: 12, memory: 32 * 1024 ** 3 }, + log: ["07:00:01 started lens worker mac-studio (transcribe,diarize)"], }, workers: [], revoked_at: null, @@ -145,6 +146,8 @@ describe("Settings › Nodes", () => { expect(within(row).getByText("10.73.0.2")).toBeInTheDocument(); expect(within(row).getByText(/Lens 0.14.0/)).toBeInTheDocument(); expect(within(row).getByText(/12 CPUs · 32 GB · Darwin arm64/)).toBeInTheDocument(); + expect(within(row).getByText("What Nebula and its worker said")).toBeInTheDocument(); + expect(within(row).getByText(/started lens worker mac-studio/)).toBeInTheDocument(); // this machine first, and it can't be removed const primary = screen.getByRole("listitem", { name: "This machine" }); expect(within(primary).queryByRole("button", { name: "Remove" })).not.toBeInTheDocument(); diff --git a/nextjs-frontend/components/settings/mesh-nodes.tsx b/nextjs-frontend/components/settings/mesh-nodes.tsx index 27920a96..dd65b7d0 100644 --- a/nextjs-frontend/components/settings/mesh-nodes.tsx +++ b/nextjs-frontend/components/settings/mesh-nodes.tsx @@ -347,7 +347,9 @@ function NodeRow({ node: n }: { node: MeshNode }) { {error && {upper(error.message)}} {(r.log ?? []).length > 0 && (
    - What Nebula said + + {n.role === "worker" ? "What Nebula and its worker said" : "What Nebula said"} +
                 {(r.log ?? []).join("\n")}
               
    From f9d40335adab1753631eeef066e9748b348e3c79 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 18 Oct 2026 12:53:57 +0000 Subject: [PATCH 4/4] docs(readme): the mesh's In progress line links its open pull request Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01GTrHPwWHtEvFJFq3M1YpH4 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 29171aa8..828fce2f 100644 --- a/README.md +++ b/README.md @@ -270,7 +270,7 @@ These are open pull requests, not yet part of Lens: ([#406](https://github.com/adeelahmad/lense/pull/406)). - **Automations:** more operators for conditions ([#434](https://github.com/adeelahmad/lense/pull/434)). - **Nodes:** Lens's own private network between the machines it runs on, a Nebula mesh it issues the certificates - for ([#595](https://github.com/adeelahmad/lense/pull/595)). + for ([#602](https://github.com/adeelahmad/lense/pull/602)). ## Planned