From ca9df4ad6753966d0dc8ff1fc30bce5722e4cd09 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sat, 14 Nov 2026 21:51:30 -0500 Subject: [PATCH 01/49] feat(web): add shadcn drawer, components.json and scoped neutral tokens Baseline typecheck: 176 errors, all pre-existing jest-dom matcher types in test files. Unchanged by this commit. - components.json: new-york, tsx, no rsc, css at src/index.css, lucide, aliases utils -> @core/utils/cn, ui -> @components/shadcn (components/ui would collide with components/UI on macOS). - pnpm dlx shadcn@latest add drawer: generated components/shadcn/drawer.tsx and added vaul. The CLI misread the utils alias as an npm package and installed "cn"; removed it and pointed the import at @core/utils/cn.ts. Formatted with oxfmt. - Tokens: shadcn neutral light/dark OKLCH set, mapped through @theme inline. Raw tokens are scoped to [data-shadcn-scope] (dark on [data-theme=dark]) so existing screens are untouched. --accent/--accent-foreground omitted because the app maps --color-accent: var(--accent) for ring-accent; --radius-* omitted because it would override Tailwind's rounded-* scale. - Toast.tsx: removed never-resolving token classes (border-muted/40, text-foreground/50, ring-ring ...) that would otherwise start resolving and shift the cascade. Rendering is identical. --- apps/web/components.json | 21 ++++ apps/web/package.json | 1 + apps/web/src/components/UI/Toast.tsx | 4 +- apps/web/src/components/shadcn/drawer.tsx | 132 ++++++++++++++++++++++ apps/web/src/index.css | 113 ++++++++++++++++++ pnpm-lock.yaml | 18 +++ 6 files changed, 287 insertions(+), 2 deletions(-) create mode 100644 apps/web/components.json create mode 100644 apps/web/src/components/shadcn/drawer.tsx diff --git a/apps/web/components.json b/apps/web/components.json new file mode 100644 index 000000000..887d243c8 --- /dev/null +++ b/apps/web/components.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "", + "css": "src/index.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "iconLibrary": "lucide", + "aliases": { + "components": "@components", + "utils": "@core/utils/cn", + "ui": "@components/shadcn", + "lib": "@core/utils", + "hooks": "@core/hooks" + } +} diff --git a/apps/web/package.json b/apps/web/package.json index 26c0c68a1..d2f49df70 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -89,6 +89,7 @@ "react-map-gl": "8.1.3", "react-qrcode-logo": "^4.1.0", "rfc4648": "^1.5.4", + "vaul": "^1.1.2", "vite": "^8.3.4", "vite-plugin-html": "^3.2.2", "vite-plugin-pwa": "^2.0.0", diff --git a/apps/web/src/components/UI/Toast.tsx b/apps/web/src/components/UI/Toast.tsx index d36816efc..e1c65b20f 100644 --- a/apps/web/src/components/UI/Toast.tsx +++ b/apps/web/src/components/UI/Toast.tsx @@ -61,7 +61,7 @@ const ToastAction = React.forwardRef< ) { + return ; +} + +function DrawerTrigger({ + ...props +}: React.ComponentProps) { + return ; +} + +function DrawerPortal({ + ...props +}: React.ComponentProps) { + return ; +} + +function DrawerClose({ + ...props +}: React.ComponentProps) { + return ; +} + +function DrawerOverlay({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function DrawerContent({ + className, + children, + ...props +}: React.ComponentProps) { + return ( + + + +
+ {children} + + + ); +} + +function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ); +} + +function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ); +} + +function DrawerTitle({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function DrawerDescription({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +export { + Drawer, + DrawerPortal, + DrawerOverlay, + DrawerTrigger, + DrawerClose, + DrawerContent, + DrawerHeader, + DrawerFooter, + DrawerTitle, + DrawerDescription, +}; diff --git a/apps/web/src/index.css b/apps/web/src/index.css index f44ef6b0d..7c8c80955 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -70,6 +70,119 @@ --brightnessDisabled: 0.75; } +/* + * shadcn/ui neutral token set. + * + * The raw tokens are scoped to `[data-shadcn-scope]` rather than `:root` so + * the generated utilities (`bg-background`, `text-foreground`, ...) only paint + * inside shadcn-styled surfaces such as the Connections drawer. Elsewhere they + * stay unresolved exactly as before. Two names are deliberately left out: + * - `--accent` / `--accent-foreground`: the app already maps + * `--color-accent: var(--accent)` for `ring-accent`; defining `--accent` + * would recolour those focus rings. Drawer hover surfaces use `bg-muted`. + * - `--radius-*`: shadcn's remap would override Tailwind's `rounded-*` scale + * app-wide, so the stock scale is kept. + */ +[data-shadcn-scope] { + --background: oklch(1 0 0); + --foreground: oklch(0.145 0 0); + --card: oklch(1 0 0); + --card-foreground: oklch(0.145 0 0); + --popover: oklch(1 0 0); + --popover-foreground: oklch(0.145 0 0); + --primary: oklch(0.205 0 0); + --primary-foreground: oklch(0.985 0 0); + --secondary: oklch(0.97 0 0); + --secondary-foreground: oklch(0.205 0 0); + --muted: oklch(0.97 0 0); + --muted-foreground: oklch(0.556 0 0); + --destructive: oklch(0.577 0.245 27.325); + --destructive-foreground: oklch(0.985 0 0); + --border: oklch(0.922 0 0); + --input: oklch(0.922 0 0); + --ring: oklch(0.708 0 0); + --chart-1: oklch(0.646 0.222 41.116); + --chart-2: oklch(0.6 0.118 184.704); + --chart-3: oklch(0.398 0.07 227.392); + --chart-4: oklch(0.828 0.189 84.429); + --chart-5: oklch(0.769 0.188 70.08); + --sidebar: oklch(0.985 0 0); + --sidebar-foreground: oklch(0.145 0 0); + --sidebar-primary: oklch(0.205 0 0); + --sidebar-primary-foreground: oklch(0.985 0 0); + --sidebar-accent: oklch(0.97 0 0); + --sidebar-accent-foreground: oklch(0.205 0 0); + --sidebar-border: oklch(0.922 0 0); + --sidebar-ring: oklch(0.708 0 0); +} + +[data-theme="dark"] [data-shadcn-scope], +[data-theme="dark"][data-shadcn-scope] { + --background: oklch(0.145 0 0); + --foreground: oklch(0.985 0 0); + --card: oklch(0.205 0 0); + --card-foreground: oklch(0.985 0 0); + --popover: oklch(0.205 0 0); + --popover-foreground: oklch(0.985 0 0); + --primary: oklch(0.922 0 0); + --primary-foreground: oklch(0.205 0 0); + --secondary: oklch(0.269 0 0); + --secondary-foreground: oklch(0.985 0 0); + --muted: oklch(0.269 0 0); + --muted-foreground: oklch(0.708 0 0); + --destructive: oklch(0.704 0.191 22.216); + --destructive-foreground: oklch(0.985 0 0); + --border: oklch(1 0 0 / 10%); + --input: oklch(1 0 0 / 15%); + --ring: oklch(0.556 0 0); + --chart-1: oklch(0.488 0.243 264.376); + --chart-2: oklch(0.696 0.17 162.48); + --chart-3: oklch(0.769 0.188 70.08); + --chart-4: oklch(0.627 0.265 303.9); + --chart-5: oklch(0.645 0.246 16.439); + --sidebar: oklch(0.205 0 0); + --sidebar-foreground: oklch(0.985 0 0); + --sidebar-primary: oklch(0.488 0.243 264.376); + --sidebar-primary-foreground: oklch(0.985 0 0); + --sidebar-accent: oklch(0.269 0 0); + --sidebar-accent-foreground: oklch(0.985 0 0); + --sidebar-border: oklch(1 0 0 / 10%); + --sidebar-ring: oklch(0.556 0 0); +} + +@theme inline { + --color-background: var(--background); + --color-foreground: var(--foreground); + --color-card: var(--card); + --color-card-foreground: var(--card-foreground); + --color-popover: var(--popover); + --color-popover-foreground: var(--popover-foreground); + --color-primary: var(--primary); + --color-primary-foreground: var(--primary-foreground); + --color-secondary: var(--secondary); + --color-secondary-foreground: var(--secondary-foreground); + --color-muted: var(--muted); + --color-muted-foreground: var(--muted-foreground); + --color-destructive: var(--destructive); + --color-destructive-foreground: var(--destructive-foreground); + --color-border: var(--border); + --color-input: var(--input); + --color-ring: var(--ring); + --color-chart-1: var(--chart-1); + --color-chart-2: var(--chart-2); + --color-chart-3: var(--chart-3); + --color-chart-4: var(--chart-4); + --color-chart-5: var(--chart-5); + --color-sidebar: var(--sidebar); + --color-sidebar-foreground: var(--sidebar-foreground); + --color-sidebar-primary: var(--sidebar-primary); + --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); + --color-sidebar-accent: var(--sidebar-accent); + --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); + --color-sidebar-border: var(--sidebar-border); + --color-sidebar-ring: var(--sidebar-ring); +} + /* Accordion Animations */ @keyframes accordion-down { from { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e6485efa1..ec9ebc6e9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -231,6 +231,9 @@ importers: rfc4648: specifier: ^1.5.4 version: 1.5.4 + vaul: + specifier: ^1.1.2 + version: 1.1.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) vite: specifier: ^8.3.4 version: 8.3.4(@types/node@26.6.5)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1) @@ -5687,6 +5690,12 @@ packages: peerDependencies: react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + vaul@1.1.2: + resolution: {integrity: sha512-ZFkClGpWyI2WUQjdLJ/BaGuV6AVQiJ3uELGk3OYtP+B6yCO7Cmn9vPFXVJkRaGkOJu3m8bQMgtyzNHixULceQA==} + peerDependencies: + react: ^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc + verkit@0.5.0: resolution: {integrity: sha512-u4J1hr6Y+C/hit34GwL3eIcUf3wngT8TlYUjK7tk0jxydKLAq3sYvifjdTDA6U3KCKRcQCQDGf/srjxfZF3l7g==} engines: {node: '>=18.12.0'} @@ -11593,6 +11602,15 @@ snapshots: dependencies: react: 19.3.1 + vaul@1.1.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1): + dependencies: + '@radix-ui/react-dialog': 1.3.1(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + transitivePeerDependencies: + - '@types/react' + - '@types/react-dom' + verkit@0.5.0: {} vite-plugin-dts@5.1.2(rolldown@1.2.14)(rollup@4.64.7)(typescript@7.0.2)(vite@8.3.4(@types/node@26.6.5)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)): From d161ac66fe00ed3137af62f4e05f1c7fc3a9a752 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sat, 14 Nov 2026 21:58:38 -0500 Subject: [PATCH 02/49] feat(web): Connections drawer shell replaces the Connections page The drawer is an overlay over whatever page is showing. Its open state and view (list | add | edit:) live in the app store as connectionsDrawer with openConnections(view?), closeConnections() and setConnectionsView(); nothing is encoded in the URL. connectDialogOpen, which nothing read, is replaced by it. - Mounted once in App.tsx next to ConnectingOverlay (drawer z-40, overlay z-50 stays above). With no device the drawer is forced open: no close button, dismissible=false, Escape prevented. - / no longer renders Connections; the /connections page route is now a redirect to / that calls openConnections(). - DeviceInfoPanel, LockdownGate and the command palette's Connect New Node call openConnections() (the palette asks for the add view). - pages/Connections/index.tsx moved to components/ConnectionsDrawer/ ConnectionsList.tsx; useConnections/utils stay where they were. - Tests: store actions, /connections redirect, open/close changes no route, no in-app navigation to /connections, forced vs dismissable drawer. --- .../public/i18n/locales/en/connections.json | 6 ++ apps/web/src/App.tsx | 10 +-- .../src/components/CommandPalette/index.tsx | 5 +- .../ConnectionsDrawer.test.tsx | 62 +++++++++++++ .../ConnectionsDrawer/ConnectionsDrawer.tsx | 88 +++++++++++++++++++ .../ConnectionsDrawer/ConnectionsList.tsx} | 54 +++--------- apps/web/src/components/DeviceInfoPanel.tsx | 6 +- .../LockdownDialog/LockdownDialog.test.tsx | 12 ++- .../Dialog/LockdownDialog/LockdownDialog.tsx | 7 +- apps/web/src/components/shadcn/drawer.tsx | 4 +- .../src/core/stores/appStore/appStore.test.ts | 24 ++++- apps/web/src/core/stores/appStore/index.ts | 29 +++--- apps/web/src/core/stores/appStore/types.ts | 8 ++ apps/web/src/routes.test.ts | 65 ++++++++++++++ apps/web/src/routes.tsx | 10 ++- 15 files changed, 309 insertions(+), 81 deletions(-) create mode 100644 apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.test.tsx create mode 100644 apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx rename apps/web/src/{pages/Connections/index.tsx => components/ConnectionsDrawer/ConnectionsList.tsx} (88%) create mode 100644 apps/web/src/routes.test.ts diff --git a/apps/web/public/i18n/locales/en/connections.json b/apps/web/public/i18n/locales/en/connections.json index f26f64d55..ccd9d79c5 100644 --- a/apps/web/public/i18n/locales/en/connections.json +++ b/apps/web/public/i18n/locales/en/connections.json @@ -1,4 +1,10 @@ { + "drawer": { + "title": "Connections", + "close": "Close connections", + "back": "Back to connections", + "addConnection": "Add connection" + }, "page": { "title": "Connect to a Meshtastic device", "description": "Add a device connection via HTTP, Bluetooth, or Serial. Your saved connections will be saved in your browser." diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 18f5b9c54..46525f6de 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -2,6 +2,7 @@ import { DeviceWrapper } from "@app/DeviceWrapper.tsx"; import { BeaconOfferNotifier } from "@components/BeaconOfferNotifier.tsx"; import { CommandPalette } from "@components/CommandPalette/index.tsx"; import { ConnectingOverlay } from "@components/ConnectingOverlay.tsx"; +import { ConnectionsDrawer } from "@components/ConnectionsDrawer/ConnectionsDrawer.tsx"; import { DialogManager } from "@components/Dialog/DialogManager.tsx"; import { LockdownGate } from "@components/Dialog/LockdownDialog/LockdownDialog.tsx"; import { RegionSetupReminder } from "@components/RegionSetupReminder.tsx"; @@ -12,7 +13,6 @@ import { useTheme } from "@core/hooks/useTheme.ts"; import { cn } from "@core/utils/cn.ts"; import { SidebarProvider, useAppStore, useDeviceStore } from "@core/stores"; import { useTotalUnread } from "@meshtastic/sdk-react"; -import { Connections } from "@pages/Connections/index.tsx"; import { Outlet } from "@tanstack/react-router"; import { TanStackRouterDevtools } from "@tanstack/react-router-devtools"; import { useEffect, useRef } from "react"; @@ -50,6 +50,9 @@ export function App() { during a first-time connect from the Connections screen as well as reconnects from inside the app. */} + {/* The Connections drawer overlays whatever page is showing. With no + device it is forced open and replaces the old full-page screen. */} +
) : ( - <> - -
- +
)}
diff --git a/apps/web/src/components/CommandPalette/index.tsx b/apps/web/src/components/CommandPalette/index.tsx index 87e75cf4b..bc02e52f0 100644 --- a/apps/web/src/components/CommandPalette/index.tsx +++ b/apps/web/src/components/CommandPalette/index.tsx @@ -75,7 +75,7 @@ export const CommandPalette = () => { const { commandPaletteOpen, setCommandPaletteOpen, - setConnectDialogOpen, + openConnections, setSelectedDevice, } = useAppStore(); const { getDevices } = useDeviceStore(); @@ -204,7 +204,8 @@ export const CommandPalette = () => { label: t("manage.command.connectNewNode"), icon: PlusIcon, action() { - setConnectDialogOpen(true); + openConnections("add"); + setCommandPaletteOpen(false); }, }, ], diff --git a/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.test.tsx b/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.test.tsx new file mode 100644 index 000000000..327cec234 --- /dev/null +++ b/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.test.tsx @@ -0,0 +1,62 @@ +import { useAppStore } from "@core/stores"; +import { act, fireEvent, render, screen } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { ConnectionsDrawer } from "./ConnectionsDrawer.tsx"; + +vi.mock("./ConnectionsList.tsx", () => ({ + ConnectionsList: () =>
, +})); + +describe("ConnectionsDrawer", () => { + beforeEach(() => { + act(() => useAppStore.getState().closeConnections()); + }); + + describe("forced open (no device)", () => { + it("renders without a close button and ignores Escape", () => { + render(); + + expect(screen.getByRole("dialog")).not.toBeNull(); + expect(screen.getByTestId("connections-list")).not.toBeNull(); + expect( + screen.queryByRole("button", { name: "Close connections" }), + ).toBeNull(); + + fireEvent.keyDown(document.activeElement ?? document.body, { + key: "Escape", + }); + + expect(screen.getByRole("dialog")).not.toBeNull(); + expect(useAppStore.getState().connectionsDrawer.open).toBe(false); + }); + }); + + describe("dismissable (device connected)", () => { + it("renders nothing until opened from the store", () => { + render(); + expect(screen.queryByRole("dialog")).toBeNull(); + expect(screen.queryByTestId("connections-list")).toBeNull(); + }); + + it("closes from the close button", () => { + render(); + act(() => useAppStore.getState().openConnections()); + + fireEvent.click( + screen.getByRole("button", { name: "Close connections" }), + ); + + expect(useAppStore.getState().connectionsDrawer.open).toBe(false); + }); + + it("closes on Escape", () => { + render(); + act(() => useAppStore.getState().openConnections()); + const dialog = screen.getByRole("dialog"); + + fireEvent.keyDown(dialog, { key: "Escape" }); + + expect(useAppStore.getState().connectionsDrawer.open).toBe(false); + }); + }); +}); diff --git a/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx b/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx new file mode 100644 index 000000000..98c6fbf74 --- /dev/null +++ b/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx @@ -0,0 +1,88 @@ +import { + Drawer, + DrawerClose, + DrawerContent, + DrawerDescription, + DrawerHeader, + DrawerTitle, +} from "@components/shadcn/drawer.tsx"; +import { useAppStore, useDeviceStore } from "@core/stores"; +import { cn } from "@core/utils/cn.ts"; +import { XIcon } from "lucide-react"; +import { useTranslation } from "react-i18next"; +import { ConnectionsList } from "./ConnectionsList.tsx"; + +export interface ConnectionsDrawerProps { + /** + * No device is connected: the drawer stays open with no way to dismiss it, + * replacing the old full-page Connections screen. + */ + forced: boolean; +} + +/** + * The Connections drawer. An overlay over whatever page is showing; its open + * state and view live in the app store, never in the URL. + */ +export function ConnectionsDrawer({ forced }: ConnectionsDrawerProps) { + const { t } = useTranslation("connections"); + const storeOpen = useAppStore((s) => s.connectionsDrawer.open); + const closeConnections = useAppStore((s) => s.closeConnections); + const count = useDeviceStore((s) => s.savedConnections.length); + const open = forced || storeOpen; + + return ( + { + if (!next && !forced) { + closeConnections(); + } + }} + > + { + if (forced) { + event.preventDefault(); + } + }} + className={cn( + // Floating inset panel on the right at every size. + "inset-y-2 right-2 h-auto rounded-2xl border border-border bg-background text-foreground shadow-2xl", + "w-[min(calc(100vw-16px),440px)]", + "motion-reduce:transition-none!", + "data-[vaul-drawer-direction=right]:w-[min(calc(100vw-16px),440px)] data-[vaul-drawer-direction=right]:sm:max-w-none", + )} + > + +
+ + {t("drawer.title")} + + {count} + + + + {t("page.description")} + +
+ {forced ? null : ( + + + + )} +
+
+ +
+
+
+ ); +} diff --git a/apps/web/src/pages/Connections/index.tsx b/apps/web/src/components/ConnectionsDrawer/ConnectionsList.tsx similarity index 88% rename from apps/web/src/pages/Connections/index.tsx rename to apps/web/src/components/ConnectionsDrawer/ConnectionsList.tsx index 95a68ed52..b271ab15c 100644 --- a/apps/web/src/pages/Connections/index.tsx +++ b/apps/web/src/components/ConnectionsDrawer/ConnectionsList.tsx @@ -1,6 +1,5 @@ import AddConnectionDialog from "@app/components/Dialog/AddConnectionDialog/AddConnectionDialog"; import { TimeAgo } from "@app/components/generic/TimeAgo"; -import LanguageSwitcher from "@app/components/LanguageSwitcher"; import { ConnectionStatusBadge } from "@app/components/PageComponents/Connections/ConnectionStatusBadge"; import type { Connection } from "@app/core/stores/deviceStore/types"; import { useConnections } from "@app/pages/Connections/useConnections"; @@ -36,11 +35,9 @@ import { DropdownMenuItem, DropdownMenuTrigger, } from "@components/UI/DropdownMenu.tsx"; -import { Separator } from "@components/UI/Separator.tsx"; import { useToast } from "@core/hooks/useToast.ts"; -import { useNavigate } from "@tanstack/react-router"; +import { useAppStore } from "@core/stores"; import { - ArrowLeft, LinkIcon, MoreHorizontal, RotateCw, @@ -52,7 +49,7 @@ import { import { useEffect, useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; -export const Connections = () => { +export const ConnectionsList = () => { const { connections, addConnectionAndConnect, @@ -64,7 +61,7 @@ export const Connections = () => { syncConnectionStatuses, } = useConnections(); const { toast } = useToast(); - const navigate = useNavigate({ from: "/" }); + const closeConnections = useAppStore((s) => s.closeConnections); const [addOpen, setAddOpen] = useState(false); const isURLHTTPS = useMemo(() => location.protocol === "https:", []); const { t } = useTranslation("connections"); @@ -95,36 +92,13 @@ export const Connections = () => { }, [connections]); return ( -
-
-
- -
-

- {t("page.title")} -

-

- {t("page.description")} -

-
-
-
- - -
-
- - +
+
+ +
{sorted.length === 0 ? ( @@ -144,7 +118,7 @@ export const Connections = () => { ) : ( -
+
{sorted.map((c) => ( { const ok = await connect(c.id, { allowPrompt: true }); // Success needs no toast: the connecting overlay shows it. if (ok) { - navigate({ to: "/" }); + closeConnections(); } else { toast({ title: t("toasts.failed"), @@ -196,7 +170,7 @@ export const Connections = () => { const ok = await connect(c.id, { allowPrompt: true }); // Success needs no toast: the connecting overlay shows it. if (ok) { - navigate({ to: "/" }); + closeConnections(); } else { toast({ title: t("toasts.failed"), @@ -228,7 +202,7 @@ export const Connections = () => { created.status === "connected" || created.status === "configured" ) { - navigate({ to: "/" }); + closeConnections(); } } else { toast({ diff --git a/apps/web/src/components/DeviceInfoPanel.tsx b/apps/web/src/components/DeviceInfoPanel.tsx index 7edc54ece..caaf78b26 100644 --- a/apps/web/src/components/DeviceInfoPanel.tsx +++ b/apps/web/src/components/DeviceInfoPanel.tsx @@ -1,7 +1,7 @@ import type { ConnectionStatus } from "@app/core/stores/deviceStore/types.ts"; +import { useAppStore } from "@core/stores"; import { cn } from "@core/utils/cn.ts"; import type { Protobuf } from "@meshtastic/sdk"; -import { useNavigate } from "@tanstack/react-router"; import { ChevronRight, CpuIcon, @@ -57,7 +57,7 @@ export const DeviceInfoPanel = ({ connectionName, }: DeviceInfoPanelProps) => { const { t } = useTranslation(); - const navigate = useNavigate({ from: "/" }); + const openConnections = useAppStore((s) => s.openConnections); const { batteryLevel, voltage } = deviceMetrics; const getStatusColor = (status?: ConnectionStatus): string => { @@ -154,7 +154,7 @@ export const DeviceInfoPanel = ({ {connectionStatus && ( -
+
{display}
{helper ? ( -

{helper}

+

{helper}

) : null}
); } +function SupportPill({ + supported, + labelSupported, + labelUnsupported, +}: { + supported: boolean; + labelSupported: string; + labelUnsupported: string; +}) { + return ( + + + ); +} + const TAB_META: Array<{ key: TabKey; label: string; Icon: LucideIcon }> = [ { key: "http", label: "HTTP", Icon: Globe }, { key: "bluetooth", label: "Bluetooth", Icon: Bluetooth }, { key: "serial", label: "Serial", Icon: Cable }, ]; -export default function AddConnectionDialog({ - open = false, - onOpenChange = () => {}, - onSave = async () => {}, +/** + * The "Add connection" form: HTTP, Bluetooth and Serial panes with their + * reachability test, validation and certificate guide. Rendered as a view + * inside the Connections drawer; it resets by unmounting. + */ +export function AddConnectionForm({ + onSave, isHTTPS = false, }: { - open?: boolean; - onOpenChange?: (open: boolean) => void; - onSave?: (conn: NewConnection, device?: BluetoothDevice) => Promise; + onSave: (conn: NewConnection, device?: BluetoothDevice) => Promise; isHTTPS?: boolean; }) { const { toast } = useToast(); @@ -336,7 +365,9 @@ export default function AddConnectionDialog({ ); // Lets an async test check whether the form changed while it ran. const stateRef = useRef(state); - stateRef.current = state; + useEffect(() => { + stateRef.current = state; + }, [state]); const { unsupported } = useBrowserFeatureDetection(); const { t } = useTranslation(); @@ -368,20 +399,10 @@ export default function AddConnectionDialog({ }); }, [isHTTPS, localNetworkAccess, httpAllowed, isLocalHost]); - const reset = useCallback(() => { - dispatch({ type: "RESET", payload: { isHTTPS } }); - }, [isHTTPS]); - - useEffect(() => { - if (!open) { - reset(); - } - }, [reset, open]); - const makeToastErrorHandler = useCallback( (titlePrefix: string) => (err: unknown): void => { - if (err && (err as { name?: string }).name === "NotFoundError") { + if (err instanceof Error && err.name === "NotFoundError") { return; // user canceled } const message = err instanceof Error ? err.message : String(err); @@ -438,19 +459,8 @@ export default function AddConnectionDialog({ return; } try { - const port = await ( - navigator as Navigator & { - serial: { - requestPort: (o: Record) => Promise; - }; - } - ).serial.requestPort({}); - const info = - ( - port as SerialPort & { - getInfo?: () => { usbVendorId?: number; usbProductId?: number }; - } - ).getInfo?.() ?? {}; + const port = await navigator.serial.requestPort({}); + const info = port.getInfo(); dispatch({ type: "SET_SERIAL_SELECTED", payload: { @@ -533,6 +543,7 @@ export default function AddConnectionDialog({ +

{t("addConnection.httpConnection.localNetwork.denied")}

)} {isHTTPS && !httpAllowed && ( -

+

{t("addConnection.httpConnection.localNetwork.unsupported")}

)}
-
+
) : null} ))} - +
); } diff --git a/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.test.tsx b/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.test.tsx index 327cec234..98c1736d9 100644 --- a/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.test.tsx +++ b/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.test.tsx @@ -1,10 +1,33 @@ import { useAppStore } from "@core/stores"; +import type React from "react"; import { act, fireEvent, render, screen } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { ConnectionsDrawer } from "./ConnectionsDrawer.tsx"; vi.mock("./ConnectionsList.tsx", () => ({ - ConnectionsList: () =>
, + ConnectionsList: ({ + addButtonRef, + }: { + addButtonRef?: React.Ref; + }) => ( +
+ +
+ ), +})); + +vi.mock("./AddConnectionForm.tsx", () => ({ + AddConnectionForm: () =>
, +})); + +vi.mock("@app/pages/Connections/useConnections", () => ({ + useConnections: () => ({ addConnectionAndConnect: vi.fn() }), })); describe("ConnectionsDrawer", () => { @@ -60,3 +83,44 @@ describe("ConnectionsDrawer", () => { }); }); }); + +describe("ConnectionsDrawer views", () => { + beforeEach(() => { + act(() => useAppStore.getState().closeConnections()); + }); + + it("opens on the list by default and on the add view when asked", () => { + render(); + + act(() => useAppStore.getState().openConnections()); + expect(screen.getByRole("heading", { name: /Connections/ })).not.toBeNull(); + expect( + screen.queryByRole("button", { name: "Back to connections" }), + ).toBeNull(); + + act(() => useAppStore.getState().openConnections("add")); + expect( + screen.getByRole("heading", { name: "Add connection" }), + ).not.toBeNull(); + }); + + it("focuses the title on push and the Add connection button on pop", () => { + render(); + act(() => useAppStore.getState().openConnections()); + + const addButton = screen.getByRole("button", { name: "Add connection" }); + fireEvent.click(addButton); + + const title = screen.getByRole("heading", { name: "Add connection" }); + expect(document.activeElement).toBe(title); + + fireEvent.click( + screen.getByRole("button", { name: "Back to connections" }), + ); + + expect(document.activeElement).toBe( + screen.getByRole("button", { name: "Add connection" }), + ); + expect(useAppStore.getState().connectionsDrawer.view).toBe("list"); + }); +}); diff --git a/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx b/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx index 98c6fbf74..55c651277 100644 --- a/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx +++ b/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx @@ -6,10 +6,14 @@ import { DrawerHeader, DrawerTitle, } from "@components/shadcn/drawer.tsx"; +import { useToast } from "@core/hooks/useToast.ts"; import { useAppStore, useDeviceStore } from "@core/stores"; import { cn } from "@core/utils/cn.ts"; -import { XIcon } from "lucide-react"; +import { useConnections } from "@app/pages/Connections/useConnections"; +import { ArrowLeft, XIcon } from "lucide-react"; +import { useEffect, useMemo, useRef } from "react"; import { useTranslation } from "react-i18next"; +import { AddConnectionForm } from "./AddConnectionForm.tsx"; import { ConnectionsList } from "./ConnectionsList.tsx"; export interface ConnectionsDrawerProps { @@ -20,15 +24,16 @@ export interface ConnectionsDrawerProps { forced: boolean; } +const iconButtonClasses = + "inline-flex size-11 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"; + /** * The Connections drawer. An overlay over whatever page is showing; its open * state and view live in the app store, never in the URL. */ export function ConnectionsDrawer({ forced }: ConnectionsDrawerProps) { - const { t } = useTranslation("connections"); const storeOpen = useAppStore((s) => s.connectionsDrawer.open); const closeConnections = useAppStore((s) => s.closeConnections); - const count = useDeviceStore((s) => s.savedConnections.length); const open = forced || storeOpen; return ( @@ -53,36 +58,122 @@ export function ConnectionsDrawer({ forced }: ConnectionsDrawerProps) { className={cn( // Floating inset panel on the right at every size. "inset-y-2 right-2 h-auto rounded-2xl border border-border bg-background text-foreground shadow-2xl", - "w-[min(calc(100vw-16px),440px)]", "motion-reduce:transition-none!", "data-[vaul-drawer-direction=right]:w-[min(calc(100vw-16px),440px)] data-[vaul-drawer-direction=right]:sm:max-w-none", )} > - -
- - {t("drawer.title")} + + + + ); +} + +/** Mounted only while the drawer is open, so each opening starts fresh. */ +function DrawerBody({ forced }: { forced: boolean }) { + const { t } = useTranslation("connections"); + const { toast } = useToast(); + const view = useAppStore((s) => s.connectionsDrawer.view); + const setConnectionsView = useAppStore((s) => s.setConnectionsView); + const closeConnections = useAppStore((s) => s.closeConnections); + const count = useDeviceStore((s) => s.savedConnections.length); + const { addConnectionAndConnect } = useConnections(); + const isURLHTTPS = useMemo(() => location.protocol === "https:", []); + + const titleRef = useRef(null); + const addButtonRef = useRef(null); + // Set when a view is popped, so the list can return focus to its trigger. + const returnFocusToAdd = useRef(false); + + const isList = view === "list"; + + // Focus: the title on push, the "Add connection" button on pop. + useEffect(() => { + if (!isList) { + titleRef.current?.focus(); + } else if (returnFocusToAdd.current) { + returnFocusToAdd.current = false; + addButtonRef.current?.focus(); + } + }, [isList]); + + const goBack = () => { + returnFocusToAdd.current = true; + setConnectionsView("list"); + }; + + return ( + <> + + {isList ? null : ( + + )} +
+ + {isList ? t("drawer.title") : t("drawer.addConnection")} + {isList ? ( {count} - - - {t("page.description")} - -
- {forced ? null : ( - - - - )} -
-
- + ) : null} + + + {t("page.description")} +
- - + {forced ? null : ( + + + + )} + +
+ {isList ? ( + + ) : ( + { + const created = await addConnectionAndConnect(partial, btDevice); + if (!created) { + toast({ + title: t("toasts.failed"), + description: t("toasts.savedCantConnect"), + }); + return; + } + toast({ + title: t("toasts.added"), + description: t("toasts.savedByName", { + name: created.name, + interpolation: { escapeValue: false }, + }), + }); + if ( + created.status === "connected" || + created.status === "configured" + ) { + closeConnections(); + } else { + goBack(); + } + }} + /> + )} +
+ ); } diff --git a/apps/web/src/components/ConnectionsDrawer/ConnectionsList.tsx b/apps/web/src/components/ConnectionsDrawer/ConnectionsList.tsx index b271ab15c..9cb4b3367 100644 --- a/apps/web/src/components/ConnectionsDrawer/ConnectionsList.tsx +++ b/apps/web/src/components/ConnectionsDrawer/ConnectionsList.tsx @@ -1,6 +1,4 @@ -import AddConnectionDialog from "@app/components/Dialog/AddConnectionDialog/AddConnectionDialog"; import { TimeAgo } from "@app/components/generic/TimeAgo"; -import { ConnectionStatusBadge } from "@app/components/PageComponents/Connections/ConnectionStatusBadge"; import type { Connection } from "@app/core/stores/deviceStore/types"; import { useConnections } from "@app/pages/Connections/useConnections"; import { @@ -8,51 +6,47 @@ import { formatConnectionSubtext, testHttpReachable, } from "@app/pages/Connections/utils"; -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, - AlertDialogTrigger, -} from "@components/UI/AlertDialog.tsx"; import { CertificateGuide } from "@components/CertificateGuide.tsx"; -import { Badge } from "@components/UI/Badge.tsx"; import { Button } from "@components/UI/Button.tsx"; -import { - Card, - CardContent, - CardFooter, - CardHeader, - CardTitle, -} from "@components/UI/Card.tsx"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "@components/UI/DropdownMenu.tsx"; -import { useToast } from "@core/hooks/useToast.ts"; import { useAppStore } from "@core/stores"; +import { useToast } from "@core/hooks/useToast.ts"; +import { cn } from "@core/utils/cn.ts"; import { LinkIcon, MoreHorizontal, + PlusIcon, RotateCw, - RouterIcon, Star, StarOff, Trash2, } from "lucide-react"; -import { useEffect, useMemo, useState } from "react"; +import { createElement, type Ref, useEffect, useMemo } from "react"; import { useTranslation } from "react-i18next"; -export const ConnectionsList = () => { +/** Tonal, rounded surface shared by cards and the empty state. */ +const surfaceClasses = + "rounded-xl bg-muted/50 ring-1 ring-border ring-inset dark:bg-muted/30"; + +const primaryButtonClasses = + "h-auto min-h-11 gap-2 rounded-xl bg-primary px-4 text-primary-foreground hover:bg-primary/90 focus:ring-ring dark:bg-primary dark:text-primary-foreground dark:hover:bg-primary/90"; + +const secondaryButtonClasses = + "h-auto min-h-11 gap-2 rounded-xl bg-background px-4 text-foreground ring-1 ring-border ring-inset hover:bg-muted focus:ring-ring dark:bg-background dark:text-foreground dark:hover:bg-muted"; + +export interface ConnectionsListProps { + /** The "Add connection" button, so the drawer can return focus to it. */ + addButtonRef?: Ref; +} + +export const ConnectionsList = ({ addButtonRef }: ConnectionsListProps) => { const { connections, - addConnectionAndConnect, connect, disconnect, removeConnection, @@ -62,8 +56,7 @@ export const ConnectionsList = () => { } = useConnections(); const { toast } = useToast(); const closeConnections = useAppStore((s) => s.closeConnections); - const [addOpen, setAddOpen] = useState(false); - const isURLHTTPS = useMemo(() => location.protocol === "https:", []); + const setConnectionsView = useAppStore((s) => s.setConnectionsView); const { t } = useTranslation("connections"); // On first mount, sync statuses and refresh @@ -91,140 +84,147 @@ export const ConnectionsList = () => { }); }, [connections]); + const connectAndClose = async (c: Connection, failureKey: string) => { + const ok = await connect(c.id, { allowPrompt: true }); + // Success needs no toast: the connecting overlay shows it. + if (ok) { + closeConnections(); + } else { + toast({ + title: t("toasts.failed"), + description: t(failureKey), + }); + } + }; + return ( -
-
-
{sorted.length === 0 ? ( - - - - {t("noConnections.title")}{" "} - - - +
+

+ {t("noConnections.title")} +

+

{t("noConnections.description")} - - - - - +

+
) : ( -
+
    {sorted.map((c) => ( - { - const ok = await connect(c.id, { allowPrompt: true }); - // Success needs no toast: the connecting overlay shows it. - if (ok) { - closeConnections(); - } else { +
  • + connectAndClose(c, "toasts.checkConnection")} + onRetry={() => connectAndClose(c, "toasts.pickConnectionAgain")} + onDisconnect={async () => { + await disconnect(c.id); toast({ - title: t("toasts.failed"), - description: t("toasts.checkConnection"), + title: t("toasts.disconnected"), + description: t("toasts.nowDisconnected", { + name: c.name, + interpolation: { escapeValue: false }, + }), }); - } - }} - onDisconnect={async () => { - await disconnect(c.id); - toast({ - title: t("toasts.disconnected"), - description: t("toasts.nowDisconnected", { - name: c.name, - interpolation: { escapeValue: false }, - }), - }); - }} - onSetDefault={() => { - setDefaultConnection(c.id); - toast({ - title: t("toasts.defaultSet"), - description: t("toasts.defaultConnection", { - name: c.name, - interpolation: { escapeValue: false }, - }), - }); - }} - onDelete={async () => { - await disconnect(c.id); - removeConnection(c.id); - toast({ - title: t("toasts.deleted"), - description: t("toasts.deletedByName", { - name: c.name, - interpolation: { escapeValue: false }, - }), - }); - }} - onRetry={async () => { - const ok = await connect(c.id, { allowPrompt: true }); - // Success needs no toast: the connecting overlay shows it. - if (ok) { - closeConnections(); - } else { + }} + onSetDefault={() => { + setDefaultConnection(c.id); toast({ - title: t("toasts.failed"), - description: t("toasts.pickConnectionAgain"), + title: t("toasts.defaultSet"), + description: t("toasts.defaultConnection", { + name: c.name, + interpolation: { escapeValue: false }, + }), }); - } - }} - /> + }} + onDelete={async () => { + await disconnect(c.id); + removeConnection(c.id); + toast({ + title: t("toasts.deleted"), + description: t("toasts.deletedByName", { + name: c.name, + interpolation: { escapeValue: false }, + }), + }); + }} + /> +
  • ))} -
+ )} - - { - const created = await addConnectionAndConnect(partial, btDevice); - if (created) { - setAddOpen(false); - toast({ - title: t("toasts.added"), - description: t("toasts.savedByName", { - name: created.name, - interpolation: { escapeValue: false }, - }), - }); - if ( - created.status === "connected" || - created.status === "configured" - ) { - closeConnections(); - } - } else { - toast({ - title: "Unable to connect", - description: "savedCantConnect", - }); - } - }} - />
); }; -function TypeBadge({ type }: { type: Connection["type"] }) { - const Icon = connectionTypeIcon(type); - const label = - type === "http" ? "HTTP" : type === "bluetooth" ? "Bluetooth" : "Serial"; +type StatusTone = "connected" | "busy" | "online" | "error" | "idle"; + +function statusTone(status: Connection["status"]): StatusTone { + switch (status) { + case "connected": + case "configured": + return "connected"; + case "connecting": + case "configuring": + return "busy"; + case "online": + return "online"; + case "error": + return "error"; + default: + return "idle"; + } +} + +const statusDot: Record = { + connected: "bg-emerald-500", + busy: "bg-amber-500", + online: "bg-sky-500", + error: "bg-red-500", + idle: "bg-muted-foreground/40", +}; + +function StatusPill({ + status, + className, +}: { + status: Connection["status"]; + className?: string; +}) { + const tone = statusTone(status); + const label = tone === "connected" ? "connected" : status; return ( - - + + + ); } @@ -237,15 +237,14 @@ function ConnectionCard({ onRetry, }: { connection: Connection; - onConnect: () => Promise | Promise; - onDisconnect: () => Promise | Promise; + onConnect: () => Promise; + onDisconnect: () => Promise; onSetDefault: () => void; - onDelete: () => void; - onRetry: () => Promise | Promise; + onDelete: () => void | Promise; + onRetry: () => Promise; }) { const { t } = useTranslation("connections"); - const Icon = connectionTypeIcon(connection.type); const isBusy = connection.status === "connecting" || connection.status === "configuring"; const isConnected = @@ -253,94 +252,88 @@ function ConnectionCard({ const isError = connection.status === "error"; return ( - - -
-
- - - {connection.name} - {connection.isDefault ? ( - - - {t("default")} - - ) : null} - -
- - - {formatConnectionSubtext(connection)} +
+
+ {/* Avatar steps up with the drawer. */} + +
+
+

+ {connection.name} +

+ {connection.isDefault ? ( + + + {t("default")} -
-
-
- - - - - - - - {connection.type === "http" && connection.isDefault && ( - onSetDefault()} - > - - {t("button.unsetDefault")} - - )} - {connection.type === "http" && !connection.isDefault && ( - onSetDefault()} - > - - {t("button.setDefault")} - - )} - - - e.preventDefault()} - > - - {t("button.delete")} - - - - - - {t("deleteConnection")} - - - {t("areYouSure", { name: connection.name })} - - - - - {t("button.cancel")} - - onDelete()} - > - {t("button.delete")} - - - - - - + ) : null} + {/* At wide sizes the status sits inline with the name. */} +
+

+ {formatConnectionSubtext(connection)} +

+
- - + + + + + + {connection.type === "http" ? ( + onSetDefault()} + > + {connection.isDefault ? ( + + ) : ( + + )} + {connection.isDefault + ? t("button.unsetDefault") + : t("button.setDefault")} + + ) : null} + void onDelete()} + > + + {t("button.delete")} + + + +
+ +
{connection.error ? (

@@ -359,33 +352,31 @@ function ConnectionCard({ )}

) : connection.lastConnectedAt ? ( -

+

{t("lastConnectedAt", { date: "" })}{" "}

) : ( -

- {t("neverConnected")} -

+

{t("neverConnected")}

)} - - +
+ +
{isConnected ? ( ) : ( )} - - +
+ ); } diff --git a/apps/web/src/components/Dialog/AddConnectionDialog/dialogReducer.test.ts b/apps/web/src/components/ConnectionsDrawer/addConnectionReducer.test.ts similarity index 98% rename from apps/web/src/components/Dialog/AddConnectionDialog/dialogReducer.test.ts rename to apps/web/src/components/ConnectionsDrawer/addConnectionReducer.test.ts index 1d31f5921..7a77e0765 100644 --- a/apps/web/src/components/Dialog/AddConnectionDialog/dialogReducer.test.ts +++ b/apps/web/src/components/ConnectionsDrawer/addConnectionReducer.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest"; import { createInitialDialogState, dialogReducer, -} from "./AddConnectionDialog.tsx"; +} from "./AddConnectionForm.tsx"; const testing = createInitialDialogState({ protocol: "https", diff --git a/apps/web/src/components/ConnectionsDrawer/textSizes.test.ts b/apps/web/src/components/ConnectionsDrawer/textSizes.test.ts new file mode 100644 index 000000000..7f0892659 --- /dev/null +++ b/apps/web/src/components/ConnectionsDrawer/textSizes.test.ts @@ -0,0 +1,42 @@ +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; + +/** + * WCAG 2.1 house floor: drawer text is sized through Tailwind's rem scale and + * nothing renders below 12px. Arbitrary `text-[...]` sizes are caught here; + * `text-xs` is the smallest named step. + */ +const drawerDir = import.meta.dirname; + +const componentFiles = readdirSync(drawerDir) + .filter((name) => /\.tsx$/.test(name) && !/\.test\.tsx$/.test(name)) + .map((name) => join(drawerDir, name)); + +const ARBITRARY_TEXT_SIZE = /\btext-\[(\d*\.?\d+)(px|rem|em)\]/g; + +const toPx = (value: number, unit: string) => + unit === "px" ? value : value * 16; + +describe("drawer text sizes", () => { + it("covers the drawer components", () => { + expect(componentFiles.length).toBeGreaterThan(0); + }); + + it.each(componentFiles)( + "%s uses no arbitrary text size below 12px", + (file) => { + const source = readFileSync(file, "utf8"); + const tooSmall = Array.from(source.matchAll(ARBITRARY_TEXT_SIZE)).filter( + ([, value, unit]) => toPx(Number(value), unit ?? "px") < 12, + ); + expect(tooSmall.map(([match]) => match)).toEqual([]); + }, + ); + + it.each(componentFiles)("%s has no fixed px font sizes", (file) => { + const source = readFileSync(file, "utf8"); + expect(source.match(/\btext-\[\d*\.?\d+px\]/g) ?? []).toEqual([]); + expect(source.match(/fontSize:\s*["']?\d/g) ?? []).toEqual([]); + }); +}); diff --git a/apps/web/src/components/Dialog/AddConnectionDialog/validation.ts b/apps/web/src/components/ConnectionsDrawer/validation.ts similarity index 100% rename from apps/web/src/components/Dialog/AddConnectionDialog/validation.ts rename to apps/web/src/components/ConnectionsDrawer/validation.ts diff --git a/apps/web/src/components/UI/Button.tsx b/apps/web/src/components/UI/Button.tsx index f96eb6aff..64df1b9e6 100644 --- a/apps/web/src/components/UI/Button.tsx +++ b/apps/web/src/components/UI/Button.tsx @@ -43,6 +43,8 @@ export interface ButtonProps VariantProps { icon?: React.ReactNode; iconAlignment?: "left" | "right"; + /** React 19: the ref is an ordinary prop, forwarded to the button. */ + ref?: React.Ref; } const Button = ({ diff --git a/apps/web/src/core/stores/appStore/appStore.test.ts b/apps/web/src/core/stores/appStore/appStore.test.ts index 3c4b421a2..2f02dd7b6 100644 --- a/apps/web/src/core/stores/appStore/appStore.test.ts +++ b/apps/web/src/core/stores/appStore/appStore.test.ts @@ -67,10 +67,10 @@ describe("AppStore – basic state & actions", () => { open: true, view: "add", }); - state.setConnectionsView({ edit: "abc" }); + state.setConnectionsView("list"); expect(useAppStore.getState().connectionsDrawer).toEqual({ open: true, - view: { edit: "abc" }, + view: "list", }); state.closeConnections(); expect(useAppStore.getState().connectionsDrawer).toEqual({ diff --git a/apps/web/src/core/stores/appStore/types.ts b/apps/web/src/core/stores/appStore/types.ts index d84ad4061..2c45f5a96 100644 --- a/apps/web/src/core/stores/appStore/types.ts +++ b/apps/web/src/core/stores/appStore/types.ts @@ -5,8 +5,8 @@ export interface RasterSource { tileSize: number; } -/** Which screen the Connections drawer shows; `edit` carries the connection id. */ -export type ConnectionsView = "list" | "add" | { edit: string }; +/** Which screen the Connections drawer shows. */ +export type ConnectionsView = "list" | "add"; export interface ConnectionsDrawerState { open: boolean; diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 7c8c80955..153acf0ae 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -95,7 +95,8 @@ --secondary: oklch(0.97 0 0); --secondary-foreground: oklch(0.205 0 0); --muted: oklch(0.97 0 0); - --muted-foreground: oklch(0.556 0 0); + /* Stock 0.556 is 4.34:1 on --muted; 0.5 gives 5.5:1 (WCAG 1.4.3). */ + --muted-foreground: oklch(0.5 0 0); --destructive: oklch(0.577 0.245 27.325); --destructive-foreground: oklch(0.985 0 0); --border: oklch(0.922 0 0); From 26b00be0cc98eb94806daaad7441f4c96e688b90 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sat, 14 Nov 2026 22:09:35 -0500 Subject: [PATCH 04/49] feat(web): resizable Connections drawer with remembered width MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Desktop (md+): a left-edge handle, role=separator with aria-valuenow/min/ max, 12px hit area straddling the edge, grip visible on hover, focus and while dragging. Width clamps to 360px … min(960px, 75vw) and re-clamps on window resize. Arrow keys move 16px, Shift+Arrow 64px, Home/End go to the limits, Enter or double-click resets to 440px. Dragging previews the width and stores it on release; the handle stops propagation and carries data-vaul-no-drag so vaul's drag-to-close never starts. - Below md the drawer is min(100vw - 16px, 440px) and not resizable. - Persisted through the repo's useLocalStorage under meshtastic:web:sidebar:width; the deserializer accepts only finite numbers, anything else falls back to 440 and storage errors fail soft. - Tests: restore, invalid values, clamp and re-clamp, keyboard, drag, limits, propagation, double-click reset. --- .../public/i18n/locales/en/connections.json | 3 +- .../ConnectionsDrawer/ConnectionsDrawer.tsx | 18 ++- .../DrawerResizeHandle.test.tsx | 136 +++++++++++++++++ .../ConnectionsDrawer/DrawerResizeHandle.tsx | 143 ++++++++++++++++++ .../ConnectionsDrawer/useDrawerWidth.ts | 84 ++++++++++ 5 files changed, 382 insertions(+), 2 deletions(-) create mode 100644 apps/web/src/components/ConnectionsDrawer/DrawerResizeHandle.test.tsx create mode 100644 apps/web/src/components/ConnectionsDrawer/DrawerResizeHandle.tsx create mode 100644 apps/web/src/components/ConnectionsDrawer/useDrawerWidth.ts diff --git a/apps/web/public/i18n/locales/en/connections.json b/apps/web/public/i18n/locales/en/connections.json index ccd9d79c5..2393f49e7 100644 --- a/apps/web/public/i18n/locales/en/connections.json +++ b/apps/web/public/i18n/locales/en/connections.json @@ -3,7 +3,8 @@ "title": "Connections", "close": "Close connections", "back": "Back to connections", - "addConnection": "Add connection" + "addConnection": "Add connection", + "resize": "Resize connections drawer" }, "page": { "title": "Connect to a Meshtastic device", diff --git a/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx b/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx index 55c651277..6b274dd5c 100644 --- a/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx +++ b/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx @@ -7,14 +7,17 @@ import { DrawerTitle, } from "@components/shadcn/drawer.tsx"; import { useToast } from "@core/hooks/useToast.ts"; +import { useIsMobile } from "@core/hooks/useIsMobile.ts"; import { useAppStore, useDeviceStore } from "@core/stores"; import { cn } from "@core/utils/cn.ts"; import { useConnections } from "@app/pages/Connections/useConnections"; import { ArrowLeft, XIcon } from "lucide-react"; -import { useEffect, useMemo, useRef } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { AddConnectionForm } from "./AddConnectionForm.tsx"; import { ConnectionsList } from "./ConnectionsList.tsx"; +import { DrawerResizeHandle } from "./DrawerResizeHandle.tsx"; +import { useDrawerWidth } from "./useDrawerWidth.ts"; export interface ConnectionsDrawerProps { /** @@ -35,6 +38,10 @@ export function ConnectionsDrawer({ forced }: ConnectionsDrawerProps) { const storeOpen = useAppStore((s) => s.connectionsDrawer.open); const closeConnections = useAppStore((s) => s.closeConnections); const open = forced || storeOpen; + // Below md the drawer is min(100vw - 16px, 440px) wide and not resizable. + const isMobile = useIsMobile(); + const drawerWidth = useDrawerWidth(); + const [draftWidth, setDraftWidth] = useState(undefined); return ( + {isMobile ? null : ( + + )} diff --git a/apps/web/src/components/ConnectionsDrawer/DrawerResizeHandle.test.tsx b/apps/web/src/components/ConnectionsDrawer/DrawerResizeHandle.test.tsx new file mode 100644 index 000000000..c95ea4846 --- /dev/null +++ b/apps/web/src/components/ConnectionsDrawer/DrawerResizeHandle.test.tsx @@ -0,0 +1,136 @@ +import { act, fireEvent, render, screen } from "@testing-library/react"; +import { useState } from "react"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { DrawerResizeHandle } from "./DrawerResizeHandle.tsx"; +import { DRAWER_WIDTH_KEY, useDrawerWidth } from "./useDrawerWidth.ts"; + +function Harness() { + const drawerWidth = useDrawerWidth(); + const [draft, setDraft] = useState(undefined); + return ( +
+ + {draft ?? ""} +
+ ); +} + +const handle = () => screen.getByRole("separator"); +const valueNow = () => Number(handle().getAttribute("aria-valuenow")); +const stored = () => window.localStorage.getItem(DRAWER_WIDTH_KEY); + +const setViewport = (width: number) => { + Object.defineProperty(window, "innerWidth", { + configurable: true, + writable: true, + value: width, + }); +}; + +describe("DrawerResizeHandle", () => { + beforeEach(() => { + window.localStorage.clear(); + setViewport(1400); + HTMLElement.prototype.setPointerCapture = () => {}; + }); + afterEach(() => { + window.localStorage.clear(); + }); + + it("exposes the width as a vertical separator with its limits", () => { + render(); + expect(handle().getAttribute("aria-orientation")).toBe("vertical"); + expect(valueNow()).toBe(440); + expect(handle().getAttribute("aria-valuemin")).toBe("360"); + // min(960px, 75vw) at 1400px wide + expect(handle().getAttribute("aria-valuemax")).toBe("960"); + }); + + it("restores a stored width", () => { + window.localStorage.setItem(DRAWER_WIDTH_KEY, "520"); + render(); + expect(valueNow()).toBe(520); + }); + + it("falls back to the default for invalid stored values", () => { + for (const raw of ['"wide"', "null", "{}", "not json", "NaN"]) { + window.localStorage.setItem(DRAWER_WIDTH_KEY, raw); + const { unmount } = render(); + expect(valueNow()).toBe(440); + unmount(); + } + }); + + it("clamps a stored width to the limits and re-clamps on resize", () => { + window.localStorage.setItem(DRAWER_WIDTH_KEY, "5000"); + render(); + expect(valueNow()).toBe(960); + + act(() => { + setViewport(800); + window.dispatchEvent(new Event("resize")); + }); + expect(handle().getAttribute("aria-valuemax")).toBe("600"); + expect(valueNow()).toBe(600); + }); + + it("moves with the keyboard and stores the result", () => { + render(); + fireEvent.keyDown(handle(), { key: "ArrowLeft" }); + expect(valueNow()).toBe(456); + fireEvent.keyDown(handle(), { key: "ArrowRight", shiftKey: true }); + expect(valueNow()).toBe(392); + fireEvent.keyDown(handle(), { key: "Home" }); + expect(valueNow()).toBe(360); + fireEvent.keyDown(handle(), { key: "End" }); + expect(valueNow()).toBe(960); + fireEvent.keyDown(handle(), { key: "Enter" }); + expect(valueNow()).toBe(440); + expect(stored()).toBe("440"); + }); + + it("drags from the left edge, previews, then stores on release", () => { + render(); + const el = handle(); + + fireEvent.pointerDown(el, { button: 0, pointerId: 1, clientX: 900 }); + fireEvent.pointerMove(el, { pointerId: 1, clientX: 800 }); + expect(screen.getByTestId("draft").textContent).toBe("540"); + expect(stored()).toBeNull(); + + fireEvent.pointerUp(el, { pointerId: 1, clientX: 780 }); + expect(screen.getByTestId("draft").textContent).toBe(""); + expect(valueNow()).toBe(560); + expect(stored()).toBe("560"); + }); + + it("never lets a drag go past the limits", () => { + render(); + const el = handle(); + fireEvent.pointerDown(el, { button: 0, pointerId: 2, clientX: 900 }); + fireEvent.pointerUp(el, { pointerId: 2, clientX: 2500 }); + expect(valueNow()).toBe(360); + fireEvent.pointerDown(el, { button: 0, pointerId: 3, clientX: 900 }); + fireEvent.pointerUp(el, { pointerId: 3, clientX: -2000 }); + expect(valueNow()).toBe(960); + }); + + it("stops the pointer event so vaul's drag-to-close never starts", () => { + let reachedParent = false; + render( +
(reachedParent = true)}> + +
, + ); + fireEvent.pointerDown(handle(), { button: 0, pointerId: 4, clientX: 10 }); + expect(reachedParent).toBe(false); + expect(handle().hasAttribute("data-vaul-no-drag")).toBe(true); + }); + + it("resets on double-click", () => { + window.localStorage.setItem(DRAWER_WIDTH_KEY, "700"); + render(); + fireEvent.doubleClick(handle()); + expect(valueNow()).toBe(440); + }); +}); diff --git a/apps/web/src/components/ConnectionsDrawer/DrawerResizeHandle.tsx b/apps/web/src/components/ConnectionsDrawer/DrawerResizeHandle.tsx new file mode 100644 index 000000000..917215925 --- /dev/null +++ b/apps/web/src/components/ConnectionsDrawer/DrawerResizeHandle.tsx @@ -0,0 +1,143 @@ +import { cn } from "@core/utils/cn.ts"; +import type { KeyboardEvent, PointerEvent } from "react"; +import { useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { + DEFAULT_DRAWER_WIDTH, + DRAWER_RESIZE_BIG_STEP, + DRAWER_RESIZE_STEP, + type DrawerWidth, +} from "./useDrawerWidth.ts"; + +export interface DrawerResizeHandleProps { + drawerWidth: DrawerWidth; + /** The width being dragged, before it is stored. */ + onDraft: (width: number | undefined) => void; +} + +/** + * The left-edge resize handle of the right-hand drawer. Dragging shows a live + * width and stores it on release; keys move 16px (64px with Shift), Home and + * End go to the limits, Enter and double-click reset to the default. + */ +export function DrawerResizeHandle({ + drawerWidth, + onDraft, +}: DrawerResizeHandleProps) { + const { t } = useTranslation("connections"); + const { width, min, max, setWidth, reset } = drawerWidth; + const drag = useRef< + { pointerId: number; startX: number; startWidth: number } | undefined + >(undefined); + const [dragging, setDragging] = useState(false); + + const clamp = (next: number) => Math.min(max, Math.max(min, next)); + + const onPointerDown = (event: PointerEvent) => { + if (event.button !== 0) { + return; + } + // Resizing must never start vaul's drag-to-close. + event.stopPropagation(); + event.preventDefault(); + event.currentTarget.setPointerCapture(event.pointerId); + drag.current = { + pointerId: event.pointerId, + startX: event.clientX, + startWidth: width, + }; + setDragging(true); + }; + + const onPointerMove = (event: PointerEvent) => { + const current = drag.current; + if (!current || current.pointerId !== event.pointerId) { + return; + } + event.stopPropagation(); + // The drawer sits on the right: moving the handle left widens it. + onDraft(clamp(current.startWidth + (current.startX - event.clientX))); + }; + + const endDrag = (event: PointerEvent) => { + const current = drag.current; + if (!current || current.pointerId !== event.pointerId) { + return; + } + event.stopPropagation(); + drag.current = undefined; + setDragging(false); + setWidth(clamp(current.startWidth + (current.startX - event.clientX))); + onDraft(undefined); + }; + + const onKeyDown = (event: KeyboardEvent) => { + const step = event.shiftKey ? DRAWER_RESIZE_BIG_STEP : DRAWER_RESIZE_STEP; + let next: number | undefined; + switch (event.key) { + case "ArrowLeft": + case "ArrowUp": + next = width + step; + break; + case "ArrowRight": + case "ArrowDown": + next = width - step; + break; + case "Home": + next = min; + break; + case "End": + next = max; + break; + case "Enter": + next = DEFAULT_DRAWER_WIDTH; + break; + default: + return; + } + event.preventDefault(); + event.stopPropagation(); + setWidth(clamp(next)); + }; + + // A focusable, draggable separator is a widget;
can take neither focus + // nor children, so the role is set explicitly. + /* oxlint-disable jsx-a11y/prefer-tag-over-role */ + return ( +
reset()} + onKeyDown={onKeyDown} + className={cn( + // A 12px hit area straddling the drawer's left edge. + "group/handle absolute inset-y-0 -left-1.5 z-10 flex w-3 cursor-col-resize touch-none items-center justify-center outline-none", + )} + > +
+ ); + /* oxlint-enable jsx-a11y/prefer-tag-over-role */ +} diff --git a/apps/web/src/components/ConnectionsDrawer/useDrawerWidth.ts b/apps/web/src/components/ConnectionsDrawer/useDrawerWidth.ts new file mode 100644 index 000000000..2ee57bd1d --- /dev/null +++ b/apps/web/src/components/ConnectionsDrawer/useDrawerWidth.ts @@ -0,0 +1,84 @@ +import useLocalStorage from "@core/hooks/useLocalStorage.ts"; +import { useCallback, useSyncExternalStore } from "react"; + +export const DRAWER_WIDTH_KEY = "meshtastic:web:sidebar:width"; +export const DEFAULT_DRAWER_WIDTH = 440; +export const MIN_DRAWER_WIDTH = 360; +export const MAX_DRAWER_WIDTH = 960; +/** The drawer never takes more than this share of the viewport. */ +export const MAX_DRAWER_VIEWPORT_RATIO = 0.75; +export const DRAWER_RESIZE_STEP = 16; +export const DRAWER_RESIZE_BIG_STEP = 64; + +export function maxDrawerWidth(viewportWidth: number): number { + return Math.max( + MIN_DRAWER_WIDTH, + Math.min( + MAX_DRAWER_WIDTH, + Math.floor(viewportWidth * MAX_DRAWER_VIEWPORT_RATIO), + ), + ); +} + +export function clampDrawerWidth(width: number, viewportWidth: number): number { + const max = maxDrawerWidth(viewportWidth); + return Math.min(max, Math.max(MIN_DRAWER_WIDTH, Math.round(width))); +} + +/** + * Reads a stored width. Anything that is not a finite number falls back to + * the default; a parse failure is caught by useLocalStorage and does the same. + */ +export function parseStoredWidth(raw: string): number { + const parsed: unknown = JSON.parse(raw); + return typeof parsed === "number" && Number.isFinite(parsed) + ? parsed + : DEFAULT_DRAWER_WIDTH; +} + +const subscribeToResize = (onChange: () => void) => { + window.addEventListener("resize", onChange); + return () => window.removeEventListener("resize", onChange); +}; +const getViewportWidth = () => window.innerWidth; + +export interface DrawerWidth { + /** The width to render, clamped to the current viewport. */ + width: number; + min: number; + max: number; + /** Stores a width; it is clamped first. */ + setWidth: (next: number) => void; + reset: () => void; +} + +/** + * The desktop drawer width, remembered in localStorage and re-clamped to + * 360px … min(960px, 75vw) whenever the window resizes. + */ +export function useDrawerWidth(): DrawerWidth { + const viewportWidth = useSyncExternalStore( + subscribeToResize, + getViewportWidth, + () => MAX_DRAWER_WIDTH, + ); + const [stored, setStored] = useLocalStorage( + DRAWER_WIDTH_KEY, + DEFAULT_DRAWER_WIDTH, + { deserializer: parseStoredWidth }, + ); + + const setWidth = useCallback( + (next: number) => setStored(clampDrawerWidth(next, window.innerWidth)), + [setStored], + ); + const reset = useCallback(() => setStored(DEFAULT_DRAWER_WIDTH), [setStored]); + + return { + width: clampDrawerWidth(stored, viewportWidth), + min: MIN_DRAWER_WIDTH, + max: maxDrawerWidth(viewportWidth), + setWidth, + reset, + }; +} From 5ac0e9610497b9adc4312277fe14957db5461161 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sat, 14 Nov 2026 22:14:01 -0500 Subject: [PATCH 05/49] feat(web): inline delete confirmation in the Connections drawer Choosing Delete from a row's overflow menu swaps that row's actions for an inline strip: "Delete {name}?", Cancel and a destructive Delete. Focus lands on Cancel as the menu's focus scope unmounts (onCloseAutoFocus); Escape cancels and returns focus to the menu trigger, and the drawer's onEscapeKeyDown ignores Escape inside a strip so it does not close. Only one strip is open at a time. After the delete, focus moves to the next row's menu button, else the previous one, else Add connection. The AlertDialog kit component and @radix-ui/react-alert-dialog had no other users and are removed. Tests: strip swap and focus, Escape, single strip, focus after deleting a middle, last and only row. --- apps/web/package.json | 1 - .../public/i18n/locales/en/connections.json | 3 +- .../ConnectionsDrawer/ConnectionsDrawer.tsx | 6 +- .../ConnectionsList.test.tsx | 161 +++++++++++++++ .../ConnectionsDrawer/ConnectionsList.tsx | 194 ++++++++++++++---- apps/web/src/components/UI/AlertDialog.tsx | 149 -------------- pnpm-lock.yaml | 29 --- 7 files changed, 326 insertions(+), 217 deletions(-) create mode 100644 apps/web/src/components/ConnectionsDrawer/ConnectionsList.test.tsx delete mode 100644 apps/web/src/components/UI/AlertDialog.tsx diff --git a/apps/web/package.json b/apps/web/package.json index d2f49df70..b46248dd2 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -42,7 +42,6 @@ "@noble/curves": "^2.4.0", "@preact/signals-core": "^1.14.4", "@radix-ui/react-accordion": "^1.3.1", - "@radix-ui/react-alert-dialog": "^1.2.1", "@radix-ui/react-checkbox": "^1.4.1", "@radix-ui/react-dialog": "^1.3.1", "@radix-ui/react-dropdown-menu": "^2.2.1", diff --git a/apps/web/public/i18n/locales/en/connections.json b/apps/web/public/i18n/locales/en/connections.json index 2393f49e7..63702590b 100644 --- a/apps/web/public/i18n/locales/en/connections.json +++ b/apps/web/public/i18n/locales/en/connections.json @@ -4,7 +4,8 @@ "close": "Close connections", "back": "Back to connections", "addConnection": "Add connection", - "resize": "Resize connections drawer" + "resize": "Resize connections drawer", + "deleteConfirm": "Delete {{name}}?" }, "page": { "title": "Connect to a Meshtastic device", diff --git a/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx b/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx index 6b274dd5c..c2a02f062 100644 --- a/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx +++ b/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx @@ -58,7 +58,11 @@ export function ConnectionsDrawer({ forced }: ConnectionsDrawerProps) { data-shadcn-scope="" aria-describedby={undefined} onEscapeKeyDown={(event) => { - if (forced) { + // Escape inside an inline delete strip cancels the strip only. + const inInlineConfirm = + event.target instanceof Element && + event.target.closest("[data-inline-confirm]") !== null; + if (forced || inInlineConfirm) { event.preventDefault(); } }} diff --git a/apps/web/src/components/ConnectionsDrawer/ConnectionsList.test.tsx b/apps/web/src/components/ConnectionsDrawer/ConnectionsList.test.tsx new file mode 100644 index 000000000..0d0d86655 --- /dev/null +++ b/apps/web/src/components/ConnectionsDrawer/ConnectionsList.test.tsx @@ -0,0 +1,161 @@ +import type { Connection } from "@app/core/stores/deviceStore/types"; +import { + act, + fireEvent, + render, + screen, + waitFor, + within, +} from "@testing-library/react"; +import { createRef } from "react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { ConnectionsList } from "./ConnectionsList.tsx"; + +const connectionsMock = vi.hoisted(() => ({ + connections: [] as Connection[], + removeConnection: vi.fn(), + disconnect: vi.fn(async () => {}), +})); + +vi.mock("@app/pages/Connections/useConnections", () => ({ + useConnections: () => ({ + connections: connectionsMock.connections, + connect: vi.fn(async () => true), + disconnect: connectionsMock.disconnect, + removeConnection: connectionsMock.removeConnection, + setDefaultConnection: vi.fn(), + refreshStatuses: vi.fn(), + syncConnectionStatuses: vi.fn(), + }), +})); + +vi.mock("@core/hooks/useToast.ts", () => ({ + useToast: () => ({ toast: vi.fn() }), +})); + +const http = (id: number, name: string): Connection => ({ + id, + type: "http", + name, + url: `http://${name.toLowerCase()}.local`, + createdAt: 1, + status: "disconnected", +}); + +const row = (name: string) => screen.getByRole("article", { name }); +const menuButton = (name: string) => + within(row(name)).getByRole("button", { name: "More actions" }); + +const openDeleteStrip = (name: string) => { + fireEvent.pointerDown(menuButton(name), { + button: 0, + ctrlKey: false, + pointerType: "mouse", + }); + fireEvent.click(screen.getByRole("menuitem", { name: "Delete" })); +}; + +const strip = (name: string) => + within(row(name)).queryByText(`Delete ${name}?`); + +describe("ConnectionsList inline delete", () => { + beforeEach(() => { + connectionsMock.connections = [ + http(1, "Alpha"), + http(2, "Bravo"), + http(3, "Charlie"), + ]; + connectionsMock.removeConnection.mockImplementation((id: number) => { + connectionsMock.connections = connectionsMock.connections.filter( + (c) => c.id !== id, + ); + }); + }); + + it("swaps the row's actions for a strip and focuses Cancel", async () => { + render(); + expect(within(row("Bravo")).getByRole("button", { name: "Connect" })); + + openDeleteStrip("Bravo"); + + expect(strip("Bravo")).not.toBeNull(); + expect( + within(row("Bravo")).queryByRole("button", { name: "Connect" }), + ).toBeNull(); + const cancel = within(row("Bravo")).getByRole("button", { name: "Cancel" }); + // The menu's focus scope hands focus over as it unmounts, a tick later. + await waitFor(() => expect(document.activeElement).toBe(cancel)); + }); + + it("Escape cancels and returns focus to the trigger", async () => { + render(); + openDeleteStrip("Bravo"); + const cancel = within(row("Bravo")).getByRole("button", { name: "Cancel" }); + await waitFor(() => expect(document.activeElement).toBe(cancel)); + + fireEvent.keyDown(cancel, { key: "Escape" }); + + expect(strip("Bravo")).toBeNull(); + expect(document.activeElement).toBe(menuButton("Bravo")); + expect(connectionsMock.removeConnection).not.toHaveBeenCalled(); + }); + + it("keeps only one strip open at a time", () => { + render(); + openDeleteStrip("Alpha"); + expect(strip("Alpha")).not.toBeNull(); + + openDeleteStrip("Charlie"); + + expect(strip("Alpha")).toBeNull(); + expect(strip("Charlie")).not.toBeNull(); + }); + + it("deletes and moves focus to the next row", async () => { + const { rerender } = render(); + openDeleteStrip("Bravo"); + + await act(async () => { + fireEvent.click( + within(row("Bravo")).getByRole("button", { name: "Delete" }), + ); + }); + rerender(); + + expect(connectionsMock.removeConnection).toHaveBeenCalledWith(2); + expect(screen.queryByRole("article", { name: "Bravo" })).toBeNull(); + expect(document.activeElement).toBe(menuButton("Charlie")); + }); + + it("falls back to the previous row when the last one goes", async () => { + const { rerender } = render(); + openDeleteStrip("Charlie"); + + await act(async () => { + fireEvent.click( + within(row("Charlie")).getByRole("button", { name: "Delete" }), + ); + }); + rerender(); + + expect(document.activeElement).toBe(menuButton("Bravo")); + }); + + it("falls back to Add connection when no rows remain", async () => { + connectionsMock.connections = [http(1, "Alpha")]; + const addRef = createRef(); + const { rerender } = render(); + openDeleteStrip("Alpha"); + + await act(async () => { + fireEvent.click( + within(row("Alpha")).getByRole("button", { name: "Delete" }), + ); + }); + rerender(); + + expect(document.activeElement).toBe( + screen.getByRole("button", { name: "Add connection" }), + ); + }); +}); diff --git a/apps/web/src/components/ConnectionsDrawer/ConnectionsList.tsx b/apps/web/src/components/ConnectionsDrawer/ConnectionsList.tsx index 9cb4b3367..08b7c90e4 100644 --- a/apps/web/src/components/ConnectionsDrawer/ConnectionsList.tsx +++ b/apps/web/src/components/ConnectionsDrawer/ConnectionsList.tsx @@ -1,5 +1,8 @@ import { TimeAgo } from "@app/components/generic/TimeAgo"; -import type { Connection } from "@app/core/stores/deviceStore/types"; +import type { + Connection, + ConnectionId, +} from "@app/core/stores/deviceStore/types"; import { useConnections } from "@app/pages/Connections/useConnections"; import { connectionTypeIcon, @@ -26,7 +29,15 @@ import { StarOff, Trash2, } from "lucide-react"; -import { createElement, type Ref, useEffect, useMemo } from "react"; +import { + createElement, + type KeyboardEvent, + type RefObject, + useEffect, + useMemo, + useRef, + useState, +} from "react"; import { useTranslation } from "react-i18next"; /** Tonal, rounded surface shared by cards and the empty state. */ @@ -39,11 +50,17 @@ const primaryButtonClasses = const secondaryButtonClasses = "h-auto min-h-11 gap-2 rounded-xl bg-background px-4 text-foreground ring-1 ring-border ring-inset hover:bg-muted focus:ring-ring dark:bg-background dark:text-foreground dark:hover:bg-muted"; +const destructiveButtonClasses = + "h-auto min-h-11 gap-2 rounded-xl bg-destructive px-4 text-destructive-foreground hover:bg-destructive/90 focus:ring-ring dark:bg-destructive dark:text-destructive-foreground dark:hover:bg-destructive/90"; + export interface ConnectionsListProps { /** The "Add connection" button, so the drawer can return focus to it. */ - addButtonRef?: Ref; + addButtonRef?: RefObject; } +/** Where focus goes once a row is deleted: a row's menu button, or Add. */ +type FocusTarget = { row: ConnectionId } | "add"; + export const ConnectionsList = ({ addButtonRef }: ConnectionsListProps) => { const { connections, @@ -58,6 +75,12 @@ export const ConnectionsList = ({ addButtonRef }: ConnectionsListProps) => { const closeConnections = useAppStore((s) => s.closeConnections); const setConnectionsView = useAppStore((s) => s.setConnectionsView); const { t } = useTranslation("connections"); + // The one connection whose actions are swapped for the delete strip. + const [confirmingId, setConfirmingId] = useState( + undefined, + ); + const listRef = useRef(null); + const pendingFocus = useRef(undefined); // On first mount, sync statuses and refresh useEffect(() => { @@ -84,6 +107,30 @@ export const ConnectionsList = ({ addButtonRef }: ConnectionsListProps) => { }); }, [connections]); + // After a delete the rows have re-rendered; move focus to the chosen one. + useEffect(() => { + const target = pendingFocus.current; + if (!target) { + return; + } + pendingFocus.current = undefined; + if (target === "add") { + addButtonRef?.current?.focus(); + return; + } + const row = listRef.current?.querySelector( + `[data-connection-id="${target.row}"] [data-row-focus]`, + ); + if (row instanceof HTMLElement) { + row.focus(); + } + }, [connections, addButtonRef]); + + const focusTargetAfter = (index: number): FocusTarget => { + const next = sorted[index + 1] ?? sorted[index - 1]; + return next ? { row: next.id } : "add"; + }; + const connectAndClose = async (c: Connection, failureKey: string) => { const ok = await connect(c.id, { allowPrompt: true }); // Success needs no toast: the connecting overlay shows it. @@ -129,11 +176,17 @@ export const ConnectionsList = ({ addButtonRef }: ConnectionsListProps) => {

) : ( -
    - {sorted.map((c) => ( -
  • +
      + {sorted.map((c, index) => ( +
    • setConfirmingId(c.id)} + onCancelDelete={() => setConfirmingId(undefined)} onConnect={() => connectAndClose(c, "toasts.checkConnection")} onRetry={() => connectAndClose(c, "toasts.pickConnectionAgain")} onDisconnect={async () => { @@ -157,6 +210,8 @@ export const ConnectionsList = ({ addButtonRef }: ConnectionsListProps) => { }); }} onDelete={async () => { + pendingFocus.current = focusTargetAfter(index); + setConfirmingId(undefined); await disconnect(c.id); removeConnection(c.id); toast({ @@ -230,6 +285,9 @@ function StatusPill({ function ConnectionCard({ connection, + confirmingDelete, + onRequestDelete, + onCancelDelete, onConnect, onDisconnect, onSetDefault, @@ -237,6 +295,9 @@ function ConnectionCard({ onRetry, }: { connection: Connection; + confirmingDelete: boolean; + onRequestDelete: () => void; + onCancelDelete: () => void; onConnect: () => Promise; onDisconnect: () => Promise; onSetDefault: () => void; @@ -244,6 +305,26 @@ function ConnectionCard({ onRetry: () => Promise; }) { const { t } = useTranslation("connections"); + const menuTriggerRef = useRef(null); + const cancelRef = useRef(null); + // The menu returns focus to its trigger as it closes; when the strip is + // opening, focus belongs to Cancel instead. The strip is already rendered + // by the time the menu's focus scope unmounts, so it is focused there. + const focusCancelOnMenuClose = useRef(false); + + const cancelDelete = () => { + onCancelDelete(); + menuTriggerRef.current?.focus(); + }; + + // Escape cancels the strip; the drawer ignores it (see ConnectionsDrawer). + const onStripKeyDown = (event: KeyboardEvent) => { + if (event.key === "Escape") { + event.preventDefault(); + event.stopPropagation(); + cancelDelete(); + } + }; const isBusy = connection.status === "connecting" || connection.status === "configuring"; @@ -294,6 +375,8 @@ function ConnectionCard({
-
- {isConnected ? ( - - ) : ( - - )} -
+ {confirmingDelete ? ( +
+

+ {t("drawer.deleteConfirm", { name: connection.name })} +

+
+ + +
+
+ ) : ( +
+ {isConnected ? ( + + ) : ( + + )} +
+ )} ); } diff --git a/apps/web/src/components/UI/AlertDialog.tsx b/apps/web/src/components/UI/AlertDialog.tsx deleted file mode 100644 index 264328cb6..000000000 --- a/apps/web/src/components/UI/AlertDialog.tsx +++ /dev/null @@ -1,149 +0,0 @@ -import { cn } from "@core/utils/cn.ts"; -import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"; -import * as React from "react"; -import { buttonVariants } from "./Button.tsx"; - -const AlertDialog = AlertDialogPrimitive.Root; - -const AlertDialogTrigger = AlertDialogPrimitive.Trigger; - -const AlertDialogPortal = ({ - children, - ...props -}: AlertDialogPrimitive.AlertDialogPortalProps) => ( - -
- {children} -
-
-); -AlertDialogPortal.displayName = AlertDialogPrimitive.Portal.displayName; - -const AlertDialogOverlay = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)); -AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName; - -const AlertDialogContent = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - - - - -)); -AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName; - -const AlertDialogHeader = ({ - className, - ...props -}: React.HTMLAttributes) => ( -
-); -AlertDialogHeader.displayName = "AlertDialogHeader"; - -const AlertDialogFooter = ({ - className, - ...props -}: React.HTMLAttributes) => ( -
-); -AlertDialogFooter.displayName = "AlertDialogFooter"; - -const AlertDialogTitle = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)); -AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName; - -const AlertDialogDescription = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)); -AlertDialogDescription.displayName = - AlertDialogPrimitive.Description.displayName; - -const AlertDialogAction = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)); -AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName; - -const AlertDialogCancel = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)); -AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName; - -export { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, - AlertDialogTrigger, -}; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ec9ebc6e9..5a9867e0f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -90,9 +90,6 @@ importers: '@radix-ui/react-accordion': specifier: ^1.3.1 version: 1.3.1(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) - '@radix-ui/react-alert-dialog': - specifier: ^1.2.1 - version: 1.2.1(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) '@radix-ui/react-checkbox': specifier: ^1.4.1 version: 1.4.1(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) @@ -1591,19 +1588,6 @@ packages: '@types/react-dom': optional: true - '@radix-ui/react-alert-dialog@1.2.1': - resolution: {integrity: sha512-MWC4N7RY+qsbNrFNo7yQ9ZbdoZEW+B5DtpWxJfUnVCqcQxxqqg3qis3RMPTDbCNaTIdHJSn5XDkl9ZdVWXknLg==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - '@radix-ui/react-arrow@1.1.17': resolution: {integrity: sha512-67jjcVvxjXCCStnTW3Z+M7jmaFMuMR7M2JgpDzH4w7JSRrikmzhjfYgP/09ECb8n7whnsgh1ifJ+Ie96qEj+pQ==} peerDependencies: @@ -7010,19 +6994,6 @@ snapshots: '@types/react': 19.3.0 '@types/react-dom': 19.3.0(@types/react@19.3.0) - '@radix-ui/react-alert-dialog@1.2.1(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': - dependencies: - '@radix-ui/primitive': 1.2.0 - '@radix-ui/react-compose-refs': 1.1.5(@types/react@19.3.0)(react@19.3.1) - '@radix-ui/react-context': 1.3.0(@types/react@19.3.0)(react@19.3.1) - '@radix-ui/react-dialog': 1.3.1(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) - '@radix-ui/react-primitive': 2.2.0(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) - react: 19.3.1 - react-dom: 19.3.1(react@19.3.1) - optionalDependencies: - '@types/react': 19.3.0 - '@types/react-dom': 19.3.0(@types/react@19.3.0) - '@radix-ui/react-arrow@1.1.17(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': dependencies: '@radix-ui/react-primitive': 2.2.0(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) From da21dc105a386118747f152170c08ef6ebe32186 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 07:48:45 -0500 Subject: [PATCH 06/49] build(sdk-kmp): add the Kotlin meshtastic-sdk compiled to JavaScript packages/sdk-kmp is a Gradle Kotlin/JS build (wrapper committed) over org.meshtastic:sdk-core-js, pinned once in gradle.properties and resolved from mavenLocal until meshtastic-sdk#215 is released. Its jsMain holds the @JsExport facade (createHttpClient, MeshtasticClient, ConnectionStateJs) and an HTTP RadioTransport with Local Network Access handling. The build emits ES modules plus sdk-kmp.d.mts into dist/, which the workspace consumes as @meshtastic/sdk-kmp; apps/web predev/prebuild hooks build it when missing, and CI sets up JDK 21 with a Gradle cache. Nothing in the app uses it yet. --- .github/workflows/ci.yml | 14 +- .github/workflows/e2e.yml | 12 + .github/workflows/nightly.yml | 12 + .github/workflows/pr.yml | 12 + .github/workflows/release-web.yml | 12 + README.md | 7 + apps/web/package.json | 3 + packages/sdk-kmp/.gitignore | 5 + packages/sdk-kmp/README.md | 50 ++++ packages/sdk-kmp/build.gradle.kts | 32 +++ packages/sdk-kmp/gradle.properties | 7 + .../gradle/gradle-daemon-jvm.properties | 13 + .../sdk-kmp/gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 49154 bytes .../gradle/wrapper/gradle-wrapper.properties | 10 + packages/sdk-kmp/gradlew | 248 ++++++++++++++++++ packages/sdk-kmp/package.json | 29 ++ packages/sdk-kmp/scripts/build.mjs | 55 ++++ packages/sdk-kmp/settings.gradle.kts | 21 ++ .../kotlin/org/meshtastic/sdk/js/Bytes.kt | 15 ++ .../kotlin/org/meshtastic/sdk/js/Client.kt | 66 +++++ .../org/meshtastic/sdk/js/HttpTransport.kt | 110 ++++++++ .../jsMain/kotlin/org/meshtastic/sdk/js/Js.kt | 32 +++ .../kotlin/org/meshtastic/sdk/js/Lna.kt | 65 +++++ .../kotlin/org/meshtastic/sdk/js/State.kt | 48 ++++ .../org/meshtastic/sdk/js/TappingTransport.kt | 29 ++ pnpm-lock.yaml | 5 + 26 files changed, 911 insertions(+), 1 deletion(-) create mode 100644 packages/sdk-kmp/.gitignore create mode 100644 packages/sdk-kmp/README.md create mode 100644 packages/sdk-kmp/build.gradle.kts create mode 100644 packages/sdk-kmp/gradle.properties create mode 100644 packages/sdk-kmp/gradle/gradle-daemon-jvm.properties create mode 100644 packages/sdk-kmp/gradle/wrapper/gradle-wrapper.jar create mode 100644 packages/sdk-kmp/gradle/wrapper/gradle-wrapper.properties create mode 100755 packages/sdk-kmp/gradlew create mode 100644 packages/sdk-kmp/package.json create mode 100644 packages/sdk-kmp/scripts/build.mjs create mode 100644 packages/sdk-kmp/settings.gradle.kts create mode 100644 packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Bytes.kt create mode 100644 packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt create mode 100644 packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/HttpTransport.kt create mode 100644 packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Js.kt create mode 100644 packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Lna.kt create mode 100644 packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/State.kt create mode 100644 packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/TappingTransport.kt diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d67bb772e..325680964 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,13 +32,25 @@ jobs: pnpm fetch pnpm install --frozen-lockfile --offline + - name: Setup JDK 21 (for @meshtastic/sdk-kmp) + uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: 21 + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v5 + + - name: Build @meshtastic/sdk-kmp + run: pnpm --filter @meshtastic/sdk-kmp build + - name: Build All Packages (with exclusions) shell: bash run: | set -euo pipefail # List packages to exclude (full paths under repo root) - EXCLUDED_DIRS=("packages/protobufs" "packages/transport-deno" "packages/ui" "packages/web") + EXCLUDED_DIRS=("packages/protobufs" "packages/sdk-kmp" "packages/transport-deno" "packages/ui" "packages/web") is_excluded() { local dir="$1" diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 0a28e4e0a..ab4f4790f 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -32,6 +32,18 @@ jobs: - name: Install workspace deps run: pnpm install --frozen-lockfile + - name: Setup JDK 21 (for @meshtastic/sdk-kmp) + uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: 21 + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v5 + + - name: Build @meshtastic/sdk-kmp + run: pnpm --filter @meshtastic/sdk-kmp build + - name: Install Chromium run: pnpm exec playwright install --with-deps chromium diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 55e73691f..01e90977f 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -33,6 +33,18 @@ jobs: - name: Install dependencies (root) run: pnpm install --frozen-lockfile + - name: Setup JDK 21 (for @meshtastic/sdk-kmp) + uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: 21 + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v5 + + - name: Build @meshtastic/sdk-kmp + run: pnpm --filter @meshtastic/sdk-kmp build + - name: Run tests run: pnpm run test diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index bc5817f99..70f6a2a8a 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -47,6 +47,18 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile + - name: Setup JDK 21 (for @meshtastic/sdk-kmp) + uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: 21 + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v5 + + - name: Build @meshtastic/sdk-kmp + run: pnpm --filter @meshtastic/sdk-kmp build + - name: Run linter run: pnpm run lint diff --git a/.github/workflows/release-web.yml b/.github/workflows/release-web.yml index 6f30930bb..b458d2a2d 100644 --- a/.github/workflows/release-web.yml +++ b/.github/workflows/release-web.yml @@ -50,6 +50,18 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile + - name: Setup JDK 21 (for @meshtastic/sdk-kmp) + uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: 21 + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v5 + + - name: Build @meshtastic/sdk-kmp + run: pnpm --filter @meshtastic/sdk-kmp build + - name: Build web package working-directory: apps/web run: pnpm run build diff --git a/README.md b/README.md index aae4e0feb..88860144b 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ Libraries live under `packages/`; the reference web client lives under `apps/`. | Package | Purpose | | --- | --- | | `packages/sdk` | Framework-agnostic TypeScript SDK. Domain-driven feature slices (device, chat, nodes, channels, config, telemetry, position, traceroute, files) built around a `MeshClient` orchestrator with `@preact/signals-core` reactive state. | +| `packages/sdk-kmp` | The Kotlin Multiplatform [meshtastic-sdk](https://github.com/meshtastic/meshtastic-sdk) compiled to JavaScript (Gradle, JDK 21) with a small `@JsExport` facade and browser transports. The web client's connection and mesh behaviour comes from here. | | `packages/sdk-react` | React hooks + `MeshProvider` on top of `@meshtastic/sdk`. Wraps signals in `useSyncExternalStore` for concurrent-safe renders. | | `apps/web` | Reference React web client. Hosted at [client.meshtastic.org](https://client.meshtastic.org). | | `packages/ui` | Shared Radix + Tailwind component library. | @@ -89,6 +90,12 @@ Expected domain errors are returned as `Result` via [`better-result`](http `pnpm -r build`, since it runs `buf generate`). If you only want to run the web client in dev, `pnpm --filter meshtastic-web dev` does not need Buf as long as the protobuf stubs are already generated. +- [JDK 21](https://adoptium.net/) — required to build `@meshtastic/sdk-kmp`, + the Kotlin meshtastic-sdk compiled to JavaScript that the web client + connects through. `pnpm --filter meshtastic-web dev` builds it on first + run (its `predev` hook); on macOS `brew install openjdk@21` and + `export JAVA_HOME=/opt/homebrew/opt/openjdk@21`. See + `packages/sdk-kmp/README.md` for how the SDK version is pinned. ### Setup diff --git a/apps/web/package.json b/apps/web/package.json index b46248dd2..ac38ab3cf 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -15,6 +15,7 @@ "scripts": { "preinstall": "npx only-allow pnpm", "setup:certs": "mkcert localhost 127.0.0.1 ::1", + "prebuild": "pnpm --filter @meshtastic/sdk-kmp ensure-dist", "build": "vite build", "build:analyze": "BUNDLE_ANALYZE=true pnpm run build", "lint": "oxlint", @@ -23,6 +24,7 @@ "format:fix": "oxfmt .", "check": "pnpm lint && pnpm format", "check:fix": "pnpm lint:fix && pnpm format:fix", + "predev": "pnpm --filter @meshtastic/sdk-kmp ensure-dist", "dev": "vite", "dev:https": "USE_HTTPS=true vite", "test": "vitest", @@ -34,6 +36,7 @@ "dependencies": { "@hookform/resolvers": "^5.9.1", "@meshtastic/sdk": "workspace:*", + "@meshtastic/sdk-kmp": "workspace:*", "@meshtastic/sdk-react": "workspace:*", "@meshtastic/sdk-storage-sqlocal": "workspace:*", "@meshtastic/transport-http": "workspace:*", diff --git a/packages/sdk-kmp/.gitignore b/packages/sdk-kmp/.gitignore new file mode 100644 index 000000000..2b56c54d7 --- /dev/null +++ b/packages/sdk-kmp/.gitignore @@ -0,0 +1,5 @@ +.gradle/ +.kotlin/ +build/ +dist/ +kotlin-js-store/ diff --git a/packages/sdk-kmp/README.md b/packages/sdk-kmp/README.md new file mode 100644 index 000000000..eeb772310 --- /dev/null +++ b/packages/sdk-kmp/README.md @@ -0,0 +1,50 @@ +# @meshtastic/sdk-kmp + +The [Kotlin Multiplatform meshtastic-sdk](https://github.com/meshtastic/meshtastic-sdk) +compiled to JavaScript, plus the small Kotlin/JS facade the web client talks to. +The SDK owns all mesh and connection behaviour (handshake, connection state, +auto-reconnect, node DB, admin); this package owns only the glue: + +- `src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt`: the `@JsExport` surface + (`createHttpClient`, `MeshtasticClient`, `ConnectionStateJs`). Only plain + objects, `Promise`s, `Uint8Array`s and unsubscribe functions cross into + TypeScript; protobuf messages cross as bytes and are decoded with + `@meshtastic/protobufs`. +- Browser transports implementing the SDK's `RadioTransport`: `HttpTransport.kt` + (device HTTP API with Chrome Local Network Access handling in `Lna.kt`). + +## Prerequisites + +- **JDK 21.** On macOS: `brew install openjdk@21` and + `export JAVA_HOME=/opt/homebrew/opt/openjdk@21`. The Gradle wrapper is + committed; Gradle itself is downloaded on first use. +- Node.js (already required by the workspace); the Kotlin build uses it for + its own tooling. + +## Building + +```bash +pnpm --filter @meshtastic/sdk-kmp build +``` + +runs `./gradlew jsBrowserProductionLibraryDistribution` and copies the ES +modules and `sdk-kmp.d.mts` into `dist/`, which the workspace consumes as +`@meshtastic/sdk-kmp`. `apps/web`'s `predev` and `prebuild` hooks run +`ensure-dist`, which only builds when `dist/` is missing, so `pnpm dev` works +from a clean checkout once JDK 21 is installed. + +## SDK version + +The SDK version is pinned once, in `gradle.properties`: + +```properties +meshtasticSdkVersion=0.2.1-spike-js-target-SNAPSHOT +``` + +Until meshtastic-sdk publishes its `js` artifacts +([meshtastic/meshtastic-sdk#215](https://github.com/meshtastic/meshtastic-sdk/pull/215)), +`org.meshtastic:sdk-core-js` is resolved from `mavenLocal()`; publish it there +from a checkout of that PR with +`JAVA_HOME=/opt/homebrew/opt/openjdk@21 ./gradlew publishToMavenLocal`. +Switching to a Maven Central release is a one-line change to +`meshtasticSdkVersion`, plus dropping `mavenLocal()` from `settings.gradle.kts`. diff --git a/packages/sdk-kmp/build.gradle.kts b/packages/sdk-kmp/build.gradle.kts new file mode 100644 index 000000000..6eb2d3fdf --- /dev/null +++ b/packages/sdk-kmp/build.gradle.kts @@ -0,0 +1,32 @@ +import org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsEnvSpec +import org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootPlugin +import org.jetbrains.kotlin.gradle.targets.js.npm.LockFileMismatchReport +import org.jetbrains.kotlin.gradle.targets.js.npm.NpmExtension + +plugins { + kotlin("multiplatform") version "2.4.10" +} + +val sdkVersion = providers.gradleProperty("meshtasticSdkVersion").get() + +kotlin { + js { + browser() + binaries.library() + generateTypeScriptDefinitions() + useEsModules() + } + sourceSets { + jsMain.dependencies { + api("org.meshtastic:sdk-core:$sdkVersion") + } + } +} + +plugins.withType { + extensions.configure { download.set(false) } + extensions.configure { + packageLockMismatchReport.set(LockFileMismatchReport.NONE) + reportNewPackageLock.set(false) + } +} diff --git a/packages/sdk-kmp/gradle.properties b/packages/sdk-kmp/gradle.properties new file mode 100644 index 000000000..d2cf4f359 --- /dev/null +++ b/packages/sdk-kmp/gradle.properties @@ -0,0 +1,7 @@ +org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8 +org.gradle.caching=true +org.gradle.configuration-cache=true +kotlin.js.yarn=false +# Pinned meshtastic-sdk version. Switching to a Maven Central release is this one line +# (and dropping mavenLocal() from settings.gradle.kts). +meshtasticSdkVersion=0.2.1-spike-js-target-SNAPSHOT diff --git a/packages/sdk-kmp/gradle/gradle-daemon-jvm.properties b/packages/sdk-kmp/gradle/gradle-daemon-jvm.properties new file mode 100644 index 000000000..5c34300fa --- /dev/null +++ b/packages/sdk-kmp/gradle/gradle-daemon-jvm.properties @@ -0,0 +1,13 @@ +#This file is generated by updateDaemonJvm +toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/56a19bc915b9ba2eb62ba7554c61b919/redirect +toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/398ffe3949748bfb1d5636f023d228fd/redirect +toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/56a19bc915b9ba2eb62ba7554c61b919/redirect +toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/398ffe3949748bfb1d5636f023d228fd/redirect +toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/e99bae143b75f9a10ead10248f02055e/redirect +toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/04e088f8677de3b384108493cc9481d0/redirect +toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/56a19bc915b9ba2eb62ba7554c61b919/redirect +toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/398ffe3949748bfb1d5636f023d228fd/redirect +toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/e55dccbfe27cb97945148c61a39c89c5/redirect +toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/dbd05c4936d573642f94cd149e1356c8/redirect +toolchainVendor=JETBRAINS +toolchainVersion=21 diff --git a/packages/sdk-kmp/gradle/wrapper/gradle-wrapper.jar b/packages/sdk-kmp/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..51cbd2a6f8121b2ce12daf979b128058fb9672ee GIT binary patch literal 49154 zcma&OV|1nKwk@2bVmq0!ZQHhO+h)bKZB(38Y}=`zV%v6Zt-Wr$-@W^sv%dYdHs4?K z&oiDrdLMm^F{gs`H&9d{NJvN^ARxj&pa1Vc1cCyR6;%hzs2^rks%InQpN&4@i?cFB(v z-M(*+9p)GpVFh0|Q&|H$3~7y1>nj^sp)F4KdOQ7ZYY$i0^%@)D?(UUY2Oqa~O-NT) zOS^{7+TjluBM%!>1Kd73v)b$vQy*S0ci;F3fwv}yVk%tAAQYyj^gV6OK1G;!9vdu0 zDox12IZpCz&VtXW6fgH&Xl@*LM0Yw;+=3R@kn&(oL_)MHq-^4h ziloqQ;YM4`)-Q$-`hQ&u4tSU1XfMK*c>%mjH7s9?7CSx&CJU6+zDw09Aczx=7}{5T zB3v9D=x8yX9}pNU69oA*hV2VXuv3BigbBWK56c~ZWUH+)B{KHrxsxO32F zPxY?VAcXf89f7!7=uR{_O69bOCX06}5kzr{TRX!eU2F%pejHDwcs+e<@oy`=fK3mB z!v~EC!tOmi{^pRRN+$uDpuHG?Bn4NKEirR1L-#ch&FlzfeZ$V(G2I3KHA@!Pj-{B2 z=IP@Bd@ODoJsQuXt9tj z*|A7$pyJSQH)T$wB!Ch%2cJ7u+q>KrH$UC^zH?w9>>vfUgwQ4)*oo;^0QsVSwqbE{ zwVf(vdhOWq!5-Y-cG|#w%j__+qTu&ysquQmiJp6wiv&_c^ypd^01}zY@@Y(4Y;YIf zYUCwAzqg+r&(<{@%v7Ase+W+mJPi~_4lz9kBlkLbe4zk;WLHT=JLGVFXY9}Pcn6@s z*(S7<;RsGhRT6OD!DIwparxA!t^$(4E3w;ehI+}{Q3|k#1lEwkmtxu#5@2We)`_zd zLkmW4%~Xj4UPWtCkYA1A2nL}b-*91Qt^qjTs1>KaBk<^t2*T8)0yZRMl9;M}sbz0d_ERfsXTIYPt|* z)<8ts6N!-`35%l^znDvAxyFBuon0Z0`^NMf-z?ySQ)XRYz#XH|{hBX_fX;djHfp_< zA(3FR!PWxv_m_Jil8yvc-0EGD{cg){2h7dm0lFzTCz_e$#fN4=+<(KYh14l?a5-d^ zfPyAsx{9~wTiKh=n!f9Kd+WNWH@TZ(riZ@#202kD!5aU42?!J8IHcN!A{HKf*;RyZ zcv@TE0DWIfeN4fktgpm`@U3HaNC~x`dh6RKX$}yQYfuz+elh_qwPpfzTM@R(nG|U&;*q z_f>>=I}|m`2Nq%wV{1}xfPxt^H&lu=C$D9sM`4P>xY0TcVx&H+W)N@bgrid*x7>d6 zcP>0`lWh!2c{_o@kw+8ddI-~I=v^p^A|euqk~?1|WUhxJ$eV@j<`Q6U=QgqatP=ch zb1lv{F!NOFkGed525LskPL2=tUiBGc^EBe7V5&+c;K-1K`ONhkyI=zFJITG*Uaa3u zg`R=$Sr-L~myczhGI_4H2cK_P>+m`ThR1MBnQ`=&)%wWc1~2E5A@|J}*Pr}b4Ud}* z!1gub9DPDvpr+p(VXXTi5zBpv31|0EW;3L#i^y{|_I#=~{>ni>+Y&Zn--!oE=_ z#;>;{v2%~=9ThJo=QM%cL*d5E7d#$B_#f01z_I1rq9JV~U`m=iG@iQ%av-|5cCQA$ z%G{QYztF-TM=G2h8fg}N8Po3r{a`39QU>obM%$O$&4b$a+4D<*R@+}%;&{r04IQDF z3V)B_4>~Hb*zb$+>Mdfk8W9DeK~I*?-Uda}2jQrIs%pKfc1u(yJHi>L59HS}svrpc zvBHA<%@lg7d?tC;q8R6nl)jFt20p#;xC@bb9;{!jZvfF}uAKnxZ7{N6yQ58`(uawq ztXkVsX4EZG=z9>CLlzWXSMTj8sRXv+Pb7iZT}S}j`_^D2k8M_4Fn^GVs8z@)0cE3B z$;w2NWj^`tD_-5%h=O_TK5L#!u*6zHcRAh@_O=?FxXA4I5BqcYo1^pm#M1#w@*9+t zxw<2^wIm4k2q|OykPmJISDH}7MuheOj-AUn(>3D3p?I;3mG-Mq%*X>7cenDI>L{3}EHRWf zxQ@vi1gliTBw|r8zRft7o$cr*5fUZuq*qZUR#}78Sor0;7gm#7eR-L7WoI7mBmeC; z_QLd4Kr;6l`AiKg2%X7zhUu7oM)|Cl)OA5s`G|~Q8C@otpyX~gJIbD5Ond->kT^y6 za7{+~1bVlHIy77S9K}gp&Uo3qpX9h2fmq#1oS-bgMW$H}JyRsbTQMxpi6IYEGk19b zIC<8!A3&4Qp#nT}fUTXatqER}Cfnv?@6adpAX$nS@Etxr2Moma0Sm!1y8Fa|4+4%E z8HTg~s%y&`BlOwT?r?HT1g|wER+#UYQ0Xob*0dsahE}L*&x8$sBD9L?eZ#0HN!)~t zwEU9xo;5?E?g5vBh#%!anPan@YEjh~+v1GG2&B&83uE0g($Zv`VGxK}M}{m@O>kzA zr#H6jW+c?}a&xyZLP=e)F(vdt21pKEKZ9B!oL{_#DR!TwVF_xYt9N_B;;KIdDQfI8 zQpQ&>i>O3ac53$~LyaVFdPs%Hv(=StN*X$QLru2A!DNF&nv5#Okp(a@D0fhdlFqU3 zZRPeZ3-nYG0oLB;ahxB?<&^0a7$X&PK`%K;C$a0Z=P^$7(@>3V*vri&C7timgKN~V zqGhUV=1bc8&=UPe1{iFV!Kqfrnz&vM(>J=v7Iqc==FluAnKj%dcMUNKR(2syhYBSh zq+rYVwn6*B^FWAVgP|4Vi~O>pUjA3uf>;^eA51|WAe$D5m2UI5UGtV#J69l|;0lu=f(ZgBOa_IT5y zSMm??r&VI-b7$Ir&vW29otI?UkxGe?R0f~RRsqlE5=xRTEesva6{f+w^Yi@LX$GpS z)uUIxTAo;>Z|T{pxrDiSyLjEG%|F;ZItV-Xz(*CjN_(nYgY)+_*fI6dsp>OCz(=>f zxiS2>v2&hSOtpu>?$iYO@Lo|_sQ$Jw>7dR5hjE?F+O;S#bJEKyg3&E>lZMEim3G@W z$GI)yu@1DniqycZe7Zu$T>j>*mN|TgQGGN;GqTBlc+HuPis3u!REgcrqi=M8Cg9&5 zaBl#(E-x@7KZeY4W3z%{*F+Q$=3_ekRWsMyE#;~^xOQp8G#-R zwHtC6o!+Yg@8qNTfinqO|y@AtSZlvRVOQ-t;<-Z@nCvF-tjay z^T48yk;B7oj>jx?+y*B6N)F?qAp6VtH8ZN|!V_{?@F_2$yuEym#^Cf(vgKjn7RxZQZPsJ*>Q-@A>t8&x<&9 zD7$J*SkdPhP;y5__KhyGZrI42Ej{Q3gf;%r0+|NM_oSssc8bV_Ws-{M;C^J$yh$~H zJjNZ)tuZ#&M%fZ83v~}LhP~7NW1ZF1c#8Nli=pJ{qNbDPN%>gdqyp*@vy`y%p_g?J z?|Tzs+~aU`3APxM&v;Q|G3+8boZgm7?5fJNZt$nm9tCL#$hwvyyc0Mepl)&?AcgzQ5_8J(v>y2ENiG+cWHyOJ;b8uW zz4)YZqH_R`YraE9{5<ePTBdC<>YrPjp<>p9ec?P00Q%m<0rl!(T0Yi-P>yDVjqTIHWYcQ z1fZaIRkx9LjfB7(lVyshjBKcsMMaWkwCx@hxVkTm4g2F~5TY-KUFa;JIGcOW#6fg1 zW+~K7CH{WO0(U~(x_ZzY9GRb@MG>hM4rBf5`4edfNZKPW5#&EnSO3Szll^1l<^Q{In<{C`qX?pYhNjZl zrb$nTUI(`7SrnKm3Q%L}LsCfs8$*HaO}MzP!k?G?-Y6WF*qyn?c&IXOl=EWd_xbXQ+e?Fvxp{HHOWieBvA%*7`(w&lOqSXr)SA6y=-UaG z=o%~7BCjFTB@CC1LyrYZaQ$A3jeb_G;{*m+wI=;)r)DzJNaJ>srkqBt%e=m|COVp1 z$Po%Pnv}A$GPCpQ8XZHZ%8;#Rs0RscAH$)SYuBaY0&=^dr0-ml?Pa>@NqCbPM^Ye% z@D|(FLHkfnd$-yKx>!CzUw$i6zxgq}_;)n|+7GBFY&4`>%0m>KcfDYS9|d;^1P(Zpefo9hSS0F z$lSeQMy#hsM@~e%S}mb~;aSoF8VBCc0-bK#*#rLvFf?`t=9sfq*M6r%9l_Z3k`{fm z+Q4J28C4krrWhV*mTZ(12)Wj^&5-o6{IJ#&=32M&(m?LPVc8@@2KR1um5d=Bi&tb=JSf{LTDzFP$7LDIiw6JB$$mzH?)mLbD^2S?A1AO z>xhOl2?DXVy|IXD42a{e(7x(#uouS9C^hGMr(f@@gu{UGq%aDm&XG}2(H4N8f!P6b zD2%>?{oTM^ZJfwrz+0o)oMW(~3&pX@DCGMv#o>=!f*lVQ5t{ztPmsUR%rg^Q?Fa${ zl>P0Wc!c>M(X3$Thw3Vo&SwVQj~T7f;R60dMaH>3DI+PYv5y2CZuG^ zFsP)DRd2Y_cvQxv+{FCGZ!MAQ~b8I}4wm6Q>YGV^gv5sr5GLv_&TAxob_hcq_Ry9l4~VwZX)#^cK!pZ>G-L z>A3tZzQ%1sxcbS_b{*%pcE2y3c~Co>MxiPz$Zx7=9Y^b_ljW=S%jsxnd9;}LVgneD zvGvMjZr0sEg?}qwNNGDxAfYYPQ&;AmIaw~+QtCMzz_7N=LkDYJJ>I`yA;Xpw5Y9Cq zT?<%Xnqsnl31UXS0s{HgxkQzXF@24sxjn`i^047&?3o6gU#3u9id`(yB@AK5NW|g| z(_LQll;g3`L`DqKrx)Fy>1sK2nyIk^8caJ_0TUSn81N>#6bP0JuhaSs1hGT-qntHz3%NDqb&CUp-x2--EXfJ&H}OA!%>w-= z!1DYjfE6+|vv)ETvvhKHQFb-@-@^EB$Zb-!RbJ3Q^`j%8tS?91a(A^p*RsH_xFu5X z0Y*iIX^o;+9swM&b=eYI&Pysenww|*&a2;gf~ez$W_B}s$YTC1ca={p6i9eBElVnX zT0hEuTX)WLz8vx2`ut`9%Fp=T-Tis@Tq~7eUD;1VnG~s}#uRC`c-r2lyTP=WsfujU z5<=KYY|$`|t6B+dyJ-0f$FyM*PTVBfOSJl?z2c3L4n_}eC%9>(jfk?Bk_2u zti_t6I@ZuqXE0r;bwT%ptG)Ju^}3y=n$9IO)CTN^ovJ%>8X(z6BORxp%thJVo?#Lp zc;Jc1$Jr8sj{TV<64J}d0dkJQ1Sgen2U57!6j^u;&V!i;ceH1l-g9Z&jI?8SwOw

D4ii5U)8pSQ%EF)}Pk=FpU6G*dMWV z=Tz*G&b=b4GdF4%cKUIfrQ7(}IxE#7w%{j`PN+0@1RaJxIeV8hTrzUUb#jmJzfG-7t}@^-6aQZRI272}=n)<#_!)zZXE zLXawGEbW%d%s>9BQHKP70+ORnL^8DQ#Oum|ZFtUJP@( zNeRWCRFIWIjt5bk2hfK(5aHX5seqNn7ztIOrdO*RMjR0~YOws8Jc3i&iMR~lN)$#~ zUq{(-?!rYiT#aHFKy<9OrNqa#a3?&sUB9VwW(wt9+POIYR2OlM+nKrUZmi5k;JO8R z;vYNgjt1KYw40sOQs_5OKZ zkz$d~O7atAQWbCIv*-NopX=e_Nj=$+-IDWqb%@UG-LsEe5Z$t>i1_SJJaW8c_0r#a zncLZ@CTeOEV{60i#75glbN;kG;(9iyyZ4AmGq+`7A8n8lc zIr+}(mVd|pS61t0B%~Vuk)TJcQ>tmbX`<)F80X%wx^RxmH(eKx!_!5(^50cH&OnB_@5 zDWDAg%J?o?`v9{GUW2?kE2{yattuS@Awrw$t#rEawo5?zHR|%7bWYA%| zI^=w$HHw#YZ{MnCAs(1b<&eg)A216Q#RC$4_HXv`9`$lOo!rOKUMHS6#kQ1=p&eyv zoR+ViI=I#Mf+y*%UBZ;IhC1Zawj$TE>I)lfGL$oB@8Q@z6jmbs8LD`F>2^o2*5OrL@YXt zoJ}oeI4-tu+{pAo!;TY*JC$qIZe_CS)1r-z1!BsVL!u+ZS^ipfnKP=GFKi0oeo|p; zpE?(v%Edz1U$;NG%cm?Y9nJ{)NcMD|JVzD1YhkRxmDL_BO}WX%&NLlPy>ACdGZscn zGbHY+JYgx3Y#Z?v4)YlQz22ZdjAnt6sCNP_g17HNckAeT2XYW!56})Ic~A>I_P?SD zF*w>mePV5o-0A#{cQI=1m8p%)1z6>V3o&<|4pvf90;t=Pnr9emWtOEFE-1bCN1eF@ z?=Du&t3=gk`lS(FkgZM=xEWwTl^r_$A_MF?ORChbm5IUYM{R)Ya)nluE@_dN5l$8_ zei7b72lIt$jnKIMFr7-#9)0v$C$M=7TA|aRzsg)QtteKNm0I0zHcF4(Eickhi~*d4 zAIT=06)vexoE(JVMnVP^|K<)Ew0l%gTaOk@Kx<*J$z+G|Vp$`L)Eh_1-10+EnBhO0 zzPmCbC@cbZL=+Zb9mug(?MP-90!e*nl5+c=hfk*6V1i@p zDdLd&!)2!Hdix>7-+<<#y2&eYFr{Y9z*!W|u_YtrqvD<%^*;i5sBbShtsc-Oko6#U zMf+?|&Xq|zWj+-fI?_M_zM>>gNjN=J)7IpBx`%P$fp&B+=w$7`~QBQ$l=hO$Mp%x>T@iP{KRJsDp_6xO$-)@NrXljrnLj5%h39>gW190b>FNR_#T zaMZfe@5dM#UwF-;Q7bO61riMc-$h+uQR^>$DzD^{R4#6m)e&=Iaw_;gpw>_pdgphS zh4Y#;xI?r1DI2mXG)Sdt&PAv`4<4vIkoTYI_&v~Z_ti(@RFOe}47&0+KkIl~#oF^-lwFaR=yPJf2yb323DD(SqFvY?VnG!hIG7Be0j+ZS*KY$(Lig2@pn zeB8h$l8lBnds~59HUy(1tG9)zs0s%ZZ`WZ@B!rr2Y@$jgifj}s1TKY0@G5VES&VI7 zDPTmwBoK{Zp6pYuphS=s)xX+EiY_QS&Io+intCC>ixO#7!qkD;-3uV0j0L-&=4ivT zX5m%BgHxpWYCSyV_7)~t{0LwEa28$s=G996NQ!5!A{V2G#XEIP```-_7lp&g`SCOC z!v~3;w6NQh2>F3F%PZWZ_WJrE0A!P-2zmV;;ReteD*$}O0v^fXX!Ba;0gNAh69)Q8 z9H8$*RPVTc4N%V==7JKJ6HdH7#&5l531oSOu|Clk`g9*$ zN4y+~j11P6elt!^&9W#>iX@hQ;1ulRlQQ&8thiIHnAtP&3_QKVsF>ELeC|;^{fq!_ zhMri#YPYF%cdXQ{S^WA}LjuOZDQy%S2*@1%pS1Hos)%JRot-W1%>P!;KkcFaPC9dv zbnO=yP($@wv=_`Mtzp21mkDfUujFP0n+OqQ98}pv<`6ram0Mt>v#BJ>2?t3&5in!| zi5&Y7w#5nM8c=P^=lP7r+_H~+%%9H2PSFdQ=oFGh(UwNcK=L3y-mE_3us zwy{#eh@o&b`pa%LsIm!OcUrOR4D^Ov*MB*HsRxmq!7|6{xbHu=zMLRG5lf>*u5osMeRny* zW+GmvQWtCeKl0#Ondo%z1+a`vZ!J5 z;p5v+`l{UNtYN4L>MAr9VktK@XwJc19-C6zrNRX6D`5t%1txc_$69v?t+iB^R@0%j z8AhdRQ4Y!KMVzt5O7=x9WY;-e&Ub6D!Xo29TB1-x9U?PF`~W;8VMO=!Xx2!{cFzCt zYTBtKCX%;-go&92Jyju!N9RZ!RAcY*u}|iez$WvDok^cc25Q9g=r6Hcf@tV^v2QQb2&uyp}1WE z-#-@+pnk{TQ(qXFHNGwC%;zaluEiJ-;OH7b@R;9Lqij2o*r1{n+hnHLLE}c27wKx1 zbz3Hc4uvvu3TwB6UlO(%z*EHo1oUE|{p*x}1#S{_3;}ed-jTD2RiF|{Mo+Z~0 zkf=Py*QvojtsJr%&SAu{3ag+Z46vB}WOg`(J5B4AMQ^q2)2j_)4LdDK?D1NG(BIP` zT+4k^@K}UrRZT0*^hR-Jumf}TAY=({F@l@mRBN4v9@FkG+&xh21E4?eox zqxL!956jJc!ChkX1A)_jM+mQoaU)&jb_w;?KOU`jRV1Yo7L-({CeZ*g!0XqP+`yd!BEbfI@d^uYDIB z`*RyEJxmd$f|LR~(4BBh_F_om-4W|(>`hkB7DwbkIrC_$Qd#m_Y+y0C3`-l7*sRg6 z(vK;8aw$dzLX@9W-!7_`mh2`xDFP4`@PZ?5jy0%|>rk+^9^hh8+j0{x6){1}#d&|6 zz{<*)U9d=1`=Wh|N{x)iQ0VA`YKLyR%7wQd{V7TTNpUVod(r(}$M?etUW!3ElqeZY zMQBRL_|3%}A)4NxqkHqs`M$P5_Yv2slnmICdb@7(&5@x_%&Oj-q9r0Me&>;rysH71BQ_P2Ojb&J#PF1OUvZ)q#bQjCKL zd}8A~7(Z<6W^beckqf^6K@B|hs`jyy`bY;h9BC{)p{6){$y~nfiOh z)i#TJgLeT5Lg!Ve=E|F}NsU0Ztd^j!&SOyCV_;XVr+$kQ`Ol1D4DqO8CVuM;7boqU zfn=i`j5AJV1Qw4udHkp6Pl<#0)l}**Dmvn%&_HS`B@K;UQkn{hxGo-HDu)p?Sm}dt z9&koo`JGe!Uu78WVu8=VX#rp3u;8#0&gH6ll^T69EH!&%!Z%ybNd=a!Au0}U{0Dz@ zptwG=g9PM>2a8{lpWYQblVwY>KJ=k(h!;&-1HKFSTamXaCUOUhN2m=)^U)tM-k08l z8p*N*yI;+9q+cZ#52U=uG2Tx|+&>V)B@RXsPdNv_kP2S_X;^f71Nj}}yl-_x;X@W) zAjT&7#o^l)KT$j?5Xh6S$tz5!kF&D`QROpa)$vNE-}&7wv>)-$Q`{rM{sLSMTCrQsr?K{h1uE$hMc4^Y;f~Ug3}oG%eXToN z@%-W9isy}9Oa?-EFSA8qu@fOa~?)OmKXQ_rnnu|D<}(J zOW%7eriLK8KwmSBU0R7k-S7#0A?JhCFwB}U=(8lH5atR2D>vzejsjSpXcuM=b>=bo z=0dJfrhop+CwxZ=x$*x)G?D*EH2nX`J*(PT|3_UmW!pbvA4I>@X4G*_ngdy|A(SRs z+c*jlP~$+7;X&|dRhfv0-uK7ss`9WN4pXDqJJlRn*TGldBq$z@?xb{as>w9{VAJmOeqrAnpNb3B3Jd|TRZ?TWh;V^;CN zsRZXilpF-$-3RM`KQotjE|^fLxhFXetYH{zWdVp$ar?wsv$@MwV@XV~QnD8383KOY zO(Mn34avuUlBZgO$pb_#{f9R}(@^rZNM73BO9NSIO5;Vu1fhk4BnT=6`ch`Gl^MSG z&1M-$WD$AveW+SCQ6|a)q8w(ZHhs+$&c-9qF7Nt^NN5v|Mn_=O;~LyYfM&L6d`ya&%j#p*xdK`+ z0sQWMb|)z83HTvLw=hNuE#B%nD><|6rrv(#}BqSLA@$D}W-T3LEZ1xA&t^a5({&^_>H+lV=Zu+WftD~r+ ze#Sz{h1W}6&ub*dTcLmus?`yBL?Kb5AyZMr7%dF!$4ASU?M{m1>uK4332arw`QDUR zKNP|>*OpY>(hxs@N`XJOFJ9 zX5m9PFaYtpNsPONHn05p?X8^BLAg<$dbOpYNqWn^m&516aK0r(26n|n@lcZwLTW@@ zD_mjCywX-O2#nL`?S~`A0)(Gw%8)}Mud5S^QjeWgZ@cl$HAM0Wx5AP`hxvTMD8TUQ zH2)Nrks?JRUpz9aIFroB!(VpqR~O}R349~29p_{5Ve*nAs}NDm-gB?~(;;Yt;vu{) zNK}D4E1T}_QfsR&S|}A;f=Q!aI00z6kdhyUDIy0{ z4~eo#ggCMy8+ksBBVjbUs3SHyGraXNmt$8WtwbNOZwaY4_`i>JsCJh4dBh*m=)&Ky z9L?2>UxJGxLRq=WwF5EG`@tB6r!)u%Vj`Dhy)^oMVVi5ZwW;K>Y0X~*B%9uVweRLh z7F-}rxl!!0su$0#Rklm_Q_NYG`#C6BY8jtxEm?EyiQ^R~8?g=ldQD)XBS{L?o(j(1 zV5mNB3S^=zQsiwlo(EgO(8e9VZpe|4QF&)@$RcdL=>l=8nQb8@&%3QH18O2rX)6j-cEU3plH* zQ7Y5Q!%Q^ghlr&K>C4dzIVA#j2s?EqmWayPy_$MVYE&dGGZYe96cA^L2Iw+K#YctYO(y?8HCKF$V`FV1)Aucfx;y>mJtx{f6RN6>0A2 z(93zu=3IHi?T&HBcW#@j!9a|n;0@CYVx51W zKE%Y^6UbI`2Yd?XhxW_4EME`pFO>MV`xg&3?-26N2)b!<~aKRsj($bi&F1q;#n#@hsh`Ba32QdPcJNk}xR^vG)I zM^YLaw}DIWzSZ1Uh|XpHS#2JOf>BN_`_AiUh|YU+j{?WdsZu!EX~i)^bEb@prwq@- zoR5bqd_PczXmVJ6USBT$M~+4!bGFu+;9=p6MFo~*Mki0zB-_PVV@}~66ZW=Y)2M|w z>jt!ms+-AB)ltoY8&%Dp9xTZ-!%j|orCgkJj-IX>WctokI6YdkEKD|z3x!oCnAkV~ z94shaOHku$T1+tJ0s9Ipb4V;Rwp>4K(&4MI(xDVe;O~q4*jDrzn1o=18pn3Qg>A59cfl7(0gdLt$#XwQVCmc?xQbXv?Y2s zt%0Jd8(5Cxb2 z>Mg`4pFIo;1`^grlY=VrwGi)(6Jud5z%#Gtq{s-S!=Hwx$IlE|*7kdrUR_gBhx0%V z|P2f<*Zi`^-RsG#jwfE zCRk#aATa283)auMq!0IVRq1D{bt|2Qcix|77=sO80ku1vs(GstClm@bI-JsQE)z@4 zF63Ih4XFU=(PUQhSYQQZ_A2keKqCe1_3FTmk!TT&(@#JPsG{qf0rBN5$M_46u0yDX z{{!VBL`RqcE3-tTvl&1`pZL&1!KTQkDK_bZ>~2qZGAbU7pN!$8=;k%NVC>?HqffI? zTNx(A8GD}S9#|C(4zI_G$mw@Ieos>WXFN0wZf|_K=C*$phM<2c%10OLajoPdG*h6B zl}&jdcp(e5wdpZ?GxIv`i0Y~SNjZV5bIhZpz5@Gse!n_YFw;u7D}F=aCz+-rwTXvD zQ87DpMa_Xfs&2iCREj1ttofTQx=Kn=1FMZk&2t_P$sO9Ym- zMsu9=S5jKWBxiy<9FjBi$7?gFs`9s*B-wKG_}jmbRu{&;xrlU&A0bUcf8d;Kpn1(8 zO~detybk%^lM{zwnmmIqOSJW0BM*pU%Ff_zZ}3JZ2~(*#QGDXXw&6uMUg2?dbk6zu z)ZKSJkGKaHz{j2Z{w9wE^$UqEA{F;jNTHwNhp5)@?v?cGQ^FllN<7(b61sTp>E&NQ z2xGsmkxCbsAzF82adz1TY<>-Syy!H-628#-?DTH<7N?d!_wp8q3>Fo8A@$vaCkHeA|SyseLWlcxbcWNHL@$E3;<1M@XWRWiyDC%PmVDB2J+|Jrp(+89DP`BSHA{v(Uh{8u0LUs&|-e$T&g zsqMcSd8pYz7FE?Lmue$+=*ek1yjdX#6&Wp*iHuc)*ZC8 zY%9A#%0;{^C$?qF@{P@Osi~|>qumgfod}w}DMt6h0iIFhFf)K6U1Oo(Mi%z29AsBi@ItSOp(C@SXm;_l+P zLHua5Y*KV+&=ArT%4JZ94;gtB!Vl__V`cs0{dG(_5t2md!1bH4qHoyTY&0C85B~4y zk2c9W92A8r{cIJWFV@cJ6{Yo))DePW6NtZyGql(@2%W%zn}!`?Hsq7TTC7#DuFAWB zGq}x9(Vcq!QaYQ(hiJh+UODL>mwf-NDQ9W-X93dA(1za3^3Srhf}x9rij$$6sgtvz zjj)BOv9+nwzg<;~>V`9lD(cq;`igC)kY;yDKQgLNCK~~&)QbXS{#>KMw_gTL>vndD zC0QG$?h8sth&|Uy>S260!=x4wW3@a>q_JNsL(U{g`)^X#7j+`>FJaj4i)ZckI#tM(60At#L`!%iKr$Ra)p!!+(~5si3?%yxX51 z2Wx&9z$RoXKfpSUH-ZYM?WHJ@#$nJTFkJ|Eu(c?ODwRxM=ld+}AqQ()W&~ZM(imIx z432n?@48XCdfg{7fPhg$vL;~z#$mHLc$19{Ffa@G=%JyQdZ|$@#ChIU=rKG>b-5bP zEayuNWOxj4#Y070Kr=AiG+>PTJeFF?-%WJ_)Q@9R2eVD9Ye+~P> zt}etvKQ0hU6UE2KaI11dX2nMoVnAp+0{OyD>}H5Dg%Kb3Az1}V>Lj9R#LHpQF;kbh z=nYEGf2`>IBEN^8SE1Vd`re8x;)qpQzu4Z6)Y$!hOV%`WmnNwdH!!c2T+>lBP3gHzNm zxq;V29dZbwwP&>Pjn1j3QQTFd+YaFH973$Y@dG1<#YQjl?6lGXw@h2Xfbio}NY057hi=aDPuEHD5#%7XV2owY8!Qg?A^l7+Dtt#;J8b znnPu?it}Zij}hu(+BgB5!|l4TY)d}dMwb>m&0Ay>3zH+{nbf{_LN_PZ5@Dwz&mR~m zBhPE2@$;v^Ik)`2!@Hej(e8MXw(&fIh-e=-Z1vzObM78AeR}k+Zljn3+VWwQaJMOL z&_sQgU<|K#rSt^dlHw)%jUUYB07Nh*ho-rZhvn)_T-vJ88R?HlB)(LZR#8p)bho~Y zYgHd99l3@6QeQzChT+#X@6@>Ql1?h?Rik_@0Gb{}K}iP=^hY#0IrSH z`~_<$zT-Bq9P_Vu>~?kkxs_5<^er|a8C)aH%K zugqsJaEv=<%qjP1ixA6jtVt|7S>tG@+Th5Y!SKUiEPDxps@h*RpfE_+q#w3~-kFeE zE3%F6nT!&#Ek87S48ZUbbdo1t)~5|$mD5S$>1Y!>*wnzD#gTQVD}1vRFi;ZIJ< zmW}h_snQZ6b|iZF?&sZT`R-(KfVonB(IP~^+|88vNKe1`nfo+Z{Cxk)ShoFB_SVze zrTN=h4}w2P9fm%`db^)*@sSltkyXLX1dU9BN>m%#}Hh!%dWVoYYr} z>fREIK1J?FY35Ng2*SWBl&h31CKaK)Ia%u=g~m|bX};a*G-2ql#Yh{FkH$q92*0qk zV9waJ-vHIkPtzRkVc3CT3#r6oH6grmK+uz0Ht}_XEtoZCXQl_70j(N)0a!KcSuUsG z19ow=PcWNdSLGYAc;|^M=>@;W7Ix{2zwQJxP@=y<~IyE z6GIym6C@;!dI{M<#5g(#y5;IjqR8bsVGZw`z6D#0Bt8*KoaQaW&*O6E6%mm~(7c?$q2$cqFrN__WklD|_h2C8;-5 zDj-s@w;!A=S(Who6>BQE6HA<`o+Ryw2QWXrOlzLN?4Gt|`QZuLikHRBrQqo)I3#{E zt1e(Ii2g2LgZRb~-16Z86V`?3Pb&`39{BOXJg}7Zm>p;gYul6@S8ldM)w*}sycU5K za4nCmE}Mi+3J~mhE8Hd-I7}g=#4-aDhJ|}m!@nKNx2*>Daby zyOR!Ye*1jqj{EI<&K_f}QR5x&TK`nlQ&rD==A2bYBr$9z6+%tc-rTqgQ1^gBo6>eq zUuKxA^PvvKr=@$LlfFQ6g+(u7RBeE>7N7O{zH;?T)zCo;Fmm{i@}AzKMlY%sm{fLN z*xFZDxlMz+S_j}Z_Au%b_c9J`T)ag4kVcI<85#b~en7zzy1^ z5VZyGR;68Nz?q;VNncl6^nZy{mQZOQ4IdAMYZ(TMx>{Eb7sxGJDD;)2WltgrkD-wB zHM8mxbS~V}X~YeJNtkhdA$^aiENpS4{ock;L`#_TB&=#N25y3SJ!Y z@hObNytE?t@qB;$EP;y1Ktib@ZSF=}ylmqQVrcTN_K6dUw7L83)(jm(ShA#)EC06= zW`etrWSAjo$xOw7ZrgBp#tBmr`n`OrpfIRCD{ze)QSU;i937!~*m}>&z)&@LN_T2c zHw40t)*Uy^V+?B7soi<-7w78%`xi~Ku&YJU=dgy%zVc*1rZ+JoDWiEV&z>w09Ib?I zKP;p8JYNQJ%kpTlG->!C2IR$dJxecHyyvfb`5`+|FmoT zn-J2?6=2Kw|85k2%U_OXW#1w96$MObH6=a*LH)hgc4%c=y!Q{zB_x0DG#?LLVJWP+P1P+Wwv#e z(l%S*)MsbxlC`u>rGQW#rmI9$nCjs(qPc`RN@~o)cCu#^#vUg7%DI@>9?Q6=i8O1x zRs}SdpObM-SA&R?3;V2JHRp8nYjzsJefT$8RlFsXx`dSjVuvK@$&2niXO|vYEmk&I z(D?o5RPMa&-E{f-;dP59P&VLt8^^rJYiNh8Ivoz^H0_|-;Rx1?S(!sr?$7+!=VE64 z;Akb2gGv!FT2q)BC`2dyCuc4c!j48%?n{8FsBkq>*o-mD?x7hj)Nh4zr7u* zM;NEr$>SaUVIC)2`2*I!qZ-O6o84#`9Y%A8B&eo+VN>CryJM0O;sysCyl*c=DLW_G z+*HQ{)ryDrXEWNjg`xzEsiEh{u1xF*Y%Oy#N$#QQ-1$LFztn-p!ZkH#urMl_my2U% zlE_w9QXuYgC;H-w_M6ygD$lcS0B6L8sW?TmFpa#cQ2sfVpR8tq>b));fOnLOz zr?3cfrzQgAr02IzXT-a!#Uh*9pus`MMaF0gDkJojp+&i7)Sq+!AT2vkun(PwOx^4c z7s5`FjK6NY@Ftzb@lMhogH93jv%RRnY6(UJO%5tYP?6%NQ1EIxRinnCpWozn2pkYDhY{tmd!){O^D%$!QMd8{(+;R z1(eq)d~yCbe?kLLx8}4uSNWCBo*Owcue4NE{qNa5(!HzaaOY{FbjA@wxx86{ZChHH z+>7c>Fb+Gv2+M9Lg82wDUW;G;SuNH**GQ=^}OGtnIie<$n z^`}y@ROWpN25)~Ad-tXrCtF}^t`|GZwL1`5n&q;(iS~->V~ss~OIg>dL)V4dKPfcU zOHjEdjc#0kd(%tIPG!cYx!r-L8ua0u=1BvlrWMp5#0PR8Z{9A?tS~ag z6UKCnQf8Z|wpI!6$&s6AKW!Nd>4@~}UB6icLZ)XJapilNS~3)MpF5XN!>F%O_3-S3*Cn&jFWH~QZLoL~)d(=s?LZrMR_5g(>nIdgDZx)ZUE z-k<<=N&}%6T~Kdqr2Oe?s}^X67YL2<(+4yS$?L+JM~1V2z~?(- z_$3WEc^E3V__6twZ5qh+pnh`O_SkB2zC7O_N5A;+tTRMxpx1-#$S-2%3PZY{oW9P} zg~U18VUoGF@J$JOJ5{bg5Efs>JmETQynHwm9I|$P@GS;cP2l#AECrD4R8js4-tw%W zQkk*-WFXj~*=Sb6A#Zt}gj~5Ow91xf9@6HJ5%eia7;P$IesR$q8cPylf_(T;Dbq)| zXxg_%f|_9{R3J8+acFS)cTX|jH=#B4kU9At6thjmbDpyuJ@6BvQLve~6ShBd($k@Q z{endjJ5d55l1A}!*ZkR^&^F)M;<6Pwtz3)yaI{GNN(4rqV}Aa)|Mifg*5?PUqfwh;`fAn^Qam zHTHB%k6J?RfhgNNhW@+A1i4crR=8u7yEL4LALD^zn&<$nJH!76cHepG4)rzuAIlRz z4{4<%`5;)l^cjwctIvW`%qAG+e5TVEs%@xMU4=tE1^?xMe-fAAsd8uBF9Nm;?0?#V z1pe>D<$v6Q!~iZ|V#GehIM>wRORak`kHc3R%{`&dQQEd^M7kFQi}(sbY;7x#xbMgGdh-gtFBj zYHFd=)I>HnufXf!dU*V|Ql{yfqsQ~ZJ=vn(tm%+>78!{~J2@=*mSb%W&D8S)AA4CO zhEV!eMyl0A|KF?Vla~H7_pvHj>%Y^PIu(8ocXcivb1{1QM5$KOeVjQ!Hp}<85c`>s z=W}uMdjZxwQ@)u>Eo}&K40e7|D++0OL*owUb?H|u>8jI?t>9HP+y%9WP)>=2}lD~zroG*xt( zwdR-sPm2+or+TI{oM~24D09d^@ycsx>BZ?@S=S#!br&(4}NqCc`Ozq~K>h7r@J-x#F+>F*tQ-M3^t1rrR;QC;+Q|KiTl zld$dGt>E%7`%wg|2!ao8#TchUOOx9)P zzhbD)=|lW_!{&OI!zdOnP8f&&RYnzr*!D@8Xb`_i%8ai)vg62X-Y1B<5R7gh{|POI zE-UV%FJ8ywf8=#A{@JHyoBDv3*U7Oqt1J@L3dtSnsFPzJxKx{dfQ5i6(V5 zN7Znir)<@5UB&5u&+jV(z@E#=N#*k~K~k?8U|jd*c+K{WIgaI8!aM+F03gZikfNMS zOYnyZ(M)ml-WTck!#z!|2FD)*oY_2(fn^EJjWe>T`SI!+A;x%5WHnng!-~Bn6Ib`c z4O%3BLjh9bC#YSr5Py?0mi8GIx`ECZi+O(+n_JudxWkdj?IbIuD3Rf|e1CyX%zdXRDT;#LU->$L>+(j7d^=5Zfp>{&T190pNJCWSljaBbJ} zb82@O*Ur)n<#It048u?sA`AlBVE|%sasEr<2|aIU-KE1f0p-ceoq7av-*hcPo8Iq> z-Kd3xwR*f*5T(pO$uwoiF)(8H_ieO=rpO3S-)~@mUr8w`-5Ynh!8d)@W~zzt5fdNeSLt> z-Fy5ujQX*g!7d-%rs*nr`)jCf(`qgE<;=#5d_hNkg0?`zQ%HPae`>y7QQ#OaRn`HAA;>z{&>6&k+9?xyr#b;e_>^pjzx{& zBxoZ_=xaK1jmjbCDtLe%e9D_izD!6B-t;T?T|Ydg^ilN*d}du9 z(K_sr!UIgf;7=vts)XP5oc%bx({^od(cx1#uvG@wWz5`~>DjA0Y z#&ferTaLE-Jj-*x!taWZ)?R$>5g-2;`$7L|(4^FSo>X^lUhBEJoRHp;UHG0}Q7O?&4PLEINIa^tR;a652@`7wH3U}; z_ndH}X;8@Ti6<3Hp&M#5;(g>Yn)C@1nZtmdw(D-FM;r{c50L6-cLh&Ewzf{oeGL~UxQCrN5GmSmlqglj%&52)kY>j*{B~-FWBP{w*HGb(8g`<7G9S`ZMj%spv3$krv^84{bFgu~j z70;21E*#kzaUQAHFF~T~O5+80tva71^$Gnb&x${;n6Ow-GG7!hW3bRl%65T`;}SNr zKDtw3=1}op7C5!0_$Gp1Y+>-Py!(GgYT5qhRr$ZelX?a9##&!G@`ZkBVQl!?BQkhHStesG(d!}{#0To)^NWa5C}UeUDm zFEQyD#mwiT1y*o5U8x7-E9WVXrPrLlf6vD?za2A=-*}sor+HN{I^JhE!n~y0V?2h~ zx2JrGqqm)N%m(S9fU?H0SI{b{ZE0-deZEJFG`RvA2hEfy-c89>H`a63&s_ALw|taU z6SixZHqG)u;>7%SGC^|IWN!9i0qEaNm5w(v*#_muG2o~*Q|HJ>VVk8Gr46cKGJan% za5s;`in`4C)$?iJkN4fuC%x9F&GgniQ5zlrB%e4YyA&V)RrWH^PZQyXY#}QA&pzF6^AXg^%ot!#u(EblKava>xB>& z{1uDm*!hXz5L@BHApw+YCH9?b0a$gIOmJW!wUA9G4HW<;8C(p3^~)kQXdjMWxWD+k zqtu4=VvDW0O;u+471#+37KW>saSAdv?D(TI*#H}4@RSS#s_fnMgIpny7+~wxwD=mv z4<2dC<(NnWQ~L9J6M?6QM1o1g^A(R)|0xkFs3le*{V!$5I4j{MCETq2EnQCpv%MzpH0uTOJ`BE{V3!zQOrXwnpEr99$3!Yks^42eno_nF7XDc z>{`=nNId^&6F$S?dY<}6(w8NpgYdj65)H`)L3vqxOF>f9KF*j!%WhM)Erj+3h|G_` znvcj+cD+f}h;!(^O>a!Y!ApFR>*HJy(~dQG93dh>#nO+HCsE!lR> zwmHLg?!taf8g$p<&()RL@ggs)*Dp3Dq7mItmEt=zc5vkN%nAE;sUVr4h$!_)Ey4&G z8j=WgVbF7rtDMywKQ^Kxr_ayq&(Gd@*K|=md?QbpP(=Y^rZr0mJl3DRuk<7fT z3wU-4aGWiilntkPEavFIRXIr>UNh9|73%e|bv?YMJN!sxUglKB()-C-W7?FK^(+@s zd;sloqAQ@PrFwUr{>qI*a|#htm6{}ORUua`a%H2f-lc!&Xjm?SXeN)I2iixH#T-_{ zJSVXRc^F4#ReuJx0ATJXDhvas&Ve1n3}^yHK148LZTIK=gwadt^w%MKpK}bJq-LC zl%u@o!6??*H@xO^XsN%G{&6Ei;SY2?=COy%fEw@+dq89g!0hnBU2NFKn>URcM2o2~O+ zPQC4hny9Rd6nf!}AGn}eu~}fTti0|zf0gfSjbe?Q#@pY8>G~(Xvzb;CvH9rs@&Fs) zJ4KAvGJ;$hwo8p-8?Q*CFq@3@zqJ&mY)tB~%uF?o23=}}(#hBRF0F2{>@+)O z*rx2nZs$hxqxA^m!4wj}d!O3`K^a#}8I12>)1x`(#B88aLf$u0}@;!!l zlKu)J%zrt1U%RxVQ=jTQ4!TCpW=kV&r{57|B(T@^pxW4HM!KCQM}WDtwuQtE91X0} z7<3rCNljajRyb3^O@;pw>}&Tm!F0E{4<#}<-X*wq^l6O4#OxC8BygBX86KzAFlLM3 z^y=8Y_+WuQ5Qw4zxIKj*&qGM&_e5KZntr7|MnoSM`^YHk^skQ?~~ zqf<-2)l;6tU!&bPvGNMyiI`gq6FxR|v=pSB`jBtdEE|1^Q4QW}9TQkK#=Y%aZe2^l zsWvBjsD(s05DxMz?wg)L&CikSdME6Q=0S628r1aO+%H4ubRjZ3s`NVt6x0X$&}9`a zRIZLZLPE}$FM=cv94on-zO zW~f=K#y|G3B6E7Rvb$!`tmgS=(>B!3yk}UGkww#snb)$*cVC!pZeAo4h$-g0ItYtq zOIGY7h!$EcZpp9=b{W>V$Zs-SiuP3n1wT(*<7;$h^zKio6qBA~Xs%nd5>PZ~l+A`M zY+%+n_8>;V;ZXz`SU9Pg`^B@KFVFZ`qRRuf$*GSL{r>ce^BPjWQi8X9h$)xy>GvIe z6NqP2;z6OA&%ILdrSED#jehpqd?5ch)isGja}BkJ*i|C&$0J6taSWtwm#A*I z9q~8xV4;4Fen(w-=wmyE`NG>z2*Y{Q0NE_DutuC?=Gc&KR98CJVRq{GV3n7l>?ByU z>c5nq%8DOJ{@x(ZKko>2h{~{@Ip&9dp}#cxlB&sRmvmmwM6rpdlvYgs3{h_C8UKXe zR(<{81@#+vMAUc`nV5>Pf`3M2-#Na`3lc|k!+jRO4;wC54;UBS)ZzNT{Y33S*UMQ< zPc+u$eIsOcB9DqIrAK6MVZ5u;4Z83o|3R%i06OZ+sO^|-Qe%V&K3K+WEA!@mk_Yi) zsP=$ zq)HV4M>1UPOUB(VUq(&*oseN%i}SB5^cc)z3%oNwG=<7)Cw_9unyg`>x{OT`x9_00U;TQ;~3+aXt&l6APj)LnBz zh7h~KeI49pMW!x*8vxaD*Zu$}a#M1KJ9g}8!p8e+eyk33yf)Un(R6U53HGfj7?jfG zk7CP-zSm{r`BANXi%NxmJ5nsChuE}>ZawSmIVF0P`6-1Rm-!vHtMjIs==r^$qFGNY zG};IhrCFdyzVQDPN)wAVh%FAtS^Jx)cb$`Fn)+?jrjjzwP1ZUJA2#rI$(!;K7oAXJII?0lbb=RjUx$~^bceAgZF&ZWOQabj5cUraJ zaioSvS0k7#lHE&ube6HckoUuO8@jR=F7nGy?A0+Z6i69jE_`Q%!}R38a)xQaXEPlq zy_n{Gzisk#NID{~@7o z*=}!VpK@4PUYlK8;)&}zuDiyAm@@w4=HrSCzHN5ue8EG=3tmj7GCp9bfql&aX6uW* zlMQ)#;$=Xi<&rN)ALP6dh)tr||4=rq^Tb&>`LN-rgMKD%hqEO$iQ@U0)6$y-x-IDl zqgx^O-cN2cwn%-T|3=qqa;D`77ky(eW%H=Le~NfbYUbE!i9)$oeJdI+yloPP;ebq?rTXX7xkapu^ zX`FHcdG$1&*AGi5r1&b{snnM@cx^p^DG-&(y22G%J4AVF;=8yT=k(?VZRqgwit-z~ zhI%(o_IZix<4}aoR?N@x=J4+Mf{h3jichQ{w1V=gHhhZ}~vsXYfjr^B9?-wfaW`lq3MK2iVr zMP7f%KTqI)&SAb9^gsFkG#)qnUw_+8GfRX$mrA$0cMjcD-hDJ_b8b(h*_R zlPic31J#5}hGXf6(%Wb7B=!Q2Dt7ohN3&FazH_hf_3$1fYHXCIcfo{v6Y`z+By>yx z|79FC%aTWg2!6Dwc%ZW2Db*MCM@t8;2uBvjJZ^`l58xDtD zL`j}T#wN|7UcAC0iI!P>3?}^_1Xz3?B>NGs|OLNp5Cb!l2M0`bL1v@#0p9NlA z-{AdLq!#zXC-zEs(kmuu19+?~dq5;M1NqRdX}5>O<_lWn{eroVCl;1@82X>+82#DE zY6bLA&Z)(C*=*fU)$0?;(wV2mZparx&D30iv4KU(hBmmtP}^|QV;yX4i9+r0NwH((>I z#b@4ue}8F7d?EEU#lwePmcwO>LjP{;6a1e70+Nyb(cYIaQVZUHf~x5M=ge91U$)um zU*@(_4tC~p4h}YMj{lZL$ExTnE(oFV_k&#e=eHK-KZ~ntp|rCj1L09nlfem6joh_S z^EgC#*XemL+2%1sW5_j3ua_}I?wjG%K7`}{a*81rIwkehxeL& zXFWn2FIu8ywXXfPPQ4!bP~ZU|pM+N}H@_7_%l=gC zXkbGyEW*p%wk{vCrCwk~%|2lQx(_!m`IgQLl>FTo;7PWz&_mY0q2c1wxXyEO`HQnf zXVRc$-uB7;>FX+z#U%$Z%0=M=L1QLPJ!~=Im*fH^UH?(0SC837x`f;r2pYH~TrWHD zG$jUOm^ADtZ0SlwsjNuafbz3!vI;18J#(s862AiU$)sE+x+Ml0?cZ2GcW`Rbn1Z#f z`E(=>m{&eS-zzex?01f&PWa@{7N#|A_BgyMco@yoE8ZLb>Tlo@W704w)0u!gVGrfa zXU$zv8qElr3@Eg1uqcaUT!kOd8^_QYeZZC)_zk!=y+FHIwyJlD4r5m#dfpI>7=!Z+ zD?R_qo=8LngK7Ay7?JTGixL0EB>L}S#D7hd|HCBur`|*+Z2CV~shgrsE zt|d*^c`B{Bg6l$cdCexFp*`?z%FWqvu9|aJ1Zmwg@jZVNNag}KA@sj(Pkgcpb{lSg zV+t+!F}-=k9FQivfNKrIoz|XgTA_a#JGj(JQK>IH0jk|6)v0GZ@euVu;qI1vk78F` z|Ddi>G(91(pIMhpvK{ueZRozlvZ4}^Jw}u_LBYxTm-!p9(epuj{^^t!3X^kzih55U z&>Q}QAKa}wjS=$kM`>H@;=2zu9xRvPK1Rx5sY>)=rfXJT#gF7IDGz!`iZsn>I0d56 z-(b2Bj!TLOj)Fl4|1#<|#wBn+{&J{C{f`m~n*S7e|DW#sx3HVk_VHCc{QD^&otcyi zK}C%Y0#cynBVQR2A-o_0t2Wn1r36ZqO;Kh?Hd-+Xt#o~o&C}AB<&tB6-%y>ERsjbz zDJyrG$YVM7pK6PCdCFSf7}R%FZ9nFx1SE0LKfj(2m;E~KyuRnVcIoasZrhLN|87)K zl3e$hX~RL^-B2hCeWhVq0Ana#*HQSJq+I;94_O@1hS@<4wxW|jlk_K0$*WOQ+B3Mz z+R=jqTVCzCJw-~Sy7uJ!Rw6~fVI|)w?58WEIu^%ozUb|o7%@-dcpOD0bpx#}NB4eh zOHIAYZ^#D-^w@|$ZTgT?lqv>&aD4V;s0ul*Vrl*StUH~mZ`T07o2Ylw!Eg&6Sj^++ zu#`>sV{zLVRD;{WczZDp{radE*WXQF@xA%*&b5^rQ<%OO(QabWWMm^D4Fu}jSj(;y zeQ)eG6tPifI7t#B@D%&TUENN66EKw7=@dm^^U$!RVJSU0c|(xZ7CGrCs0ulb11k)u z9tCnkauXyI8E`Uv)FCJo=gUE1lUmH$h0N*>8x5n=AxAy*rW{8o*=@Wi3gl>~YpL?p zs53g)cHc3^(h(H}bSgt&M40nddux!)nJvtfU79Y%$Q6?6vC10N+gDo=)Q+_$Lz0wa z>nhVIS5u%47e8(-^pzVYBfUM%7YYLH%$-q|aKI;rVxzXkCHR7k%)?d!e%^))(AKAy`iT6j87kUMKZAzx zd#Wek-_+Si+MRSsM0s)@ZYrl7nVlc}JE3|gR2EY$;^zJx6&ATOl+Q5;h4r{mpxL;C zs6N=J!rF0X&Izr-Jrmf+AS_JGQ)HV^b8hb&=ycrq6l@F~vf4Y`ZeimX;^H|U0&Zbv7K#OlgNdq{E zwy6^0ucE-)!E$Lx6Guy|--q_sHxSxNn*A328`4Ky>zY(82M<{^n-(ldGjnwTP13Ug zRdZjj-UYrlX+N`9D*fJ^?dO1qzdM426x48=g3{Oh8G<#(Od2G}cGsyZSLw~1&Al@; zl%#tD_x>AN6HJ6VEd-GEN3KS|M~aN77R_j9omZlB*>l#UYi@AZ_yA}BiFqwd!oF~D zPQnb}D?D~|Kyr2dfDcd^!`~%I}g* zQ!^9)84j0oHg9IJTr+(ou!HMM?+Enfnma+HY%TYXt1A>;L?sw>nO)+DhrS+d73(h3 z2}y5PjQk_M;2qz>y~fzAA@TY|l~}CPPwd2*hoXYo>&aC_s!6QbiunX>(49b!3;`*B z+d4OW`YuZ%gc?NH2k^p~il0$#&e%!2MaK?q4JZ_V$AmhxQtu0{>S2aCPZnd0rrWLD zU`qcob2#JFHn+Sz7Hy{X^W7lzRO1>8gbwl4?Gwi6QIZk~v1VwgY?2b2q*z9qV?i*E z*r{QFGnMEuWg!@1&OmY0X&U3!0HGxJ`xH`j4W4h(W7CLS(0P2x4 zdF*YzfR<-IK)}bIKpcAe=wg`OuA^O%GYSRr&Ev)d+Mvgy4G@Vv{&!M-Xgk{zdK=Y| zv9Vhs<%1zbG3p$bg}|UrjrCUZ1{8bvMw9`=pcYi{$izuRII}%tQ%(VRgNpo(vhqG} z%oASF6uWEdGOebwcq-8FMpkXM%|VvymbO+#i^p0b?ea{B-E!WYKrpC|}i9=wX!eMSn_e@ml|g(%ZiVkdsC!PB}*h$>?*^ ztha?b)8->neU7Iy>Xef#$#RF;w4~NmlGp4e4U5u^0EF|X4PPLJ%`yx6n)H20_Haaa zx=OHu1~ol11|YEfYS^kks(fPKi?V11I*?5xry>ZIhMpqZ-Ectd_3d=c%={-4)2;ZGo zWCD*#4J7|%fOL1P*c=9j(iHtM)~dtgO-^Zd;Gf2Uq{ugaw~}1mpS^{GM_BZJ{461g z=0Ry!P(64NnWM+jXnb7!Bcd%FkToJ6nQE2CWeX{Zy*Nvror1DU%k|sc8SA#M2AW$y zGLzvuvRTP-GQeKIJ2@gzZzv35FV`h^^k=wiIb~+di7|p%{OS=KSGi=VJ#z=$git6O z`z~^@PHltaBUQaWYBI4GTSca8`bJ-v_OSb{&Ds^24NV_)MVq<&JjUlyjtwU}`>U?I z{i)UJFPF`*W(>-~*4Sbyz)^{m#{E7V&!Ch@nyOxU#G)ZjZhJ8BLPSm@_R?w205!o9 z(?>7X+DEHbGkq!nU*6f5tNR#teHXO0)CMfa=H5Awsm1<5;+J9Rd1z5Ptkp>E<3q%X zS9dwzx}4$X4>`^``H&|!4m)cHJHvCpWu#L8<{elPbWWL}Y9+z$_17m?>gXuqcu&it zm6F=1zaH9AAU@cB*FT-y=1j&4ncyI{5~h7I9p_XuJAgzdK1m>mJt%a2plM1#!SW)P z5EZ&RQb3`cib(vZJ%6wjAIU8gGF3bD7x`?NS-Ys&{m&pTt4?S6P`D9S-rI6h&O=hP z&btw&dY&TC!HHK_Ouy#zSudze&2JSM!-El}A!O|xb+DL)G_zfJ7kuN_i+dfM;YB|w z8aSMCUP1io)31scvAG>oTxzY@4__MOo@O*<>JyoG3&lD_WXwO_70EHf)?rX^%5Kp^ z?IS4!yJs|PG|*{bur1i!9NgxD9};3nUe4fn`6oV@+#R`^CD*GtUf`A2)bvj^f+qC3 z#p0dWB!@AehMkMJgNL!YbVleXBV|~1(aIH*h@+@qKAQmq-0b#~1DlI7WOK+E?>K(3 z2xG245b9-ALUun5DSYCef^n@zz-NqeXIWlz>k0ZuueA8p%gBEY{R~VbZH2nwvN;w` zE<^2W18;adPz~@03CPYxlAlHH+Yk{MM&Y3~C@j0X2A9Y}RR9!D#=2w6k8)Bp6Qc5E zir!|i@QX@9rzxN}Q`YrHrjO!1R()xsTf&@~YMh1bIj+Q}a>mT>RM(!zZM}2jpn=;M zr@R}7`PYthp%)zYFz-UyFZ~yX4o69$PECiFq0r}VT6#}jEO|_C3f}U* zM_O`%hY*$<=2{s0$9mclSrgg#PP@Q!d2Zc_amG_kmiHk4OR)jpm+Ay_pAXGc={ot! zcY{*R)5lH@ ze!Aaqndot3VJA55Lhr4TCCIYWxJT30$|0DqUC%jTld}Oi6OKfsG4}9GN|&9u$ z5=0yP>ISXrM=_#9hj$B&#AM4Aq6g;5x~z@cbTn*6rADOmC60@|9}L*n>CKx?+sXl| z3aIEX(d#KS#j_TX56e4sBO8s8*Pgci2w6M!1fU$zaq+rz%;L?IMf%o!jVe4C=3&Lq z1eei7!f%a*SO_1A7?j;zebX8rxNhhrOr)WAXh$V=R6B|VW9msF``@h3!yNw@-?$zT zhE%#>$p<#Kqh-!(Xf=_XX=ZlQT~kTM;W^5gs-?xg(~ z={HvhWZ11zk0tI<|MzQQU;5B~fG>Y6X}>4U4((mL9e~dTYZ}?tz2%*W%LQTP{)*)G z&95&>ZjG|!rs#Y7Hhr4`dkl*URxNXl(EHz=5oUu=bC_=IA6c_x9Ea!jk?NlkFkkKw z@Ns-2ub*sxa0mQP$Iw2yQ5#-Yg*_RtB(iAp~IG&fSyTs zBsx-f+)lC3uyp8#1&$)-%QIr}|#7Zn3PfioGXY zOfhL($c3ggbd=VGWeYTO$xasHI2*X30qu}DDpwxRJMgdest97xf4yamZ4EM zndCSj)UG(K77KwgPe$H7cUA^)w1M~JiBZYej=Sn z#hr+Knqc2wLE4H5%=n1Odq*JvI?DCI_V8*^6xi?1{X|ZVToCB1m{LYc?FI8B|HSWI z0}%=s1&MX6q05bdh18w}?Ih7obg(Ll_ z!wPMqEA+1j`7bXp+)x2CWd;hO84Dw1(A1l`j&f#BhGJv}N$#jpT<}VXQEtg(jQ!Pe zHb|vu_Ap+dkFN9<9HV{|hT2M_VVU4k?Ji|CHRbywg_7XQ$%hWLSl6bnET@T(lOl$Qy({elPebpw{qBr`HZf!rvd83w< zA1c8*wU(Lg4;Wp1jCCAk054?O>eTRQbF{Mgyt3VTIL>-gd6RxT&$``2E!~h+BMvaw z>sKS5WccZ+(4~U=q9w?=c&f~NOJ@_nJC2`2oUsa17{jWPz6g_h2oAB>7lZhC`)bRGhIldz~r2=o^{1pp7YK9-$EaWX;u4W6b=7_IuPN;UL?$(XT4Ghq=xG|)Rn5&xu zeSqS>G5iN-?&-;Ui$(eN?U~{~;mjoeGukEn-<-&QL%G;v7EGmfFbLGK{HF%8!!5@4tJmAs)wjB!$RBy=j zf!>Px)GigY*s^vy>r4bV^W@dk)Q*yJC)6Rj50P8It=Hd=EVT*zgL6yL(HwveL5z?^ z7|~_(TE9hBNJp~cew%Nrd^wD&UKu}-nBF(m8lKvI>4RlNF}H z=3u1X8}SL0ncbUSXxxhtkzzQ>V@WM0>f7 z$IpTDj&Ec#C3_iiCY&az7`!6eBHJ*OSo9r{o)Zc16{KuK5)+ zy^6)_cdG8~J}%LwX~_*$K7_7ld&B39Q0Y6r*gP`izZTOl5)=kk+hr0xB{26BldyDN}JviUAHlzl=(ukp@k37|4eXe zqJ>{tUr_GUe}r?1{+9{)AqY4+9k%{zV2D8zZaw2 zCJ-j=ue0^JJNUOYQ6n=er1&%z@vrNca_b6HGk!6xnp0G+byWSS9(DC_b}yfgp{O2P z<=6e$KAHP7qR=VR+&vdyVrSxHA7IIYGuXpHn+T>3M^|H@Pm^qkx#lSR zfn%F#acLD_nv`gF#^H8(sll>pH6%Bt|2|wMNL*2L=c=CRdP1YYdprY@XksM?jmE}ocqW>$%RFkwVt6DxFxeo{m*K-BN z!`+Rv00iz-5`D9FNeN?<94J}k19QZ9d^E*?6=KEo^kJ<61d7bn^ma;X@dGvo>E!VJ z%`-72_4Kl1Fk4$3d2OriZRv~yr{iTM^R`ecYk{muXCIhdi^bsG5yV*4<90V-wA6!D9jNoRK7*h{5L%;EcK&21y&X)4BK(bZy0lw+V^xjak& zt3!#J53>N*cE|c3fWC6>oGCLJYzqA}sq{0s9P6%MQfQiJ(lrreJ=%P;=S7VdUuK%Z zji3TMjCNR;^0Ehemh&pBh_bkXK&PB3(>c=76lY#S`XVoJHOcXe(m0Hn23N8*;xWTW zQw>@_Fy1>foNR}gGiAI3*K)bqE!oNw-xD!cEYL>v&{P7>WPVI%n|ul4*#R{{!4>2d zV6PS*x^4WhiUk=4n`zh1aH`yZj0U9U)rs)%8C2h~@!a(gVdMo&In=N2qbhE5iXS8{ipv$_vdHxd4T)*-8Ji&F)ZdFi80ys(qF8bg%XGMhzowF!kZ>e>qD}7x%R9L zpU^PsOKTn@5Vi@GDKY_Y(@r0x(|IL+fY!{#jt}eziZ6Se;=HhdC0v~{sU{S~RlImR z0jFo+Npf&q%u>uaUCH;>Cpo^qP6sOZu;u>peejBOUY@}eDiejqr2HP1_V*$6huT20}kkr1qHK)N-VpvbzM^&Asmm1JGES`noIx@?~_h(eYOp zLYbo5#*=;pD}KfLB_6$=mc)qA?wKQtwpU%Dls>*F^8>AcQ?(UNAZjkQomPR(6(hY)iNq0&~H%N%mA>C|J z!hd`2y`OPCNAEuw3k)3i1*oO}g1c#96bNY8@li3|SQFcTWPfIPqxThf#_1oht6o1)`tz!9Z3W z*B8!GNutS9lM=Cih>=@wy^*62k{MBvg_Bf~iN9=wje^H%Mk$)cRdUU!zN&*?o#=m5 zB0}2pz;uW$*M{A4d~)#Fl>u|NF%CmV+jaM9%0C$ROqxG^T0j7<>m`(C4z%bIroc`~^}J2u;VjA8YZ4!&@-L+RA^~2R9mn}%t{);l z0bz|u3EwbG^|;EuHR5;O3n8BpI(XeeGi6GhAVk+y5V0V1Ic0io=ubaffJ8c z8CCeEBAAWO=^pZ4{QVc#UJ)-j*Uyg4yn8kMp4~dQ4Xq-WgC{OSLsMgr_c(}h_q#k!MhChDj0 z1BO>fHx$z|;p2m`rc1s&m4uF8D(chhQah$K{LyDi{4)c{z^&ePhNX|R z!u3p?)+4xtk$Re$+)n{G#AEGJtJ{ZIanUIMQ2~(D(&=@Pp2w zhR98d>wBgVNj#HLBb%%{7zXEkungTwQ(v-RawhU=y(1iek$*(TLl2s5%NjhWPLm#g)VdDK%2MV{rfgc4`X&B8Y>CXu5pNZ2(K zBL+mNWn^`llU|SZAgnyRX5_m&Mrf4C-=1pu+LPF9h1A(^v3BeHYJ^~dp z!6&a;w2+hYN5!8^ipF2RaC>%|A|AZ^X)1o65x?TVx$?vrSCfpUVBKwOWPd-S?v?sN z_iGXTcg-fbZ;N|UbUDjQb?i=X8v&^oMUX2wR|rx`gY#>dDatq7MD1|g98dQy z-01N%92~3-T6}@&Zqf8e28`oXy>kimXtwK*f;Oa*x%4Ksy{|D05UdTVeV1)nyMMsKjw9ZKn$;Q=iVkai~|Z zC@$&EV~3y0J6Z!TBHmt*aVK_n?c;k-5-Fa{-b6~Yl72+H`e16mIJscj-XwE7hBX?I0z=P1>gP=|VguvtOn9ua#y8;(SyqlAHo)d>;g zEx$IM3;wWnU4Nz_Y93K=1$ltNi`SjdQRAUc81`PI3nzUH$zK>$K5;t&o)O+fui2Ok z4#m);wB0ej2we%qL*Kiw6F7o zBgyz;=t`Jr=(YL9U|s(W_lqlFyTJpKrJmWB;I0Pa^qt++G*%egr`t9Ul3sZ^h(i5*q@!vuCVk9J& z6`;S5D|vujgAFDg0cNzd^U8tGl0&>pi_J#e@O$MKmMvsrg|&xx5BvHC)aduVG^%UjZGc_NfNnQ*$pY5QRv z;ZuJP&r;{L!qDPFCOtKfjxDY9j-<;GVh(;-i}!0M9mEihS&Cy%Em-nOsQ?7rot_o`GOd3uQ9#yhB}jCRZCk z4Mn@r&Q*uP3okFB}}&Q=-pBnVtcfi2?XbnufKM7zKRY zNOz_ztk~m)ZE0}N5976@0NzuRfz9SesZdFeZZ1jKY$d(S`{p-g`isZjZw)@Q2uC+c zGa$5uy4xJV=^S<|P|^?HYZT=A(xj{pMfI6JJ}Ej=t$tqz?N^T&}@~oR~ZPXGsl2j>Mhs(yw zQ!qGWKyo{tnPQc5u`em-vFvqpDVtHv2u45TuhO7C9#Ztu=BVG4xBODIydpW3NX>0e zDQ#1x>=GR{@k;KrkDbwrEPE`Vd8tlc>@!y;AU;a79bfJVm-Q8 z`@v1-n>f=2@PmDd;MRu~c8@^2RYF>#2PnDCU72)grm4rmnb#I^Fe_BU#~({C-f_>y z6vJ5w1mEw}xU)V_{?t#DXXM4*R+3FcTtK_laL>_jX8^CZC^t=iT=-J`YKrz&&GS+k zveDxV{MC*mUm?F3(2?pGY_|L`-{l=2dE4b<=PRTR9p5;t5d2%~(_9yV2E|U7EuwVo zBM&CnFg;wI+Q_zKZ~#x!g$?x;lAvKr;~iLq(Y!=4QGxoJLgM@L>G=r63fs(c!JAR# zk@=t*ysb0eRx9TB28b^X1$|E`p|JRnmBS=arU($n;ll7oKuN+h7E4E@EIlT39UY2_ zcv?Hg{gKng<8)=O!5hpoHD0Xq_(Wo!hn(wEn4u=;6vu>7tBh0Y1V_};cPC9zR;X;# zuIY(~7&4Z*dj$Ea!1t1O*708cg<(~I>3O^0(G%+Twx zs3mIr_-0xWl8(9pJc8yU2Q#0XRo}70#0DRigPy5s3%F<25ELEv!Awkmm{~~5Md2gL ziA9_o5L1+@ur*;_atvPdO>N8w1h?$U%-!#4s9bw_6cY6m`v;B}@5&xAf3EWovO+xm6o-?f5f%S^?ZUJ_P}4~Eoj?scKKW4vV?Rcy|)3dJ&)TPY>xlv+F@y`GyQDb{`E9;bNONG?nul`o%goNp9Ie4DPv05{6Ij z`F0fXur3|IQKdmGE6D=OUYf*cW}fi{bf1$zhB*1j@{lu3HQahK(QH=8o+VTr^7aox?UIZWa=fse^;VIKEQ| zi_o|R#{^0XJs6l?^4hfMIGO<%14I|($;Bul^Y}?ZP#XuqWM)HkNXGs6*ge32HJlMW z4ZfKRqS&9`nX@A3aXG{pO)PB76}yu>^V$>mFo61P3u(dCyH8;Kc6QHUO^*?FF~L2A zv7IqR?S&k1$Y?I9F^uO$RaPb{*5cyHwJ9hvKEI|g`b1NS9-*)a-cA?0EJ40&-q{)| zeOxRoJdox8rgmNMh-&x*=JDkvJXxtOUWOd^3)CXcVwYQF0wSH9*c#yg8@Q{KD_|IM z4+~m7M97tU>#IujLnPNS8~c2p7ZK3bC0$u^mI~V@nM(0Wbf&Dr$4}EogQ}w*A=Ely zlbiOwN@v*-c5n3@wKo5}9lw2TJ&JoUf|eGiL=ska3IEcdFoC8P+`t~Tl$*x{EVKgX zz6pj6K}g^P7VH7Px`5~@PrG^yh|-H7ggfZKzp{b%ExJqSs zq3rzX89-x;*Tvr4;#&3Nth&~{we}bnq5`RrKbs0)2U@XxV}MU`%(A#wU^UMq-81y? z7n&1o5(G1w+ylpID^V}*o>#b7@F>EzI27igEz=T3lsj&L`LTXVL0Kv^@fdW1TpSC( z9HVTbHzIK$?*sEK;{b_obvJ#m_+V4FY{MSzd44Lvgv^uK&}x|N#V4Tmlt@FHuv;qB z5#Kol@mOQ-VK2@_`Y5iQcT4WtJ$@X_k6nq0o%j>m5YM$@G69z6Adw#Zr-MWcC>TJo z8*xlB0`x2P`&PZdI24ouoU_(Vn+#Ej82^AWuXKHI=E^2!<>37_e*q5T2-|6}E2XV~ zL9)47UX%SPe;`XR;E7Mf10t(mXh+U`hEX46BP1N}-D}I!pStYOmWv4Ob+l=R_`FJ81Pm)!7f?d^n@6=ZTPq{zEvlYGHf6aJ?eber}ljMKIEK0ed zN`M8$51vhD9+C5I`w@{i;XT-wn4yO=DH)IPBu8f1j-W{I;kp!@lddU4yff_u)OY~t zu2+3q9{kpeG`6lPHH&Mpz&Z6h*XuQgHpzGpG5?rW5V`>yg4j8i>_>!qd1XE+BgMs zB0CKkoL`}JyCYu2!=#F&p%PM z0xQ?CPt6`98t82SXp;*Xk~4<@p$K zSCS`3DRYHg9}mh270lD`$j%x_aFx1KFBQz|S~b~pig=W`GaqUm2GKwk_#_dj9&Vhw z%nC~RsT@Y0m)aQSdlab0kyX4EnH}F`S6>*$KCNrZ=XNFZBuZ>z^Q}6Btq|c_6;V^o6?Dyhhr!)wG@C(*qRRXqU}7Om)A{uW#Qc3JbHzD|tx{=6{gj`qx5hmdylFC&?$sDN3e9u@Bs|+{@QsEKIS>CUV@5Se%5uUbK&WsD=Uz(;x@< zbX69Eul0+H0_*Kw^ztcbGO9=t9>JcM^Lr8!sDS<2BrC zGd_BZ1GCt9*jN1g?xBs4C_|gV!jwj;W_jnXf~S?a)Y?lbOIvNdi~7W--QXJ+Pz!Fm z(fCp8Kdg(0IKufbhaU(pSvk|AmX%s!*d1YxHcH8yY~dAabpl4Y$VbT5gs;I{5|o)L zu^p?*93|i4tUuv8b35&-hwN$F$4_4ahEmq23SRNA*{aX61Xme_8=IsOJB_W!T8I3e0 z>VOtvkMwlJCLSXD$GsPhjOPjiuceRFkQy{aXzZZadz&9`zT71#Dig@Pj-z>dDEkPT z1-pk~3%BSwB+VcTO%?_Nb%2EYK#jkg8k?hISgvbp${5y_t%(p?3=>_8P1TqtPCYP= zU4ls@*{h0eac{)I{zAbM2zV_uZ2s~L`ibD1k8@r}$2usWR7oqh(qYON#G)w53(Bdk zi+ZO#w~ISt2D<#Vgm67OZkJSNK}7L-@S3Ud;E0NrLP^Z)=*m)Z3R7yyx6dRxB_PUM^uJ`+YjbTtc?kcU6YF!R zYGuxNyP9$Q0PPpV-0uTzh1ON5ZOg`fyU+w2Yq~o2`*KF_4+rQuIeEA*EO9i2GSI_* zZ)3-+!O)jblc(>7m?+oNsG{zz9=C*9w3n zz>n{V@2*qW!qIxQC)XoC;j)b;R)9N~!|sZ=Y@mC1`tHqR@ySB+s6@p3=nuFH93^ao zqtlaPsA%d^4yux&)2BTWWIG~NG1EJyJGR2nf=^!M)}|tj#2v$!AB#I-1@S^V#Te(b z^h9l5vr+56EyFW-I*Uxm0_&qbfI80Zn#O5p&b{Dd6M+IS6q8TJwcvirVXq{95=zG( z{CIe2$1TPilQ$x?Ip*oCnj<}xmq-nl%y2Y}Uv93u$IMJQ22@sUqYJOyP{UZ@qWmP2s1-gCwBWA4qHy-D$SX z^`83n0;K1~qm7eMZjZEwt|0WLbJuvqK6sNho}xO`4?0ii_b5!YP`A*xV~S}=3!mom zB=>H`y*nipH1Qk)A}sqN+@Frt2$-=}wPAxpo}iH0*S!MYoU+K z`Sj?i?}s)MX1VDvL_25%W2$e6JI#2pw!TACSV~5H|FF3ay3xpP8_P)%z&V8_J_Nsi%qHqZ$I zq2dF2!Lti;5i)V?9;)`J{6y5%ZE>Vx-{4D(dnI?)xCu*-lQX8!Goa}Zzy#(Uohl|pLC-t(h? z=Ib9!r_Kpw)*zbmljDc-OYn(OPN)@Hk>Ke>AkS`|tLuO$gKmO$w1dH)C>au*w_eE& z7ZDHg#^~`Bu0S!R@bvR14)n%v9DI(HxyIW+S!t}+<1e`Y=C@`;NN9w2==+)e{kzH& z7FPBGMA2M(GmB+bTq{AFY%7*2J^$6L=)LRfu)HeV2;_}18EfCuu$qI2rQ3-#R z*(Pis!q{V0L7i(R52QXGZ~bh-^OSU0NlzH;a8+CqXT+%%}djJnWnkkaHFg=`qLK$A5VjLLtPom zYeR|~@NOqcY&km>u1p4JANZcoT3(IMwQm|^lM2y4xdpVJmG7e9qGgXg{e)5dno|K? ziGat`5;VsI0SAU+w4KF%dch>T zqP#=X32KCv!YR2Cu;kgIyTE7j|*Ie(E=V)CWVbV3~eU`-VqG@crJ21Lq2}HrUfAoR3FV5_N4pZMEhoS6m5<;f9fYN-onG69={f#GCPp83pKpgB1a<0cwZdlHL2eiQz4 z_YB4Ib{Aux#)JvgXT#Ma^|F2Amz9^}l{*_EumQ?br5~&}eAyjg#TohL;_EKtmv?ZQ zE>wo9`H0T?eb6Oa*R>iSb#@J-f2M6GufldAgppLlv6d1cR7kdqlpf$1eq?*~CN08r zix1gg_83j8BmC?Y(^Xv2EU7u!-joKb?G~iY)k>ODY-Gs?hu5F-mMq@6Ucz!TF*Imq zNbNrcHbV6z5QHihNw%ZPB z7F#WPwKn=D8^bEyW7h&U`eol@<@VwzQculbgN-5ZV7HMNhGK{0 zO5I0TbKmwckH47!&?C;GG~WB8S)h@=RfD@5q||2K%#%puy>Tnl0d<0_tgM_W;welwZdO!uN=omnmmuJVl{|!ldS(!QmRLh}OOQ zkfY5~9)T_{B79y-)0GfDmEgN+FCCzuTYL`a*!Qlyt zb`mAgnmS}dc;6y&6xT=Y$q_8W-%nO7#GcRB?=y!rX^mzf#2rmdxmH|IGyn2vbtGX@ zGX-_tR=bV#LrRuKubwC{9X~Fw*z&{<*05&|7jhwIo(AT$En>SpyuB+;_TrO)fg()p zN5S!qf^|yA%M662?kBB|WcEpImDh{`{d;P1idcj`dGIIpTkntd4#L$A?y^WaHfCqR zs(8v?ueUM8x?CTbFn>8HT1_6bbsoEd;$#>{QHwx!$%}Zq|LE#c_wm&#`9={t9xgi- z`IzqTSbVK!o+OnC7CG=xsMb?cqPAQK`y){=%16*ioBm|xeDuC&^6(oH+osN@6LPOt zLda`KAN5MRdAV(LH$I2AaV=woUuh)+s8s4-g&*ub+5MoUVoL#9bWcE4WLTIYCoON9Q_>h2h!<-mzi0Ak^`U z6{H!W0(IiohqR;Q#u$iFhZE<~)v{jpX$ow*sCY@{u)4WaNoNV80$JWI?iX1NY@wI<}Rw zIi}zqdfn!+>r*a{p}Sxl{?@B61oqSY~lP7$B_)>7$UMCAOGL zttBXY)g8x&yivfH(nrM;K^5;b;Lf@l1F`;^uM_cjdVwT~e)NJD3OwX0sarAc1g#gd zEz%q)o4aZk8|Z?hSuJ9tM`@g~IjU5}vJ1#c;9fP<3NxHMBd!r6yY581O-pD$N%Z#T z-#@|86nYC{o1ySYr~OQjcn(FiF(N-zCqD_4e>aDdKlifPQKV-%f z=d_;ZfM6D11r_4_$Jwh`ccHz$BQT4{PV~O9un+zU*XZQ;mTWf&4n2l7P<~?Q4>1;Z zLCmlG*gk&|LCij@>3fdl2GE_&*FQ0))HqRZh_I|nK`D`RjiAb!Kz4m0(h(Wstci3M zuz`styQu2Fph7c+X)=v=o=$82FDVMKE#SRlF`D;h~dNT%pgaL*D z1`7)k2m~Vqt8U6C+C>5b>!1b$Lj~QAe>4RNH4#P`MM-9P88Hb(RS9)9C@|3W_P^ag zro$GLf?kIN{T1T}H!L9Dp#O8DAfhNEDWR&yq#*gXt{AtUi=%f>@<1jyx{{iH`u{?~O&HsFuC>kBeZlJ*D0pW80FtrGv59r?q|G(qr zf1OoW%(O{t5R^73fPM_qW12sPQw6E*I9UE>{rn$?oce(V76C$I`(a>CptAOF2lnSP zxK!t=Y5@Xi1_g@H4?tRse*mQJVEg|Qo*PiyJaC{mK?Hr&f4rD*u>2nNH*@#B*7=Xl z)1Um8^S@@w?7QpYZ=8QG(*0E~{hO`w{@(e&0`4~u-)qwT7-hlyKS2DSnBbpkfB$@C z`d-KItKi8uyB7Her2kp*_GjGh#jAe2XE90tfcs0qs=wDv{2AwaC7-WSSl_Hh@%K1? zD2(+p==b_EUqynx8KTM$p#P~m{E=kP&nVx^Vf?ss`>MZ0`A@s&|EOH^Gw%1Q0AIy6 zzFD5;KjZ#ZdgEuP?`agj$_#unblrc1`pxI-d(OSD$9UgN!RD8K|A3P5=lA|S5#5gw z?rHZA82>)X`Fk$EpK-o#0scyB_ss_E{|x6hll6W3?AK1>Z`R=dOMt)YEB^VNf8X2r z<0{Mt{MzyFdvSlp_`Y8KwM+Dyr3C#G#&722`zqttV)r+r%KoL>UzWaqezV^f#D2VO z4dnjP>p#^ie|G-;q4w9B+Bb8~|F!c!sIdJE^8G31k4uX1`j;Soa9aK|#`l}EujirP o%n!7o`Ytj0&(-zc7=Lp*sw@Wu%FMyQ$U$GLpnV-;?bqM_A9CD*LjV8( literal 0 HcmV?d00001 diff --git a/packages/sdk-kmp/gradle/wrapper/gradle-wrapper.properties b/packages/sdk-kmp/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..bdc1ff0ac --- /dev/null +++ b/packages/sdk-kmp/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,10 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionSha256Sum=d8a18a7a841dd5df825d35a685fad6f2d7f12ac0c280e57b67c27b4a520ba228 +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/packages/sdk-kmp/gradlew b/packages/sdk-kmp/gradlew new file mode 100755 index 000000000..249efbb03 --- /dev/null +++ b/packages/sdk-kmp/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/packages/sdk-kmp/package.json b/packages/sdk-kmp/package.json new file mode 100644 index 000000000..4fff403fb --- /dev/null +++ b/packages/sdk-kmp/package.json @@ -0,0 +1,29 @@ +{ + "name": "@meshtastic/sdk-kmp", + "version": "0.1.0", + "private": true, + "description": "Kotlin Multiplatform meshtastic-sdk compiled to JavaScript, with a TypeScript-facing facade and browser transports.", + "license": "GPL-3.0-only", + "repository": { + "type": "git", + "url": "git+https://github.com/meshtastic/web.git", + "directory": "packages/sdk-kmp" + }, + "files": [ + "dist" + ], + "type": "module", + "main": "./dist/sdk-kmp.mjs", + "types": "./dist/sdk-kmp.d.mts", + "exports": { + ".": { + "types": "./dist/sdk-kmp.d.mts", + "default": "./dist/sdk-kmp.mjs" + } + }, + "scripts": { + "build": "node ./scripts/build.mjs", + "ensure-dist": "node ./scripts/build.mjs --if-missing", + "clean": "rm -rf dist build" + } +} diff --git a/packages/sdk-kmp/scripts/build.mjs b/packages/sdk-kmp/scripts/build.mjs new file mode 100644 index 000000000..c485af503 --- /dev/null +++ b/packages/sdk-kmp/scripts/build.mjs @@ -0,0 +1,55 @@ +import { spawnSync } from "node:child_process"; +import { cpSync, existsSync, mkdirSync, readdirSync, rmSync } from "node:fs"; +import path from "node:path"; +import process from "node:process"; +import { fileURLToPath } from "node:url"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const dist = path.join(root, "dist"); +const gradleOut = path.join(root, "build/dist/js/productionLibrary"); +const entry = path.join(dist, "sdk-kmp.mjs"); + +if (process.argv.includes("--if-missing") && existsSync(entry)) { + process.exit(0); +} + +const env = { ...process.env }; +const homebrewJdk = "/opt/homebrew/opt/openjdk@21"; +if (!env.JAVA_HOME && existsSync(homebrewJdk)) { + env.JAVA_HOME = homebrewJdk; +} + +const gradlew = process.platform === "win32" ? "gradlew.bat" : "./gradlew"; +const result = spawnSync( + gradlew, + ["jsBrowserProductionLibraryDistribution", "--console=plain", "-q"], + { + cwd: root, + env, + stdio: "inherit", + shell: process.platform === "win32", + }, +); + +if (result.error || result.status !== 0) { + console.error( + [ + "", + "@meshtastic/sdk-kmp: the Gradle build failed.", + "It needs JDK 21 (set JAVA_HOME, e.g. /opt/homebrew/opt/openjdk@21 on macOS) and", + "org.meshtastic:sdk-core-js in a reachable Maven repository; see packages/sdk-kmp/README.md.", + "", + ].join("\n"), + ); + process.exit(result.status ?? 1); +} + +rmSync(dist, { recursive: true, force: true }); +mkdirSync(dist, { recursive: true }); +for (const name of readdirSync(gradleOut)) { + if (name === "package.json") continue; + cpSync(path.join(gradleOut, name), path.join(dist, name)); +} +console.log( + `@meshtastic/sdk-kmp: wrote ${readdirSync(dist).length} files to dist/`, +); diff --git a/packages/sdk-kmp/settings.gradle.kts b/packages/sdk-kmp/settings.gradle.kts new file mode 100644 index 000000000..5b09248a4 --- /dev/null +++ b/packages/sdk-kmp/settings.gradle.kts @@ -0,0 +1,21 @@ +pluginManagement { + repositories { + gradlePluginPortal() + mavenCentral() + google() + } +} + +plugins { id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" } + +dependencyResolutionManagement { + repositories { + mavenCentral() + google() + // Until meshtastic-sdk publishes its js artifacts (meshtastic/meshtastic-sdk#215), + // sdk-core-js comes from `./gradlew publishToMavenLocal` in that repo. + mavenLocal() + } +} + +rootProject.name = "sdk-kmp" diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Bytes.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Bytes.kt new file mode 100644 index 000000000..f71a40459 --- /dev/null +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Bytes.kt @@ -0,0 +1,15 @@ +package org.meshtastic.sdk.js + +import okio.ByteString +import org.khronos.webgl.Int8Array +import org.khronos.webgl.Uint8Array + +internal fun Uint8Array.toByteArray(): ByteArray = + Int8Array(buffer, byteOffset, length).unsafeCast() + +internal fun ByteArray.toUint8Array(): Uint8Array { + val i8 = unsafeCast() + return Uint8Array(i8.buffer, i8.byteOffset, i8.length) +} + +internal fun ByteString.toUint8Array(): Uint8Array = toByteArray().toUint8Array() diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt new file mode 100644 index 000000000..7d5c81258 --- /dev/null +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt @@ -0,0 +1,66 @@ +@file:OptIn(ExperimentalJsExport::class) + +package org.meshtastic.sdk.js + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.promise +import org.khronos.webgl.Uint8Array +import org.meshtastic.proto.ToRadio +import org.meshtastic.sdk.AutoReconnectConfig +import org.meshtastic.sdk.InMemoryStorageProvider +import org.meshtastic.sdk.RadioClient +import org.meshtastic.sdk.RadioTransport +import kotlin.js.ExperimentalJsExport +import kotlin.js.JsExport +import kotlin.js.Promise + +@JsExport +class MeshtasticClient internal constructor(transport: RadioTransport, private val maxAttempts: Int) { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val frameListeners = mutableSetOf<(Uint8Array) -> Unit>() + private val client: RadioClient = RadioClient { + transport(TappingTransport(transport) { bytes -> frameListeners.toList().forEach { it(bytes.toUint8Array()) } }) + storage(InMemoryStorageProvider()) + autoReconnect(AutoReconnectConfig(maxAttempts = maxAttempts)) + } + + fun connect(): Promise = scope.promise { + try { + client.connect() + } catch (e: Throwable) { + throw e.toJsError().unsafeCast() + } + } + + fun disconnect(): Promise = scope.promise { client.disconnect() } + + val connectionState: ConnectionStateJs get() = client.connection.value.toJs(maxAttempts) + + val myNodeNum: Int? get() = client.ownNode.value?.num + + fun onConnectionState(cb: (ConnectionStateJs) -> Unit): () -> Unit { + val job = client.connection.onEach { cb(it.toJs(maxAttempts)) }.launchIn(scope) + return { job.cancel() } + } + + fun onFromRadio(cb: (Uint8Array) -> Unit): () -> Unit { + frameListeners.add(cb) + return { frameListeners.remove(cb) } + } + + fun sendRaw(toRadio: Uint8Array) { + try { + client.sendRaw(ToRadio.ADAPTER.decode(toRadio.toByteArray())) + } catch (e: Throwable) { + throw e.toJsError().unsafeCast() + } + } +} + +@JsExport +fun createHttpClient(url: String, allowPrompt: Boolean = false, maxAttempts: Int = 10): MeshtasticClient = + MeshtasticClient(HttpTransport(url.trimEnd('/'), allowPrompt), maxAttempts) diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/HttpTransport.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/HttpTransport.kt new file mode 100644 index 000000000..d3afcd7a0 --- /dev/null +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/HttpTransport.kt @@ -0,0 +1,110 @@ +package org.meshtastic.sdk.js + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.await +import kotlinx.coroutines.cancel +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.receiveAsFlow +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import okio.ByteString.Companion.toByteString +import org.khronos.webgl.ArrayBuffer +import org.khronos.webgl.Uint8Array +import org.meshtastic.sdk.Frame +import org.meshtastic.sdk.RadioTransport +import org.meshtastic.sdk.TransportIdentity +import org.meshtastic.sdk.TransportState +import org.meshtastic.sdk.WireFraming +import kotlin.js.Promise + +internal class HttpTransport( + private val baseUrl: String, + private var allowPrompt: Boolean, + private val pollMillis: Long = 3_000, +) : RadioTransport { + override val identity: TransportIdentity = TransportIdentity("http:${baseUrl.lowercase()}") + private val _state = MutableStateFlow(TransportState.Disconnected) + override val state: StateFlow = _state.asStateFlow() + private val inbound = Channel(Channel.UNLIMITED) + private var scope: CoroutineScope? = null + + override suspend fun connect() { + _state.value = TransportState.Connecting + try { + Lna.check(baseUrl, allowPrompt) + request("$baseUrl/api/v1/toradio", "OPTIONS") + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + _state.value = TransportState.Disconnected + throw Lna.classify(baseUrl, e) + } finally { + allowPrompt = false + } + _state.value = TransportState.Connected + scope = CoroutineScope(SupervisorJob()).also { s -> + s.launch { + while (isActive) { + try { + drain() + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + _state.value = TransportState.Error(Lna.classify(baseUrl, e), recoverable = true) + return@launch + } + delay(pollMillis) + } + } + } + } + + private suspend fun drain() { + while (true) { + val response = request("$baseUrl/api/v1/fromradio?all=false", "GET") + val buffer = (response.arrayBuffer() as Promise).await() + if (buffer.byteLength == 0) return + inbound.trySend(Frame(WireFraming.frame(Uint8Array(buffer).toByteArray()))) + } + } + + override suspend fun disconnect() { + scope?.cancel() + scope = null + _state.value = TransportState.Disconnected + } + + override suspend fun send(frame: Frame) { + val init = Lna.requestInit(baseUrl, "PUT") + init.body = WireFraming.payload(frame.bytes.toByteArray()).toUint8Array() + val response = fetch("$baseUrl/api/v1/toradio", init).await() + if (response.ok != true) throw ClientException("transport", "toradio ${response.status}") + } + + override fun frames(): Flow = inbound.receiveAsFlow() + + private suspend fun request(url: String, method: String): dynamic { + val response = fetch(url, Lna.requestInit(baseUrl, method)).await() + if (response.ok != true) throw ClientException("transport", "$method ${response.status}") + return response + } +} + +private fun WireFraming.frame(payload: ByteArray): okio.ByteString { + val framed = ByteArray(HEADER_SIZE + payload.size) + framed[0] = MAGIC_0 + framed[1] = MAGIC_1 + framed[2] = (payload.size shr 8).toByte() + framed[3] = (payload.size and 0xFF).toByte() + payload.copyInto(framed, HEADER_SIZE) + return framed.toByteString() +} + +private fun WireFraming.payload(framed: ByteArray): ByteArray = framed.copyOfRange(HEADER_SIZE, framed.size) diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Js.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Js.kt new file mode 100644 index 000000000..b7c6b486c --- /dev/null +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Js.kt @@ -0,0 +1,32 @@ +package org.meshtastic.sdk.js + +import kotlin.js.Promise + +internal fun jso(): T = js("({})").unsafeCast() + +internal external fun fetch(url: String, init: dynamic = definedExternally): Promise + +internal class ClientException(val kind: String, message: String) : Exception(message) + +internal fun Throwable.kind(): String { + var cause: Throwable? = this + while (cause != null) { + if (cause is ClientException) return cause.kind + cause = cause.cause + } + return when (this) { + is org.meshtastic.sdk.MeshtasticException.HandshakeTimeout -> "handshake-timeout" + is org.meshtastic.sdk.MeshtasticException.FirmwareTooOld -> "firmware-too-old" + is org.meshtastic.sdk.MeshtasticException.Protocol -> "protocol" + is org.meshtastic.sdk.MeshtasticException.AlreadyConnected -> "already-connected" + is org.meshtastic.sdk.MeshtasticException.NotConnected -> "not-connected" + else -> "transport" + } +} + +internal fun Throwable.toJsError(): dynamic { + val error = js("new Error()") + error.name = kind() + error.message = message ?: kind() + return error +} diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Lna.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Lna.kt new file mode 100644 index 000000000..1160a4adf --- /dev/null +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Lna.kt @@ -0,0 +1,65 @@ +package org.meshtastic.sdk.js + +import kotlinx.browser.window +import kotlinx.coroutines.await +import kotlin.js.Promise + +internal object Lna { + const val DENIED = "lna-denied" + const val PROMPT = "lna-prompt" + + private val permissionNames = listOf("local-network", "local-network-access") + + fun needsLocalTarget(url: String): Boolean = + url.startsWith("http:") && window.location.protocol == "https:" && !isLoopback(url) + + fun requestInit(url: String, method: String): dynamic { + val init = jso() + init.method = method + if (needsLocalTarget(url)) init.targetAddressSpace = "local" + return init + } + + suspend fun permission(): String { + val permissions = js("navigator.permissions") + if (js("globalThis.isSecureContext") != true || permissions == null || permissions.query == null) return "unsupported" + for (name in permissionNames) { + val query = jso() + query.name = name + val state = try { + (permissions.query(query) as Promise).await().state as String + } catch (_: Throwable) { + continue + } + return state + } + return "unsupported" + } + + suspend fun check(url: String, allowPrompt: Boolean) { + if (!needsLocalTarget(url)) return + when (permission()) { + "denied" -> throw ClientException(DENIED, "Local network access denied") + "prompt" -> if (!allowPrompt) throw ClientException(PROMPT, "Local network access not yet allowed") + } + } + + suspend fun classify(url: String, failure: Throwable): Throwable { + if (failure is ClientException || !needsLocalTarget(url)) return failure + return when (permission()) { + "denied" -> ClientException(DENIED, "Local network access denied") + "prompt" -> ClientException(PROMPT, "Local network access not yet allowed") + else -> failure + } + } + + private fun isLoopback(url: String): Boolean { + val host = try { + org.w3c.dom.url.URL(url).hostname.lowercase() + } catch (_: Throwable) { + return false + } + return host == "localhost" || host.endsWith(".localhost") || host == "[::1]" || + Regex("""^127\.\d+\.\d+\.\d+$""").matches(host) + } +} diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/State.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/State.kt new file mode 100644 index 000000000..e558ff821 --- /dev/null +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/State.kt @@ -0,0 +1,48 @@ +@file:OptIn(ExperimentalJsExport::class) + +package org.meshtastic.sdk.js + +import org.meshtastic.sdk.ConnectionState +import kotlin.js.ExperimentalJsExport +import kotlin.js.JsExport + +@JsExport +external interface ConnectionStateJs { + val kind: String + val attempt: Int + val maxAttempts: Int + val phase: String? + val progress: Double + val error: String? + val errorKind: String? +} + +internal fun ConnectionState.toJs(maxAttempts: Int): ConnectionStateJs { + val state = jso() + state.attempt = 0 + state.maxAttempts = maxAttempts + state.phase = null + state.progress = 0.0 + state.error = null + state.errorKind = null + when (this) { + ConnectionState.Disconnected -> state.kind = "disconnected" + is ConnectionState.Connecting -> { + state.kind = "connecting" + state.attempt = attempt + } + is ConnectionState.Configuring -> { + state.kind = "configuring" + state.phase = phase.name + state.progress = progress.toDouble() + } + ConnectionState.Connected -> state.kind = "connected" + is ConnectionState.Reconnecting -> { + state.kind = "reconnecting" + state.attempt = attempt + state.error = cause.message + state.errorKind = cause.kind() + } + } + return state.unsafeCast() +} diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/TappingTransport.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/TappingTransport.kt new file mode 100644 index 000000000..61bb18a8f --- /dev/null +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/TappingTransport.kt @@ -0,0 +1,29 @@ +package org.meshtastic.sdk.js + +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.onEach +import org.meshtastic.sdk.Frame +import org.meshtastic.sdk.RadioTransport +import org.meshtastic.sdk.TransportIdentity +import org.meshtastic.sdk.TransportState +import org.meshtastic.sdk.WireFraming + +internal class TappingTransport( + private val inner: RadioTransport, + private val tap: (ByteArray) -> Unit, +) : RadioTransport { + override val identity: TransportIdentity get() = inner.identity + override val state: StateFlow get() = inner.state + + override suspend fun connect() = inner.connect() + + override suspend fun disconnect() = inner.disconnect() + + override suspend fun send(frame: Frame) = inner.send(frame) + + override fun frames(): Flow = inner.frames().onEach { frame -> + val bytes = frame.bytes.toByteArray() + if (bytes.size > WireFraming.HEADER_SIZE) tap(bytes.copyOfRange(WireFraming.HEADER_SIZE, bytes.size)) + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5a9867e0f..3f3b8d19a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -66,6 +66,9 @@ importers: '@meshtastic/sdk': specifier: workspace:* version: link:../../packages/sdk + '@meshtastic/sdk-kmp': + specifier: workspace:* + version: link:../../packages/sdk-kmp '@meshtastic/sdk-react': specifier: workspace:* version: link:../../packages/sdk-react @@ -357,6 +360,8 @@ importers: specifier: ^5.2.0 version: 5.2.0 + packages/sdk-kmp: {} + packages/sdk-react: dependencies: '@meshtastic/sdk': From e0b6ab0dd64dda85d8fb841cc9192b77062cbefb Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 07:54:30 -0500 Subject: [PATCH 07/49] feat(web): connect over HTTP through the Kotlin SDK behind a flag With localStorage meshtastic:web:kmp=1, HTTP connections are opened by @meshtastic/sdk-kmp: the Kotlin SDK runs the handshake, owns the connection state and reconnects (AutoReconnectConfig maxAttempts=10), and handles Chrome Local Network Access (denied is terminal, prompt only from a gesture). core/kmp presents the SDK client as the TypeScript SDK's Transport so the existing MeshDevice keeps feeding the stores, maps ConnectionState onto the saved-connection status (reconnect attempt n/max) and classifies connect failures by the SDK's exception kinds. The SDK bundle is a lazily imported chunk (231 KB gz). --- .../public/i18n/locales/en/connections.json | 6 +- apps/web/src/core/connections/sdkClient.ts | 4 +- apps/web/src/core/kmp/client.ts | 27 ++++ apps/web/src/core/kmp/connectionState.test.ts | 87 ++++++++++++ apps/web/src/core/kmp/connectionState.ts | 110 +++++++++++++++ apps/web/src/core/kmp/fakeClient.ts | 72 ++++++++++ apps/web/src/core/kmp/flag.ts | 13 ++ apps/web/src/core/kmp/transport.test.ts | 106 ++++++++++++++ apps/web/src/core/kmp/transport.ts | 82 +++++++++++ apps/web/src/core/stores/deviceStore/types.ts | 4 +- .../Connections/useConnections.kmp.test.ts | 133 ++++++++++++++++++ .../src/pages/Connections/useConnections.ts | 102 +++++++++++++- 12 files changed, 740 insertions(+), 6 deletions(-) create mode 100644 apps/web/src/core/kmp/client.ts create mode 100644 apps/web/src/core/kmp/connectionState.test.ts create mode 100644 apps/web/src/core/kmp/connectionState.ts create mode 100644 apps/web/src/core/kmp/fakeClient.ts create mode 100644 apps/web/src/core/kmp/flag.ts create mode 100644 apps/web/src/core/kmp/transport.test.ts create mode 100644 apps/web/src/core/kmp/transport.ts create mode 100644 apps/web/src/pages/Connections/useConnections.kmp.test.ts diff --git a/apps/web/public/i18n/locales/en/connections.json b/apps/web/public/i18n/locales/en/connections.json index 63702590b..fe85df795 100644 --- a/apps/web/public/i18n/locales/en/connections.json +++ b/apps/web/public/i18n/locales/en/connections.json @@ -89,7 +89,11 @@ "httpsNotReachable": "HTTPS endpoint not reachable. Check that the device is online.", "httpNotReachable": "HTTP endpoint not reachable (may be blocked by CORS or a network issue)", "openInNewTab": "Open in new tab →", - "firmwareTooOld": "Firmware {{version}} is too old for the web client. Update the radio to {{minimum}} or newer." + "firmwareTooOld": "Firmware {{version}} is too old for the web client. Update the radio to {{minimum}} or newer.", + "localNetworkDenied": "Chrome blocked local network access for this site. Click the site-info icon in the address bar, allow Local network, then Connect.", + "localNetworkPrompt": "Chrome needs your permission to reach the local network. Click Connect to allow it.", + "handshakeTimeout": "The radio stopped responding during the handshake. It may be in CLI or bootloader mode, or its firmware isn't answering config requests.", + "reconnectFailed": "Could not reconnect after {{attempts}} attempts." }, "httpTest": { "certNotTrusted": "Certificate not trusted. <0>Open in new tab and accept the warning, then test again." diff --git a/apps/web/src/core/connections/sdkClient.ts b/apps/web/src/core/connections/sdkClient.ts index 9e7e807d4..c1e9d05f4 100644 --- a/apps/web/src/core/connections/sdkClient.ts +++ b/apps/web/src/core/connections/sdkClient.ts @@ -1,6 +1,6 @@ import { coordinator, getStorageDb } from "@core/sdkStorage.ts"; import type { ConnectionId } from "@core/stores/deviceStore/types"; -import { createLogger, MeshDevice } from "@meshtastic/sdk"; +import { createLogger, MeshDevice, type Transport } from "@meshtastic/sdk"; import { SqlocalDraftRepository, SqlocalMessageRepository, @@ -61,7 +61,7 @@ export const UNKNOWN_NODE_SCOPE = -1; export async function buildMeshDevice( connectionId: ConnectionId, deviceId: number, - transport: AnyTransport, + transport: Transport, nodeNum?: number, ): Promise<{ meshDevice: MeshDevice; persistent: boolean }> { log.debug("buildMeshDevice: enter", { connectionId, deviceId, nodeNum }); diff --git a/apps/web/src/core/kmp/client.ts b/apps/web/src/core/kmp/client.ts new file mode 100644 index 000000000..9c8eed5f5 --- /dev/null +++ b/apps/web/src/core/kmp/client.ts @@ -0,0 +1,27 @@ +import type { MeshtasticClient } from "@meshtastic/sdk-kmp"; + +export type { ConnectionStateJs, MeshtasticClient } from "@meshtastic/sdk-kmp"; + +/** Reconnect attempts the SDK makes before giving up, as the user approved. */ +export const MAX_RECONNECT_ATTEMPTS = 10; + +type KmpModule = typeof import("@meshtastic/sdk-kmp"); + +let loading: Promise | undefined; + +/** + * The Kotlin SDK is ~240 KB gzipped, so it is loaded on first connect + * rather than with the app shell. + */ +export function loadKmp(): Promise { + loading ??= import("@meshtastic/sdk-kmp"); + return loading; +} + +export async function createHttpClient( + url: string, + allowPrompt: boolean, +): Promise { + const kmp = await loadKmp(); + return kmp.createHttpClient(url, allowPrompt, MAX_RECONNECT_ATTEMPTS); +} diff --git a/apps/web/src/core/kmp/connectionState.test.ts b/apps/web/src/core/kmp/connectionState.test.ts new file mode 100644 index 000000000..d65e25483 --- /dev/null +++ b/apps/web/src/core/kmp/connectionState.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it, vi } from "vitest"; +import { + connectErrorKind, + connectFailure, + reconnectAttempt, + toConnectionStatus, +} from "./connectionState.ts"; +import { state } from "./fakeClient.ts"; + +vi.mock("i18next", () => ({ t: (key: string) => key })); + +function named(name: string, message = name): Error { + const error = new Error(message); + error.name = name; + return error; +} + +describe("toConnectionStatus", () => { + it("maps every SDK state onto a saved-connection status", () => { + expect(toConnectionStatus(state("disconnected"))).toBe("disconnected"); + expect(toConnectionStatus(state("connecting", { attempt: 1 }))).toBe( + "connecting", + ); + expect(toConnectionStatus(state("configuring", { phase: "Stage2" }))).toBe( + "configuring", + ); + expect(toConnectionStatus(state("connected"))).toBe("connected"); + expect(toConnectionStatus(state("reconnecting", { attempt: 3 }))).toBe( + "connecting", + ); + }); +}); + +describe("reconnectAttempt", () => { + it("exposes attempt n of maxAttempts only while reconnecting", () => { + expect( + reconnectAttempt(state("reconnecting", { attempt: 4, maxAttempts: 10 })), + ).toEqual({ attempt: 4, maxAttempts: 10 }); + expect(reconnectAttempt(state("connecting", { attempt: 1 }))).toBe( + undefined, + ); + }); +}); + +describe("connectFailure", () => { + it("treats a denied Local Network Access permission as terminal", () => { + expect(connectErrorKind(named("lna-denied"))).toBe("lna-denied"); + expect(connectFailure(named("lna-denied"))).toEqual({ + status: "error", + error: "connections:errors.localNetworkDenied", + errorKind: "lna-denied", + }); + }); + + it("leaves a connection disconnected when the permission still needs a prompt", () => { + expect(connectFailure(named("lna-prompt"))).toMatchObject({ + status: "disconnected", + errorKind: "network", + }); + }); + + it("surfaces handshake timeouts and firmware errors", () => { + expect(connectFailure(named("handshake-timeout"))).toMatchObject({ + status: "error", + error: "connections:errors.handshakeTimeout", + }); + expect( + connectFailure( + named("firmware-too-old", "Firmware requires newer client"), + ), + ).toEqual({ + status: "error", + error: "Firmware requires newer client", + errorKind: undefined, + }); + }); + + it("classifies anything else as a network error with its message", () => { + expect(connectErrorKind(new Error("boom"))).toBe("transport"); + expect(connectFailure(new Error("boom"))).toEqual({ + status: "error", + error: "boom", + errorKind: "network", + }); + expect(connectFailure("oops")).toMatchObject({ error: "oops" }); + }); +}); diff --git a/apps/web/src/core/kmp/connectionState.ts b/apps/web/src/core/kmp/connectionState.ts new file mode 100644 index 000000000..2c6576880 --- /dev/null +++ b/apps/web/src/core/kmp/connectionState.ts @@ -0,0 +1,110 @@ +import type { + Connection, + ConnectionStatus, +} from "@app/core/stores/deviceStore/types"; +import type { ConnectionStateJs } from "@meshtastic/sdk-kmp"; +import { t } from "i18next"; + +/** + * How a connect failure is classified. The facade sets `error.name` to one + * of the SDK's exception kinds; everything else is a plain transport error. + */ +export type ConnectErrorKind = + | "lna-denied" + | "lna-prompt" + | "handshake-timeout" + | "firmware-too-old" + | "protocol" + | "transport"; + +const ERROR_KINDS: ReadonlySet = new Set([ + "lna-denied", + "lna-prompt", + "handshake-timeout", + "firmware-too-old", + "protocol", + "transport", +]); + +function isConnectErrorKind(name: string): name is ConnectErrorKind { + return ERROR_KINDS.has(name); +} + +export function connectErrorKind(error: unknown): ConnectErrorKind { + if (error instanceof Error && isConnectErrorKind(error.name)) { + return error.name; + } + return "transport"; +} + +export interface ConnectFailure { + status: ConnectionStatus; + error: string; + errorKind: Connection["errorKind"]; +} + +/** + * Saved-connection fields for a failed connect. A denied Local Network + * Access permission is terminal (only the user can lift it); a pending + * prompt means an automatic connect stopped short of prompting, so the + * connection just stays disconnected until the user clicks Connect. + */ +export function connectFailure(error: unknown): ConnectFailure { + const kind = connectErrorKind(error); + const message = error instanceof Error ? error.message : String(error); + switch (kind) { + case "lna-denied": + return { + status: "error", + error: t("connections:errors.localNetworkDenied"), + errorKind: "lna-denied", + }; + case "lna-prompt": + return { + status: "disconnected", + error: t("connections:errors.localNetworkPrompt"), + errorKind: "network", + }; + case "handshake-timeout": + return { + status: "error", + error: t("connections:errors.handshakeTimeout"), + errorKind: "network", + }; + case "firmware-too-old": + return { status: "error", error: message, errorKind: undefined }; + default: + return { status: "error", error: message, errorKind: "network" }; + } +} + +/** + * Maps the SDK's connection state onto the saved-connection status the + * drawer and overlay already render. `configuring` is the SDK handshake; + * `configured` is only reached once the web client has its own config + * stream (see `useConnections`), so the SDK's `connected` maps to + * `connected` here. + */ +export function toConnectionStatus(state: ConnectionStateJs): ConnectionStatus { + switch (state.kind) { + case "connecting": + case "reconnecting": + return "connecting"; + case "configuring": + return "configuring"; + case "connected": + return "connected"; + default: + return "disconnected"; + } +} + +/** The reconnect attempt the SDK is on, as `attempt/maxAttempts`, if any. */ +export function reconnectAttempt( + state: ConnectionStateJs, +): { attempt: number; maxAttempts: number } | undefined { + if (state.kind !== "reconnecting") { + return undefined; + } + return { attempt: state.attempt, maxAttempts: state.maxAttempts }; +} diff --git a/apps/web/src/core/kmp/fakeClient.ts b/apps/web/src/core/kmp/fakeClient.ts new file mode 100644 index 000000000..b6535517f --- /dev/null +++ b/apps/web/src/core/kmp/fakeClient.ts @@ -0,0 +1,72 @@ +import type { ConnectionStateJs, MeshtasticClient } from "@meshtastic/sdk-kmp"; + +export function state( + kind: string, + overrides: Partial = {}, +): ConnectionStateJs { + return { + kind, + attempt: 0, + maxAttempts: 10, + phase: null, + progress: 0, + error: null, + errorKind: null, + ...overrides, + }; +} + +/** + * A scripted stand-in for the facade's client, for tests: callers push + * frames and states and record what the web client sent. + */ +export class FakeKmpClient implements MeshtasticClient { + connectionState: ConnectionStateJs = state("disconnected"); + myNodeNum: number | null = null; + readonly sent: Uint8Array[] = []; + readonly disconnects: number[] = []; + private frameListeners = new Set<(bytes: Uint8Array) => void>(); + private stateListeners = new Set<(s: ConnectionStateJs) => void>(); + + async connect(): Promise { + this.setState(state("connected")); + } + + async disconnect(): Promise { + this.disconnects.push(Date.now()); + this.setState(state("disconnected")); + } + + onConnectionState(cb: (s: ConnectionStateJs) => void): () => void { + this.stateListeners.add(cb); + cb(this.connectionState); + return () => this.stateListeners.delete(cb); + } + + onFromRadio(cb: (bytes: Uint8Array) => void): () => void { + this.frameListeners.add(cb); + return () => this.frameListeners.delete(cb); + } + + sendRaw(toRadio: Uint8Array): void { + if (this.connectionState.kind !== "connected") { + const error = new Error("Client not connected"); + error.name = "not-connected"; + throw error; + } + this.sent.push(toRadio); + } + + emitFrame(bytes: Uint8Array): void { + for (const cb of this.frameListeners) { + cb(bytes); + } + } + + setState(next: ConnectionStateJs): void { + this.connectionState = next; + for (const cb of this.stateListeners) { + cb(next); + } + } +} diff --git a/apps/web/src/core/kmp/flag.ts b/apps/web/src/core/kmp/flag.ts new file mode 100644 index 000000000..df6be423f --- /dev/null +++ b/apps/web/src/core/kmp/flag.ts @@ -0,0 +1,13 @@ +/** + * Opt-in for connecting over HTTP through the Kotlin SDK while the + * migration lands: `localStorage.setItem("meshtastic:web:kmp", "1")`. + */ +export const KMP_FLAG_KEY = "meshtastic:web:kmp"; + +export function isKmpEnabled(): boolean { + try { + return globalThis.localStorage?.getItem(KMP_FLAG_KEY) === "1"; + } catch { + return false; + } +} diff --git a/apps/web/src/core/kmp/transport.test.ts b/apps/web/src/core/kmp/transport.test.ts new file mode 100644 index 000000000..d47dc7e9f --- /dev/null +++ b/apps/web/src/core/kmp/transport.test.ts @@ -0,0 +1,106 @@ +import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; +import { DeviceStatusEnum, type DeviceOutput, Protobuf } from "@meshtastic/sdk"; +import { describe, expect, it } from "vitest"; +import { FakeKmpClient, state } from "./fakeClient.ts"; +import { kmpTransport } from "./transport.ts"; + +async function readAll( + stream: ReadableStream, + count: number, +): Promise { + const reader = stream.getReader(); + const out: DeviceOutput[] = []; + while (out.length < count) { + const { value, done } = await reader.read(); + if (done) break; + out.push(value); + } + reader.releaseLock(); + return out; +} + +describe("kmpTransport", () => { + it("replays FromRadio frames from the SDK as packets", async () => { + const client = new FakeKmpClient(); + await client.connect(); + const transport = kmpTransport(client); + const myInfo = toBinary( + Protobuf.Mesh.FromRadioSchema, + create(Protobuf.Mesh.FromRadioSchema, { + payloadVariant: { + case: "myInfo", + value: { myNodeNum: 0x0a0b0c0d }, + }, + }), + ); + client.emitFrame(myInfo); + + const [status, packet] = await readAll(transport.fromDevice, 2); + expect(status).toEqual({ + type: "status", + data: { status: DeviceStatusEnum.DeviceConnected }, + }); + if (packet?.type !== "packet") throw new Error("expected a packet"); + const decoded = fromBinary(Protobuf.Mesh.FromRadioSchema, packet.data); + expect(decoded.payloadVariant.case).toBe("myInfo"); + }); + + it("writes ToRadio bytes through the SDK", async () => { + const client = new FakeKmpClient(); + await client.connect(); + const transport = kmpTransport(client); + const writer = transport.toDevice.getWriter(); + const bytes = new Uint8Array([1, 2, 3]); + await writer.write(bytes); + expect(client.sent).toEqual([bytes]); + }); + + it("rejects writes while the SDK is reconnecting", async () => { + const client = new FakeKmpClient(); + await client.connect(); + const transport = kmpTransport(client); + client.setState(state("reconnecting", { attempt: 2 })); + const writer = transport.toDevice.getWriter(); + await expect(writer.write(new Uint8Array([1]))).rejects.toMatchObject({ + name: "not-connected", + }); + }); + + it("maps SDK states to device status events", async () => { + const client = new FakeKmpClient(); + await client.connect(); + const transport = kmpTransport(client); + client.setState(state("reconnecting", { attempt: 1 })); + client.setState(state("configuring", { phase: "Stage1" })); + client.setState(state("connected")); + const events = await readAll(transport.fromDevice, 3); + expect( + events.map((e) => (e.type === "status" ? e.data.status : e.type)), + ).toEqual([ + DeviceStatusEnum.DeviceConnected, + DeviceStatusEnum.DeviceReconnecting, + DeviceStatusEnum.DeviceConnected, + ]); + }); + + it("disconnects the SDK client and closes the stream once", async () => { + const client = new FakeKmpClient(); + await client.connect(); + const transport = kmpTransport(client); + await transport.disconnect(); + await transport.disconnect(); + expect(client.disconnects).toHaveLength(2); + const reader = transport.fromDevice.getReader(); + const first = await reader.read(); + expect(first).toEqual({ + value: { + type: "status", + data: { status: DeviceStatusEnum.DeviceConnected }, + }, + done: false, + }); + const last = await reader.read(); + expect(last.done).toBe(true); + client.emitFrame(new Uint8Array([9])); + }); +}); diff --git a/apps/web/src/core/kmp/transport.ts b/apps/web/src/core/kmp/transport.ts new file mode 100644 index 000000000..b56bc2d85 --- /dev/null +++ b/apps/web/src/core/kmp/transport.ts @@ -0,0 +1,82 @@ +import type { ConnectionStateJs, MeshtasticClient } from "@meshtastic/sdk-kmp"; +import { + type DeviceOutput, + DeviceStatusEnum, + type Transport, +} from "@meshtastic/sdk"; + +function toDeviceStatus( + state: ConnectionStateJs, +): DeviceStatusEnum | undefined { + switch (state.kind) { + case "connected": + return DeviceStatusEnum.DeviceConnected; + case "reconnecting": + return DeviceStatusEnum.DeviceReconnecting; + case "disconnected": + return DeviceStatusEnum.DeviceDisconnected; + default: + return undefined; + } +} + +/** + * Presents a Kotlin SDK client as the TypeScript SDK's `Transport`, so the + * existing `MeshDevice` keeps feeding the stores while the Kotlin SDK owns + * the connection: every FromRadio frame the SDK receives is replayed here + * as bare protobuf bytes, and every ToRadio the web client writes goes + * through the SDK's send path. + */ +export function kmpTransport(client: MeshtasticClient): Transport { + let controller: ReadableStreamDefaultController | undefined; + let closed = false; + const unsubscribe: Array<() => void> = []; + + const close = (): void => { + if (closed) { + return; + } + closed = true; + for (const off of unsubscribe) { + off(); + } + controller?.close(); + }; + + const fromDevice = new ReadableStream({ + start(c) { + controller = c; + unsubscribe.push( + client.onFromRadio((bytes) => { + if (!closed) { + c.enqueue({ type: "packet", data: bytes }); + } + }), + client.onConnectionState((state) => { + const status = toDeviceStatus(state); + if (status !== undefined && !closed) { + c.enqueue({ type: "status", data: { status } }); + } + }), + ); + }, + cancel() { + close(); + }, + }); + + const toDevice = new WritableStream({ + write(chunk) { + client.sendRaw(chunk); + }, + }); + + return { + fromDevice, + toDevice, + async disconnect() { + close(); + await client.disconnect(); + }, + }; +} diff --git a/apps/web/src/core/stores/deviceStore/types.ts b/apps/web/src/core/stores/deviceStore/types.ts index 8dea18f09..7415fa584 100644 --- a/apps/web/src/core/stores/deviceStore/types.ts +++ b/apps/web/src/core/stores/deviceStore/types.ts @@ -53,7 +53,9 @@ export type Connection = { isDefault?: boolean; status: ConnectionStatus; error?: string; - errorKind?: "cert" | "network"; + errorKind?: "cert" | "network" | "lna-denied"; + /** The SDK's current reconnect attempt, while it is reconnecting. */ + reconnect?: { attempt: number; maxAttempts: number }; meshDeviceId?: number; /** * Node number of the radio this connection last reached, from the diff --git a/apps/web/src/pages/Connections/useConnections.kmp.test.ts b/apps/web/src/pages/Connections/useConnections.kmp.test.ts new file mode 100644 index 000000000..8bc7753c9 --- /dev/null +++ b/apps/web/src/pages/Connections/useConnections.kmp.test.ts @@ -0,0 +1,133 @@ +import { fromBinary } from "@bufbuild/protobuf"; +import { FakeKmpClient, state } from "@core/kmp/fakeClient.ts"; +import { KMP_FLAG_KEY } from "@core/kmp/flag.ts"; +import type { Connection } from "@app/core/stores/deviceStore/types"; +import { useDeviceStore } from "@core/stores"; +import { Protobuf } from "@meshtastic/sdk"; +import { act, renderHook } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { useConnections } from "./useConnections.ts"; + +const kmp = vi.hoisted(() => ({ + client: undefined as FakeKmpClient | undefined, + connectError: undefined as Error | undefined, +})); + +vi.mock("@core/sdkStorage.ts", () => ({ + getStorageDb: async () => { + throw new Error("no storage in tests"); + }, + coordinator: undefined, +})); + +vi.mock("@core/kmp/client.ts", async () => { + const { FakeKmpClient } = await import("@core/kmp/fakeClient.ts"); + return { + createHttpClient: async () => { + const client = new FakeKmpClient(); + if (kmp.connectError) { + const error = kmp.connectError; + client.connect = async () => { + throw error; + }; + } + kmp.client = client; + return client; + }, + }; +}); + +const saved = (id: number): Connection | undefined => + useDeviceStore.getState().savedConnections.find((c) => c.id === id); + +function named(name: string): Error { + const error = new Error(name); + error.name = name; + return error; +} + +describe("useConnections over the Kotlin SDK (HTTP)", () => { + beforeEach(() => { + localStorage.setItem(KMP_FLAG_KEY, "1"); + kmp.client = undefined; + kmp.connectError = undefined; + }); + afterEach(() => { + localStorage.removeItem(KMP_FLAG_KEY); + }); + + it("connects through the SDK and asks the radio for its config", async () => { + const { result } = renderHook(() => useConnections()); + const conn = result.current.addConnection({ + type: "http", + name: "Radio", + url: "http://192.168.1.10", + }); + + const ok = await act(() => result.current.connect(conn.id)); + expect(ok).toBe(true); + expect(saved(conn.id)?.status).toBe("configuring"); + const client = kmp.client; + if (!client) throw new Error("no client created"); + await vi.waitFor(() => { + const sent = client.sent.map((bytes) => + fromBinary(Protobuf.Mesh.ToRadioSchema, bytes), + ); + expect(sent.some((m) => m.payloadVariant.case === "wantConfigId")).toBe( + true, + ); + }); + + await act(() => result.current.disconnect(conn.id)); + expect(client.disconnects).toHaveLength(1); + expect(saved(conn.id)?.status).toBe("disconnected"); + }); + + it("shows the SDK's reconnect attempts and reports when they run out", async () => { + const { result } = renderHook(() => useConnections()); + const conn = result.current.addConnection({ + type: "http", + name: "Radio", + url: "http://192.168.1.10", + }); + await act(() => result.current.connect(conn.id)); + const client = kmp.client; + if (!client) throw new Error("no client created"); + + act(() => client.setState(state("reconnecting", { attempt: 3 }))); + expect(saved(conn.id)).toMatchObject({ + status: "connecting", + reconnect: { attempt: 3, maxAttempts: 10 }, + }); + + act(() => client.setState(state("connected"))); + expect(saved(conn.id)).toMatchObject({ + status: "configuring", + reconnect: undefined, + }); + + act(() => client.setState(state("reconnecting", { attempt: 1 }))); + act(() => client.setState(state("disconnected"))); + expect(saved(conn.id)).toMatchObject({ + status: "error", + errorKind: "network", + reconnect: undefined, + }); + }); + + it("marks a denied Local Network Access permission as a terminal error", async () => { + kmp.connectError = named("lna-denied"); + const { result } = renderHook(() => useConnections()); + const conn = result.current.addConnection({ + type: "http", + name: "Radio", + url: "http://192.168.1.10", + }); + const ok = await act(() => result.current.connect(conn.id)); + expect(ok).toBe(false); + expect(saved(conn.id)).toMatchObject({ + status: "error", + errorKind: "lna-denied", + }); + }); +}); diff --git a/apps/web/src/pages/Connections/useConnections.ts b/apps/web/src/pages/Connections/useConnections.ts index 5cf6dd52a..0e2c1d6d1 100644 --- a/apps/web/src/pages/Connections/useConnections.ts +++ b/apps/web/src/pages/Connections/useConnections.ts @@ -4,6 +4,14 @@ import { openTransport, probeConnection, } from "@app/core/connections/transports.ts"; +import { createHttpClient } from "@core/kmp/client.ts"; +import { + connectFailure, + reconnectAttempt, + toConnectionStatus, +} from "@core/kmp/connectionState.ts"; +import { isKmpEnabled } from "@core/kmp/flag.ts"; +import { kmpTransport } from "@core/kmp/transport.ts"; import { toast } from "@core/hooks/useToast.ts"; import { createLogger, @@ -11,6 +19,7 @@ import { FirmwareTooOldError, HandshakeTimeoutError, MIN_FIRMWARE_VERSION, + type Transport, } from "@meshtastic/sdk"; import { t } from "i18next"; @@ -33,6 +42,8 @@ import { useCallback, useEffect, useRef } from "react"; // - configSubscriptions: handshake status / reboot unsubscribers. const cachedTransports = new Map(); const configSubscriptions = new Map void>(); +// Kotlin SDK connection-state subscriptions for connections it owns. +const kmpSubscriptions = new Map void>(); // Handshake attempts per connection. A stalled handshake is retried by // reopening the transport with backoff, as the Android app does, instead of // re-sending want_config in the same session. @@ -86,6 +97,8 @@ export function useConnections() { { keepHandle = false }: { keepHandle?: boolean } = {}, ) => { log.debug("teardown: enter", { id }); + kmpSubscriptions.get(id)?.(); + kmpSubscriptions.delete(id); configSubscriptions.get(id)?.(); configSubscriptions.delete(id); @@ -148,7 +161,7 @@ export function useConnections() { const setupMeshDevice = useCallback( async ( id: ConnectionId, - transport: Awaited>["transport"], + transport: Transport, bluetoothDevice?: BluetoothDevice, serialPort?: SerialPort, ): Promise => { @@ -236,6 +249,10 @@ export function useConnections() { (s) => { if (s === DeviceStatusEnum.DeviceConfigured) markConfigured("device.status"); + // The Kotlin SDK reconnected the transport; the next handshake + // must be able to mark the connection configured again. + if (s === DeviceStatusEnum.DeviceReconnecting) + configuredHandled = false; }, ); // Catch-up: signal subscribe doesn't fire for the current value, so @@ -334,6 +351,84 @@ export function useConnections() { ], ); + /** + * Connects over the device HTTP API through the Kotlin SDK, which owns + * the handshake and reconnects. The existing MeshDevice is fed from the + * SDK's frames so the rest of the app is unchanged. + */ + const connectThroughKmp = useCallback( + async (id: ConnectionId, url: string, allowPrompt: boolean) => { + const client = await createHttpClient(url, allowPrompt); + let reconnecting = false; + kmpSubscriptions.get(id)?.(); + kmpSubscriptions.set( + id, + client.onConnectionState((state) => { + const saved = useDeviceStore + .getState() + .savedConnections.find((c) => c.id === id); + if (!saved) return; + const reconnect = reconnectAttempt(state); + if (reconnect) { + reconnecting = true; + log.warn("kmp: reconnecting", { id, ...reconnect }); + updateSavedConnection(id, { + status: "connecting", + reconnect, + error: undefined, + errorKind: undefined, + }); + return; + } + if (!reconnecting) return; + if (state.kind === "connected") { + reconnecting = false; + log.info("kmp: reconnected, re-running the handshake", { id }); + updateSavedConnection(id, { + status: "configuring", + reconnect: undefined, + }); + const device = saved.meshDeviceId + ? useDeviceStore.getState().getDevice(saved.meshDeviceId) + : undefined; + device?.connection?.configure().catch((error: unknown) => { + updateSavedConnection(id, connectFailure(error)); + }); + } else if (state.kind === "disconnected") { + reconnecting = false; + log.error("kmp: reconnect attempts exhausted", { id }); + updateSavedConnection(id, { + status: "error", + reconnect: undefined, + error: t("connections:errors.reconnectFailed", { + attempts: state.maxAttempts, + }), + errorKind: "network", + }); + } else { + updateSavedConnection(id, { status: toConnectionStatus(state) }); + } + }), + ); + try { + await client.connect(); + await setupMeshDevice(id, kmpTransport(client)); + return true; + } catch (error) { + log.error("kmp: connect failed", { + id, + name: error instanceof Error ? error.name : undefined, + message: error instanceof Error ? error.message : String(error), + }); + kmpSubscriptions.get(id)?.(); + kmpSubscriptions.delete(id); + updateSavedConnection(id, connectFailure(error)); + return false; + } + }, + [setupMeshDevice, updateSavedConnection], + ); + const connect = useCallback( async (id: ConnectionId, opts?: { allowPrompt?: boolean }) => { // Read from the live store, not the memoized `connections` closure: callers @@ -357,6 +452,9 @@ export function useConnections() { allowPrompt: !!opts?.allowPrompt, }); updateStatus(id, "connecting"); + if (conn.type === "http" && isKmpEnabled()) { + return connectThroughKmp(conn.id, conn.url, opts?.allowPrompt ?? false); + } try { const cached = cachedTransports.get(id); const result = await openTransport(conn, { @@ -402,7 +500,7 @@ export function useConnections() { return false; } }, - [updateStatus, setupMeshDevice], + [updateStatus, setupMeshDevice, connectThroughKmp], ); useEffect(() => { From 3aa33b2c4cc884b95e17e6dd5c0819fca44c7f1e Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 07:58:57 -0500 Subject: [PATCH 08/49] refactor(web): take connection state and reconnects from the Kotlin SDK HTTP connections always go through @meshtastic/sdk-kmp now; the TS TransportHTTP path, the web-side handshake retry (reopen with backoff), the pending-retry bookkeeping and the store's connectionPhase are gone. The SDK's own heartbeat and liveness watchdog replace the TS heartbeat for connections it owns. The connecting overlay and the drawer's status pill show the SDK's reconnect attempt n of 10, and useDeviceConnected reads the device status the SDK drives instead of a web-side phase. --- .../public/i18n/locales/en/connections.json | 4 + .../src/components/ConnectingOverlay.test.tsx | 9 ++ apps/web/src/components/ConnectingOverlay.tsx | 18 ++- .../ConnectionsList.test.tsx | 14 ++ .../ConnectionsDrawer/ConnectionsList.tsx | 19 ++- .../SettingsPages/useDeviceConnected.ts | 8 +- apps/web/src/core/connections/sdkClient.ts | 10 +- apps/web/src/core/connections/transports.ts | 26 +--- apps/web/src/core/kmp/flag.ts | 13 -- .../stores/deviceStore/deviceStore.mock.ts | 2 - apps/web/src/core/stores/deviceStore/index.ts | 19 --- .../Connections/useConnections.kmp.test.ts | 14 +- .../src/pages/Connections/useConnections.ts | 137 +++++------------- 13 files changed, 111 insertions(+), 182 deletions(-) delete mode 100644 apps/web/src/core/kmp/flag.ts diff --git a/apps/web/public/i18n/locales/en/connections.json b/apps/web/public/i18n/locales/en/connections.json index fe85df795..b0c5b028e 100644 --- a/apps/web/public/i18n/locales/en/connections.json +++ b/apps/web/public/i18n/locales/en/connections.json @@ -73,6 +73,7 @@ }, "phase": { "connecting": "Opening transport…", + "reconnecting": "Reconnect attempt {{attempt}} of {{max}}…", "configuring": "Streaming configuration…" }, "chip": { @@ -84,6 +85,9 @@ "stuckHint": "Taking longer than usual. The device may be in CLI / bootloader mode, or the firmware isn't responding to config requests.", "cancel": "Cancel" }, + "status": { + "reconnecting": "reconnecting {{attempt}}/{{max}}" + }, "errors": { "certNotTrusted": "Self-signed certificate not trusted. Open {{url}} in a new tab, accept the security warning, then return here and try again.", "httpsNotReachable": "HTTPS endpoint not reachable. Check that the device is online.", diff --git a/apps/web/src/components/ConnectingOverlay.test.tsx b/apps/web/src/components/ConnectingOverlay.test.tsx index 8937368ea..8b47f0708 100644 --- a/apps/web/src/components/ConnectingOverlay.test.tsx +++ b/apps/web/src/components/ConnectingOverlay.test.tsx @@ -44,6 +44,15 @@ describe("ConnectingOverlay", () => { ).toBeInTheDocument(); }); + it("shows the SDK's reconnect attempt", () => { + savedConnections = [ + connection({ reconnect: { attempt: 3, maxAttempts: 10 } }), + ]; + render(); + expect(screen.getByRole("heading", { name: "Reconnecting" })).toBeDefined(); + expect(screen.getByText("Reconnect attempt 3 of 10…")).toBeDefined(); + }); + it("shows nothing when no connection is in progress", () => { savedConnections = [connection({ status: "configured" })]; const { container } = render(); diff --git a/apps/web/src/components/ConnectingOverlay.tsx b/apps/web/src/components/ConnectingOverlay.tsx index f3fb9f093..2580c8eb0 100644 --- a/apps/web/src/components/ConnectingOverlay.tsx +++ b/apps/web/src/components/ConnectingOverlay.tsx @@ -79,14 +79,20 @@ export const ConnectingOverlay = (): ReactElement | null => { const isConnecting = active.status === "connecting"; // A connection that has been connected before is being reconnected. const title = - active.lastConnectedAt !== undefined + active.reconnect || active.lastConnectedAt !== undefined ? t("overlay.title.reconnecting") : t("overlay.title.connecting"); - const phaseLabel = isConnecting - ? t("overlay.phase.connecting", { defaultValue: "Opening transport…" }) - : t("overlay.phase.configuring", { - defaultValue: "Streaming configuration…", - }); + // The SDK reports which reconnect attempt it is on. + const phaseLabel = active.reconnect + ? t("overlay.phase.reconnecting", { + attempt: active.reconnect.attempt, + max: active.reconnect.maxAttempts, + }) + : isConnecting + ? t("overlay.phase.connecting", { defaultValue: "Opening transport…" }) + : t("overlay.phase.configuring", { + defaultValue: "Streaming configuration…", + }); return (

diff --git a/apps/web/src/components/ConnectionsDrawer/ConnectionsList.test.tsx b/apps/web/src/components/ConnectionsDrawer/ConnectionsList.test.tsx index 0d0d86655..dddfc6130 100644 --- a/apps/web/src/components/ConnectionsDrawer/ConnectionsList.test.tsx +++ b/apps/web/src/components/ConnectionsDrawer/ConnectionsList.test.tsx @@ -72,6 +72,20 @@ describe("ConnectionsList inline delete", () => { }); }); + it("shows the SDK's reconnect attempt on the status pill", () => { + connectionsMock.connections = [ + { + ...http(1, "Alpha"), + status: "connecting", + reconnect: { attempt: 2, maxAttempts: 10 }, + }, + ]; + render(); + expect( + within(row("Alpha")).getAllByText("reconnecting 2/10").length, + ).toBeGreaterThan(0); + }); + it("swaps the row's actions for a strip and focuses Cancel", async () => { render(); expect(within(row("Bravo")).getByRole("button", { name: "Connect" })); diff --git a/apps/web/src/components/ConnectionsDrawer/ConnectionsList.tsx b/apps/web/src/components/ConnectionsDrawer/ConnectionsList.tsx index 08b7c90e4..c18fafd71 100644 --- a/apps/web/src/components/ConnectionsDrawer/ConnectionsList.tsx +++ b/apps/web/src/components/ConnectionsDrawer/ConnectionsList.tsx @@ -260,13 +260,23 @@ const statusDot: Record = { function StatusPill({ status, + reconnect, className, }: { status: Connection["status"]; + reconnect?: Connection["reconnect"]; className?: string; }) { + const { t } = useTranslation("connections"); const tone = statusTone(status); - const label = tone === "connected" ? "connected" : status; + const label = reconnect + ? t("status.reconnecting", { + attempt: reconnect.attempt, + max: reconnect.maxAttempts, + }) + : tone === "connected" + ? "connected" + : status; return (

{formatConnectionSubtext(connection)}

- +
diff --git a/apps/web/src/components/PageComponents/SettingsPages/useDeviceConnected.ts b/apps/web/src/components/PageComponents/SettingsPages/useDeviceConnected.ts index b4237d57c..3a870aefe 100644 --- a/apps/web/src/components/PageComponents/SettingsPages/useDeviceConnected.ts +++ b/apps/web/src/components/PageComponents/SettingsPages/useDeviceConnected.ts @@ -1,7 +1,11 @@ import { useDevice } from "@core/stores"; +import { Types } from "@meshtastic/sdk"; /** True once the active node is connected and configured. */ export function useDeviceConnected(): boolean { - const { connection, connectionPhase } = useDevice(); - return connection !== undefined && connectionPhase === "configured"; + const { connection, status } = useDevice(); + return ( + connection !== undefined && + status === Types.DeviceStatusEnum.DeviceConfigured + ); } diff --git a/apps/web/src/core/connections/sdkClient.ts b/apps/web/src/core/connections/sdkClient.ts index c1e9d05f4..cad03723f 100644 --- a/apps/web/src/core/connections/sdkClient.ts +++ b/apps/web/src/core/connections/sdkClient.ts @@ -7,17 +7,9 @@ import { } from "@meshtastic/sdk-storage-sqlocal/chat"; import { SqlocalNodesRepository } from "@meshtastic/sdk-storage-sqlocal/nodes"; import { SqlocalTelemetryRepository } from "@meshtastic/sdk-storage-sqlocal/telemetry"; -import type { TransportHTTP } from "@meshtastic/transport-http"; -import type { TransportWebBluetooth } from "@meshtastic/transport-web-bluetooth"; -import type { TransportWebSerial } from "@meshtastic/transport-web-serial"; const log = createLogger("sdkClient"); -export type AnyTransport = - | TransportHTTP - | TransportWebBluetooth - | TransportWebSerial; - const CHAT_RETENTION = { maxPerBucket: 1000, olderThanMs: 1000 * 60 * 60 * 24 * 90, @@ -63,6 +55,7 @@ export async function buildMeshDevice( deviceId: number, transport: Transport, nodeNum?: number, + { heartbeat = true }: { heartbeat?: boolean } = {}, ): Promise<{ meshDevice: MeshDevice; persistent: boolean }> { log.debug("buildMeshDevice: enter", { connectionId, deviceId, nodeNum }); const scope = nodeNum ?? UNKNOWN_NODE_SCOPE; @@ -119,6 +112,7 @@ export async function buildMeshDevice( const meshDevice = new MeshDevice(transport, { configId: deviceId, + heartbeatIntervalMs: heartbeat ? undefined : false, storageScope: "node", storageNodeNum: nodeNum, chat: diff --git a/apps/web/src/core/connections/transports.ts b/apps/web/src/core/connections/transports.ts index 456ed987b..f7057e658 100644 --- a/apps/web/src/core/connections/transports.ts +++ b/apps/web/src/core/connections/transports.ts @@ -1,7 +1,6 @@ import type { Connection } from "@core/stores/deviceStore/types"; import { httpErrorMessage, testHttpReachable } from "@pages/Connections/utils"; -import { createLogger } from "@meshtastic/sdk"; -import { TransportHTTP } from "@meshtastic/transport-http"; +import { createLogger, type Transport } from "@meshtastic/sdk"; import { BluetoothConnectError, TransportWebBluetooth, @@ -11,7 +10,6 @@ import { TransportWebSerial, } from "@meshtastic/transport-web-serial"; import { Result } from "better-result"; -import type { AnyTransport } from "./sdkClient.ts"; const log = createLogger("transports"); @@ -30,8 +28,11 @@ export interface OpenTransportOptions { cachedSerialPort?: SerialPort; } +/** HTTP connections are opened by the Kotlin SDK (see `core/kmp`). */ +export type BrowserConnection = Exclude; + export interface OpenTransportResult { - transport: AnyTransport; + transport: Transport; /** BT device (when type=bluetooth) so caller can cache for cleanup + reconnect. */ bluetoothDevice?: BluetoothDevice; /** Serial port (when type=serial) so caller can cache for cleanup + reconnect. */ @@ -39,12 +40,10 @@ export interface OpenTransportResult { } export async function openTransport( - conn: Connection, + conn: BrowserConnection, opts: OpenTransportOptions = {}, ): Promise { switch (conn.type) { - case "http": - return openHttp(conn); case "bluetooth": return openBluetooth(conn, opts); case "serial": @@ -59,19 +58,6 @@ export async function openTransport( } } -async function openHttp( - conn: Connection & { type: "http"; url: string }, -): Promise { - const { reachable, certError } = await testHttpReachable(conn.url); - if (!reachable) { - throw new Error(httpErrorMessage(conn.url, certError)); - } - const url = new URL(conn.url); - const isTLS = url.protocol === "https:"; - const transport = await TransportHTTP.create(url.host, isTLS); - return { transport }; -} - async function openBluetooth( conn: Connection & { type: "bluetooth"; diff --git a/apps/web/src/core/kmp/flag.ts b/apps/web/src/core/kmp/flag.ts deleted file mode 100644 index df6be423f..000000000 --- a/apps/web/src/core/kmp/flag.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * Opt-in for connecting over HTTP through the Kotlin SDK while the - * migration lands: `localStorage.setItem("meshtastic:web:kmp", "1")`. - */ -export const KMP_FLAG_KEY = "meshtastic:web:kmp"; - -export function isKmpEnabled(): boolean { - try { - return globalThis.localStorage?.getItem(KMP_FLAG_KEY) === "1"; - } catch { - return false; - } -} diff --git a/apps/web/src/core/stores/deviceStore/deviceStore.mock.ts b/apps/web/src/core/stores/deviceStore/deviceStore.mock.ts index 864653a53..237214348 100644 --- a/apps/web/src/core/stores/deviceStore/deviceStore.mock.ts +++ b/apps/web/src/core/stores/deviceStore/deviceStore.mock.ts @@ -16,7 +16,6 @@ export const mockDeviceStore: Device = { id: 0, myNodeNum: 123456, status: 5 as const, - connectionPhase: "disconnected", connectionId: null, channels: new Map(), config: {} as Protobuf.LocalOnly.LocalConfig, @@ -51,7 +50,6 @@ export const mockDeviceStore: Device = { neighborInfo: new Map(), setStatus: vi.fn(), - setConnectionPhase: vi.fn(), setConnectionId: vi.fn(), setConfig: vi.fn(), setModuleConfig: vi.fn(), diff --git a/apps/web/src/core/stores/deviceStore/index.ts b/apps/web/src/core/stores/deviceStore/index.ts index 5469e40ff..4142efdc6 100644 --- a/apps/web/src/core/stores/deviceStore/index.ts +++ b/apps/web/src/core/stores/deviceStore/index.ts @@ -42,16 +42,9 @@ type DeviceData = { waypoints: WaypointWithMetadata[]; neighborInfo: Map; }; -export type ConnectionPhase = - | "disconnected" - | "connecting" - | "configuring" - | "configured"; - export interface Device extends DeviceData { // Ephemeral state (not persisted) status: Types.DeviceStatusEnum; - connectionPhase: ConnectionPhase; connectionId: ConnectionId | null; channels: Map; config: Protobuf.LocalOnly.LocalConfig; @@ -66,7 +59,6 @@ export interface Device extends DeviceData { clientNotifications: Protobuf.Mesh.ClientNotification[]; setStatus: (status: Types.DeviceStatusEnum) => void; - setConnectionPhase: (phase: ConnectionPhase) => void; setConnectionId: (id: ConnectionId | null) => void; setConfig: (config: Protobuf.Config.Config) => void; setModuleConfig: (config: Protobuf.ModuleConfig.ModuleConfig) => void; @@ -170,7 +162,6 @@ function deviceFactory( neighborInfo, status: Types.DeviceStatusEnum.DeviceDisconnected, - connectionPhase: "disconnected", connectionId: null, channels: new Map(), config: create(Protobuf.LocalOnly.LocalConfigSchema), @@ -211,16 +202,6 @@ function deviceFactory( }), ); }, - setConnectionPhase: (phase: ConnectionPhase) => { - set( - produce((draft) => { - const device = draft.devices.get(id); - if (device) { - device.connectionPhase = phase; - } - }), - ); - }, setConnectionId: (connectionId: ConnectionId | null) => { set( produce((draft) => { diff --git a/apps/web/src/pages/Connections/useConnections.kmp.test.ts b/apps/web/src/pages/Connections/useConnections.kmp.test.ts index 8bc7753c9..b9d226346 100644 --- a/apps/web/src/pages/Connections/useConnections.kmp.test.ts +++ b/apps/web/src/pages/Connections/useConnections.kmp.test.ts @@ -1,17 +1,15 @@ import { fromBinary } from "@bufbuild/protobuf"; import { FakeKmpClient, state } from "@core/kmp/fakeClient.ts"; -import { KMP_FLAG_KEY } from "@core/kmp/flag.ts"; import type { Connection } from "@app/core/stores/deviceStore/types"; import { useDeviceStore } from "@core/stores"; import { Protobuf } from "@meshtastic/sdk"; import { act, renderHook } from "@testing-library/react"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { useConnections } from "./useConnections.ts"; -const kmp = vi.hoisted(() => ({ - client: undefined as FakeKmpClient | undefined, - connectError: undefined as Error | undefined, -})); +const kmp = vi.hoisted( + (): { client?: FakeKmpClient; connectError?: Error } => ({}), +); vi.mock("@core/sdkStorage.ts", () => ({ getStorageDb: async () => { @@ -48,13 +46,9 @@ function named(name: string): Error { describe("useConnections over the Kotlin SDK (HTTP)", () => { beforeEach(() => { - localStorage.setItem(KMP_FLAG_KEY, "1"); kmp.client = undefined; kmp.connectError = undefined; }); - afterEach(() => { - localStorage.removeItem(KMP_FLAG_KEY); - }); it("connects through the SDK and asks the radio for its config", async () => { const { result } = renderHook(() => useConnections()); diff --git a/apps/web/src/pages/Connections/useConnections.ts b/apps/web/src/pages/Connections/useConnections.ts index 0e2c1d6d1..4c27d3b88 100644 --- a/apps/web/src/pages/Connections/useConnections.ts +++ b/apps/web/src/pages/Connections/useConnections.ts @@ -10,14 +10,12 @@ import { reconnectAttempt, toConnectionStatus, } from "@core/kmp/connectionState.ts"; -import { isKmpEnabled } from "@core/kmp/flag.ts"; import { kmpTransport } from "@core/kmp/transport.ts"; import { toast } from "@core/hooks/useToast.ts"; import { createLogger, DeviceStatusEnum, FirmwareTooOldError, - HandshakeTimeoutError, MIN_FIRMWARE_VERSION, type Transport, } from "@meshtastic/sdk"; @@ -35,7 +33,7 @@ import { meshRegistry } from "@core/meshRegistry.ts"; import { useAppStore, useDeviceStore } from "@core/stores"; import { subscribeAll } from "@core/subscriptions.ts"; import { randId } from "@core/utils/randId.ts"; -import { useCallback, useEffect, useRef } from "react"; +import { useCallback } from "react"; // Per-connection out-of-band handles tracked outside Zustand: // - cachedTransports: held BT device / serial port for reconnect + cleanup. @@ -44,18 +42,6 @@ const cachedTransports = new Map(); const configSubscriptions = new Map void>(); // Kotlin SDK connection-state subscriptions for connections it owns. const kmpSubscriptions = new Map void>(); -// Handshake attempts per connection. A stalled handshake is retried by -// reopening the transport with backoff, as the Android app does, instead of -// re-sending want_config in the same session. -const handshakeAttempts = new Map(); -const HANDSHAKE_RETRY_DELAYS_MS = [2_000, 4_000]; -// The pending retry per connection; disconnect or removal cancels it. -const pendingRetries = new Map(); - -const cancelHandshakeRetry = (id: ConnectionId): void => { - pendingRetries.delete(id); - handshakeAttempts.delete(id); -}; export function useConnections() { const connections = useDeviceStore((s) => s.savedConnections); @@ -68,10 +54,6 @@ export function useConnections() { const { addDevice } = useDeviceStore(); const { setSelectedDevice } = useAppStore(); const selectedDeviceId = useAppStore((s) => s.selectedDeviceId); - // Set below once connect() exists; used by setupMeshDevice to retry. - const retryHandshakeRef = useRef< - ((id: ConnectionId, delayMs: number) => Promise) | undefined - >(undefined); const updateStatus = useCallback( ( @@ -90,45 +72,37 @@ export function useConnections() { [updateSavedConnection], ); - const teardown = useCallback( - async ( - id: ConnectionId, - conn?: Connection, - { keepHandle = false }: { keepHandle?: boolean } = {}, - ) => { - log.debug("teardown: enter", { id }); - kmpSubscriptions.get(id)?.(); - kmpSubscriptions.delete(id); - configSubscriptions.get(id)?.(); - configSubscriptions.delete(id); + const teardown = useCallback(async (id: ConnectionId, conn?: Connection) => { + log.debug("teardown: enter", { id }); + kmpSubscriptions.get(id)?.(); + kmpSubscriptions.delete(id); + configSubscriptions.get(id)?.(); + configSubscriptions.delete(id); - if (conn?.meshDeviceId) { - const device = useDeviceStore.getState().getDevice(conn.meshDeviceId); - try { - // Await the underlying transport's close so the port is fully - // released before the user clicks reconnect — otherwise port.open() - // can race the close and throw "port already open". - await device?.connection?.disconnect(); - log.debug("teardown: transport disconnect awaited"); - } catch (e) { - const err = e as Error; - log.warn("teardown: transport disconnect threw", { - name: err?.name, - message: err?.message, - }); - } + if (conn?.meshDeviceId) { + const device = useDeviceStore.getState().getDevice(conn.meshDeviceId); + try { + // Await the underlying transport's close so the port is fully + // released before the user clicks reconnect — otherwise port.open() + // can race the close and throw "port already open". + await device?.connection?.disconnect(); + log.debug("teardown: transport disconnect awaited"); + } catch (e) { + const err = e as Error; + log.warn("teardown: transport disconnect threw", { + name: err?.name, + message: err?.message, + }); } - closeTransport(cachedTransports.get(id)); - if (!keepHandle) cachedTransports.delete(id); - log.debug("teardown: done", { id }); - }, - [], - ); + } + closeTransport(cachedTransports.get(id)); + cachedTransports.delete(id); + log.debug("teardown: done", { id }); + }, []); const removeConnection = useCallback( async (id: ConnectionId) => { const conn = connections.find((c) => c.id === id); - cancelHandshakeRetry(id); await teardown(id, conn); if (conn?.meshDeviceId) { try { @@ -162,6 +136,7 @@ export function useConnections() { async ( id: ConnectionId, transport: Transport, + { sdkOwnsConnection = false }: { sdkOwnsConnection?: boolean } = {}, bluetoothDevice?: BluetoothDevice, serialPort?: SerialPort, ): Promise => { @@ -179,7 +154,6 @@ export function useConnections() { // OPFS DB open which can take a beat (or stall under multi-tab // contention); we don't want the UI looking stuck at "connecting" // while persistence is spinning up. - device.setConnectionPhase("configuring"); updateStatus(id, "configuring"); log.debug("setupMeshDevice: building MeshDevice", { id, deviceId }); @@ -193,6 +167,7 @@ export function useConnections() { deviceId, transport, nodeNum, + { heartbeat: !sdkOwnsConnection }, ); log.debug("setupMeshDevice: MeshDevice built", { id, persistent }); if (!persistent) { @@ -228,9 +203,7 @@ export function useConnections() { const markConfigured = (source: string): void => { if (configuredHandled) return; configuredHandled = true; - handshakeAttempts.delete(id); log.info("connect transitioned to configured", { id, source }); - device.setConnectionPhase("configured"); updateStatus(id, "configured"); const client = meshDevice.meshClient; if (client.device.firmwareSupport.value === "shouldUpdate") { @@ -272,7 +245,6 @@ export function useConnections() { const unsubRebooted = meshDevice.events.onRebooted.subscribe(() => { log.info("device rebooted — re-entering configuring", { id }); configuredHandled = false; - device.setConnectionPhase("configuring"); updateStatus(id, "configuring"); }); @@ -310,21 +282,6 @@ export function useConnections() { name: e?.name, message: e?.message, }); - if (error instanceof HandshakeTimeoutError) { - const attempt = handshakeAttempts.get(id) ?? 0; - const delayMs = HANDSHAKE_RETRY_DELAYS_MS[attempt]; - if (delayMs !== undefined && retryHandshakeRef.current) { - handshakeAttempts.set(id, attempt + 1); - log.warn("handshake stalled, reopening the transport", { - id, - attempt: attempt + 1, - delayMs, - }); - void retryHandshakeRef.current(id, delayMs); - return; - } - } - handshakeAttempts.delete(id); updateStatus( id, "error", @@ -412,7 +369,9 @@ export function useConnections() { ); try { await client.connect(); - await setupMeshDevice(id, kmpTransport(client)); + await setupMeshDevice(id, kmpTransport(client), { + sdkOwnsConnection: true, + }); return true; } catch (error) { log.error("kmp: connect failed", { @@ -452,7 +411,7 @@ export function useConnections() { allowPrompt: !!opts?.allowPrompt, }); updateStatus(id, "connecting"); - if (conn.type === "http" && isKmpEnabled()) { + if (conn.type === "http") { return connectThroughKmp(conn.id, conn.url, opts?.allowPrompt ?? false); } try { @@ -472,6 +431,7 @@ export function useConnections() { await setupMeshDevice( id, result.transport, + {}, result.bluetoothDevice, result.serialPort, ); @@ -503,40 +463,17 @@ export function useConnections() { [updateStatus, setupMeshDevice, connectThroughKmp], ); - useEffect(() => { - retryHandshakeRef.current = async (id, delayMs) => { - const token = Symbol(); - pendingRetries.set(id, token); - const conn = useDeviceStore - .getState() - .savedConnections.find((c) => c.id === id); - // Keep the port or BT device: rediscovering it can need a prompt. - await teardown(id, conn, { keepHandle: true }); - await new Promise((r) => setTimeout(r, delayMs)); - if (pendingRetries.get(id) !== token) return; - pendingRetries.delete(id); - // connect() skips configured/connected connections; this one is still - // "configuring", so it reopens the transport and runs a fresh handshake. - await connect(id); - }; - return () => { - retryHandshakeRef.current = undefined; - }; - }, [connect, teardown]); - const disconnect = useCallback( async (id: ConnectionId) => { const conn = connections.find((c) => c.id === id); if (!conn) return; - cancelHandshakeRetry(id); try { await teardown(id, conn); if (conn.meshDeviceId) { - const device = useDeviceStore.getState().getDevice(conn.meshDeviceId); - if (device) { - device.setConnectionId(null); - device.setConnectionPhase("disconnected"); - } + useDeviceStore + .getState() + .getDevice(conn.meshDeviceId) + ?.setConnectionId(null); } } finally { updateSavedConnection(id, { status: "disconnected", error: undefined }); From 1091b7535f724b2a0d1ae7697760526853a177e3 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 08:06:09 -0500 Subject: [PATCH 09/49] refactor(web): import Protobuf and Types through core/protobuf --- apps/web/package.json | 2 ++ apps/web/src/components/DeviceInfoPanel.tsx | 2 +- .../ClientNotificationDialog/ClientNotificationDialog.tsx | 2 +- apps/web/src/components/Dialog/ImportDialog.tsx | 2 +- apps/web/src/components/Dialog/LocationResponseDialog.tsx | 2 +- .../Dialog/LockdownDialog/LockdownDialog.test.tsx | 2 +- .../src/components/Dialog/LockdownDialog/LockdownDialog.tsx | 2 +- .../Dialog/NodeDetailsDialog/NodeDetailsDialog.tsx | 2 +- .../Dialog/NodeDetailsDialog/NodeTelemetry.test.tsx | 3 ++- apps/web/src/components/Dialog/QRDialog.tsx | 2 +- apps/web/src/components/Dialog/TracerouteResponseDialog.tsx | 2 +- .../src/components/PageComponents/Channels/BeaconOffers.tsx | 3 ++- .../src/components/PageComponents/Channels/ChannelCard.tsx | 2 +- .../web/src/components/PageComponents/Channels/Channels.tsx | 3 ++- .../PageComponents/Channels/EditChannelDialog.test.tsx | 2 +- .../PageComponents/Channels/EditChannelDialog.tsx | 2 +- .../PageComponents/Channels/channelStaging.test.ts | 2 +- .../components/PageComponents/Channels/channelStaging.ts | 2 +- .../components/PageComponents/Map/Layers/HeatmapLayer.tsx | 2 +- .../src/components/PageComponents/Map/Layers/NodesLayer.tsx | 2 +- .../components/PageComponents/Map/Layers/PrecisionLayer.tsx | 2 +- .../src/components/PageComponents/Map/Layers/SNRLayer.tsx | 2 +- .../components/PageComponents/Map/Layers/WaypointLayer.tsx | 2 +- .../src/components/PageComponents/Map/Popups/NodeDetail.tsx | 2 +- .../components/PageComponents/Map/Popups/WaypointDetail.tsx | 2 +- apps/web/src/components/PageComponents/Map/cluster.ts | 2 +- .../PageComponents/Messages/MessageDiagnostics.tsx | 2 +- .../components/PageComponents/Messages/MessageItem.test.tsx | 2 +- .../src/components/PageComponents/Messages/MessageItem.tsx | 2 +- .../components/PageComponents/Messages/TraceRoute.test.tsx | 2 +- .../src/components/PageComponents/Messages/TraceRoute.tsx | 2 +- .../PageComponents/ModuleConfig/AmbientLighting.tsx | 2 +- .../src/components/PageComponents/ModuleConfig/Audio.tsx | 2 +- .../PageComponents/ModuleConfig/CannedMessage.tsx | 3 ++- .../PageComponents/ModuleConfig/DetectionSensor.tsx | 2 +- .../PageComponents/ModuleConfig/ExternalNotification.tsx | 2 +- .../components/PageComponents/ModuleConfig/MQTT.test.tsx | 2 +- .../web/src/components/PageComponents/ModuleConfig/MQTT.tsx | 2 +- .../components/PageComponents/ModuleConfig/MeshBeacon.tsx | 2 +- .../PageComponents/ModuleConfig/MeshBeaconTargets.tsx | 2 +- .../components/PageComponents/ModuleConfig/NeighborInfo.tsx | 2 +- .../components/PageComponents/ModuleConfig/Paxcounter.tsx | 2 +- .../components/PageComponents/ModuleConfig/RangeTest.tsx | 2 +- .../PageComponents/ModuleConfig/RemoteHardware.tsx | 2 +- .../PageComponents/ModuleConfig/RemoteHardwarePins.tsx | 2 +- .../src/components/PageComponents/ModuleConfig/Serial.tsx | 2 +- .../components/PageComponents/ModuleConfig/StoreForward.tsx | 2 +- apps/web/src/components/PageComponents/ModuleConfig/Tak.tsx | 2 +- .../PageComponents/ModuleConfig/TakTeamSwatches.tsx | 2 +- .../components/PageComponents/ModuleConfig/Telemetry.tsx | 2 +- .../PageComponents/ModuleConfig/useStagedAdminString.ts | 2 +- .../src/components/PageComponents/Settings/Bluetooth.tsx | 2 +- .../src/components/PageComponents/Settings/Device/index.tsx | 2 +- .../PageComponents/Settings/DeviceConfig.test.tsx | 2 +- apps/web/src/components/PageComponents/Settings/Display.tsx | 2 +- .../src/components/PageComponents/Settings/LoRa.test.tsx | 2 +- apps/web/src/components/PageComponents/Settings/LoRa.tsx | 3 ++- .../PageComponents/Settings/Network/Network.test.tsx | 2 +- .../components/PageComponents/Settings/Network/index.tsx | 2 +- .../components/PageComponents/Settings/Position.test.tsx | 2 +- .../web/src/components/PageComponents/Settings/Position.tsx | 2 +- .../src/components/PageComponents/Settings/Power.test.tsx | 2 +- apps/web/src/components/PageComponents/Settings/Power.tsx | 2 +- .../Settings/Security/LockdownSection.test.tsx | 2 +- .../PageComponents/Settings/Security/LockdownSection.tsx | 2 +- .../PageComponents/Settings/Security/Security.test.tsx | 2 +- .../PageComponents/Settings/Security/Security.tsx | 2 +- .../src/components/PageComponents/Settings/User.test.tsx | 2 +- apps/web/src/components/PageComponents/Settings/User.tsx | 3 ++- .../PageComponents/SettingsPages/useDeviceConnected.ts | 2 +- apps/web/src/components/generic/Filter/FilterControl.tsx | 2 +- .../web/src/components/generic/Filter/useFilterNode.test.ts | 2 +- apps/web/src/components/generic/Filter/useFilterNode.ts | 2 +- apps/web/src/components/generic/NodeTrustIndicators.tsx | 3 ++- apps/web/src/core/dto/NodeNumToNodeInfoDTO.ts | 2 +- apps/web/src/core/dto/PacketToMessageDTO.test.ts | 2 +- apps/web/src/core/dto/PacketToMessageDTO.ts | 2 +- apps/web/src/core/hooks/useChatAsLegacyMessages.test.ts | 3 +-- apps/web/src/core/hooks/useChatAsLegacyMessages.ts | 3 ++- apps/web/src/core/hooks/useChatLegacy.ts | 2 +- apps/web/src/core/hooks/useDeviceCapabilities.ts | 3 ++- apps/web/src/core/hooks/useLockdown.ts | 3 ++- apps/web/src/core/hooks/useMapFitting.ts | 2 +- apps/web/src/core/hooks/useNewNodeNum.ts | 2 +- apps/web/src/core/hooks/useNodesAsProto.ts | 2 +- apps/web/src/core/hooks/useNodesLegacy.ts | 2 +- apps/web/src/core/kmp/transport.test.ts | 3 ++- apps/web/src/core/protobuf.ts | 2 ++ apps/web/src/core/stores/deviceStore/deviceStore.mock.ts | 2 +- apps/web/src/core/stores/deviceStore/deviceStore.test.ts | 2 +- apps/web/src/core/stores/deviceStore/index.ts | 3 ++- apps/web/src/core/stores/deviceStore/types.ts | 2 +- apps/web/src/core/stores/messageStore/index.ts | 2 +- apps/web/src/core/stores/messageStore/types.ts | 2 +- apps/web/src/core/subscriptions.ts | 3 ++- apps/web/src/core/utils/beaconJoin.test.ts | 2 +- apps/web/src/core/utils/beaconJoin.ts | 2 +- apps/web/src/core/utils/channelUrl.ts | 2 +- apps/web/src/core/utils/cleanNodes.test.ts | 3 ++- apps/web/src/core/utils/excludedModules.test.ts | 2 +- apps/web/src/core/utils/excludedModules.ts | 2 +- apps/web/src/core/utils/logRecords.test.ts | 2 +- apps/web/src/core/utils/logRecords.ts | 2 +- apps/web/src/core/utils/loraPresets.test.ts | 2 +- apps/web/src/core/utils/loraPresets.ts | 2 +- apps/web/src/core/utils/messageStatus.test.ts | 2 +- apps/web/src/core/utils/messageStatus.ts | 2 +- apps/web/src/core/utils/profileExport.test.ts | 2 +- apps/web/src/core/utils/profileExport.ts | 2 +- apps/web/src/core/utils/signalQuality.test.ts | 2 +- apps/web/src/core/utils/signalQuality.ts | 2 +- apps/web/src/core/utils/telemetry.test.ts | 3 ++- apps/web/src/pages/Connections/useConnections.kmp.test.ts | 2 +- apps/web/src/pages/Connections/useConnections.test.ts | 3 ++- apps/web/src/pages/Map/index.tsx | 3 ++- apps/web/src/pages/Messages.tsx | 2 +- apps/web/src/pages/Nodes/index.tsx | 2 +- apps/web/src/pages/Settings/BackupRestore.tsx | 3 ++- apps/web/src/pages/Settings/DebugPanel.tsx | 2 +- apps/web/src/pages/Settings/DeviceConfig.tsx | 2 +- apps/web/src/pages/Settings/ModuleConfig.tsx | 2 +- apps/web/src/tests/renderSettingsForm.tsx | 3 ++- apps/web/src/validation/config/bluetooth.test.ts | 2 +- apps/web/src/validation/config/bluetooth.ts | 2 +- apps/web/src/validation/config/device.test.ts | 2 +- apps/web/src/validation/config/device.ts | 2 +- apps/web/src/validation/config/display.ts | 2 +- apps/web/src/validation/config/lora.test.ts | 2 +- apps/web/src/validation/config/lora.ts | 2 +- apps/web/src/validation/config/network.test.ts | 2 +- apps/web/src/validation/config/network.ts | 2 +- apps/web/src/validation/config/position.ts | 2 +- apps/web/src/validation/config/power.test.ts | 2 +- apps/web/src/validation/config/power.ts | 2 +- apps/web/src/validation/config/security.test.ts | 2 +- apps/web/src/validation/config/security.ts | 2 +- apps/web/src/validation/formSchemaCoverage.test.ts | 2 +- apps/web/src/validation/moduleConfig/audio.ts | 2 +- apps/web/src/validation/moduleConfig/cannedMessage.ts | 3 ++- apps/web/src/validation/moduleConfig/detectionSensor.ts | 2 +- apps/web/src/validation/moduleConfig/meshBeacon.test.ts | 2 +- apps/web/src/validation/moduleConfig/meshBeacon.ts | 2 +- apps/web/src/validation/moduleConfig/moduleMessages.test.ts | 2 +- apps/web/src/validation/moduleConfig/remoteHardware.test.ts | 2 +- apps/web/src/validation/moduleConfig/remoteHardware.ts | 2 +- apps/web/src/validation/moduleConfig/serial.ts | 2 +- apps/web/src/validation/moduleConfig/tak.ts | 2 +- pnpm-lock.yaml | 6 ++++++ 148 files changed, 175 insertions(+), 146 deletions(-) create mode 100644 apps/web/src/core/protobuf.ts diff --git a/apps/web/package.json b/apps/web/package.json index ac38ab3cf..1ce2898ec 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -34,7 +34,9 @@ "package": "gzipper c -i html,js,css,png,ico,svg,json,webmanifest,txt dist dist/output && tar -cvf dist/build.tar -C ./dist/output/ ." }, "dependencies": { + "@bufbuild/protobuf": "^2.16.0", "@hookform/resolvers": "^5.9.1", + "@meshtastic/protobufs": "workspace:*", "@meshtastic/sdk": "workspace:*", "@meshtastic/sdk-kmp": "workspace:*", "@meshtastic/sdk-react": "workspace:*", diff --git a/apps/web/src/components/DeviceInfoPanel.tsx b/apps/web/src/components/DeviceInfoPanel.tsx index caaf78b26..f787f4f32 100644 --- a/apps/web/src/components/DeviceInfoPanel.tsx +++ b/apps/web/src/components/DeviceInfoPanel.tsx @@ -1,7 +1,7 @@ import type { ConnectionStatus } from "@app/core/stores/deviceStore/types.ts"; import { useAppStore } from "@core/stores"; import { cn } from "@core/utils/cn.ts"; -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { ChevronRight, CpuIcon, diff --git a/apps/web/src/components/Dialog/ClientNotificationDialog/ClientNotificationDialog.tsx b/apps/web/src/components/Dialog/ClientNotificationDialog/ClientNotificationDialog.tsx index 021d48604..bf026e756 100644 --- a/apps/web/src/components/Dialog/ClientNotificationDialog/ClientNotificationDialog.tsx +++ b/apps/web/src/components/Dialog/ClientNotificationDialog/ClientNotificationDialog.tsx @@ -10,7 +10,7 @@ import { } from "@components/UI/Dialog.tsx"; import { Input } from "@components/UI/Input.tsx"; import { useDevice } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useState } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/Dialog/ImportDialog.tsx b/apps/web/src/components/Dialog/ImportDialog.tsx index 835a3a598..a7e3f7708 100644 --- a/apps/web/src/components/Dialog/ImportDialog.tsx +++ b/apps/web/src/components/Dialog/ImportDialog.tsx @@ -22,7 +22,7 @@ import { Switch } from "@components/UI/Switch.tsx"; import { useDevice } from "@core/stores"; import type { BeaconJoinPlan } from "@core/utils/beaconJoin.ts"; import { channelSetFromUrl } from "@core/utils/channelUrl.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor } from "@meshtastic/sdk-react"; import { useNavigate } from "@tanstack/react-router"; import { useEffect, useState } from "react"; diff --git a/apps/web/src/components/Dialog/LocationResponseDialog.tsx b/apps/web/src/components/Dialog/LocationResponseDialog.tsx index f69094628..44cb9f0ba 100644 --- a/apps/web/src/components/Dialog/LocationResponseDialog.tsx +++ b/apps/web/src/components/Dialog/LocationResponseDialog.tsx @@ -1,5 +1,5 @@ import { useNodeAsProto } from "@core/hooks/useNodesAsProto.ts"; -import type { Protobuf, Types } from "@meshtastic/sdk"; +import type { Protobuf, Types } from "@core/protobuf.ts"; import { numberToHexUnpadded } from "@noble/curves/utils.js"; import { useTranslation } from "react-i18next"; import { diff --git a/apps/web/src/components/Dialog/LockdownDialog/LockdownDialog.test.tsx b/apps/web/src/components/Dialog/LockdownDialog/LockdownDialog.test.tsx index 83f8ac91a..459e29de8 100644 --- a/apps/web/src/components/Dialog/LockdownDialog/LockdownDialog.test.tsx +++ b/apps/web/src/components/Dialog/LockdownDialog/LockdownDialog.test.tsx @@ -1,5 +1,5 @@ import { create } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { act, fireEvent, render, screen } from "@testing-library/react"; import type { ReactNode } from "react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; diff --git a/apps/web/src/components/Dialog/LockdownDialog/LockdownDialog.tsx b/apps/web/src/components/Dialog/LockdownDialog/LockdownDialog.tsx index 91f699981..302f5721a 100644 --- a/apps/web/src/components/Dialog/LockdownDialog/LockdownDialog.tsx +++ b/apps/web/src/components/Dialog/LockdownDialog/LockdownDialog.tsx @@ -12,7 +12,7 @@ import { Input } from "@components/UI/Input.tsx"; import { Label } from "@components/UI/Label.tsx"; import { useLockdown } from "@core/hooks/useLockdown.ts"; import { useAppStore, useDeviceStore } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { LockIcon } from "lucide-react"; import { type FormEvent, useEffect, useId, useState } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/Dialog/NodeDetailsDialog/NodeDetailsDialog.tsx b/apps/web/src/components/Dialog/NodeDetailsDialog/NodeDetailsDialog.tsx index 13244df63..6735e2493 100644 --- a/apps/web/src/components/Dialog/NodeDetailsDialog/NodeDetailsDialog.tsx +++ b/apps/web/src/components/Dialog/NodeDetailsDialog/NodeDetailsDialog.tsx @@ -32,7 +32,7 @@ import { toast } from "@core/hooks/useToast.ts"; import { useNodeAsProto } from "@core/hooks/useNodesAsProto.ts"; import { useAppStore, useDevice } from "@core/stores"; import { cn } from "@core/utils/cn.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { numberToHexUnpadded } from "@noble/curves/utils.js"; import { useNavigate } from "@tanstack/react-router"; import { fromByteArray } from "base64-js"; diff --git a/apps/web/src/components/Dialog/NodeDetailsDialog/NodeTelemetry.test.tsx b/apps/web/src/components/Dialog/NodeDetailsDialog/NodeTelemetry.test.tsx index e97f1cfb2..74a93e73b 100644 --- a/apps/web/src/components/Dialog/NodeDetailsDialog/NodeTelemetry.test.tsx +++ b/apps/web/src/components/Dialog/NodeDetailsDialog/NodeTelemetry.test.tsx @@ -1,6 +1,7 @@ import { create } from "@bufbuild/protobuf"; import { TelemetrySections } from "@components/Dialog/NodeDetailsDialog/NodeTelemetry.tsx"; -import { Protobuf, type TelemetryReading } from "@meshtastic/sdk"; +import type { TelemetryReading } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { render, screen, within } from "@testing-library/react"; import { describe, expect, it } from "vitest"; diff --git a/apps/web/src/components/Dialog/QRDialog.tsx b/apps/web/src/components/Dialog/QRDialog.tsx index ad63c4c31..748df0e0e 100644 --- a/apps/web/src/components/Dialog/QRDialog.tsx +++ b/apps/web/src/components/Dialog/QRDialog.tsx @@ -11,7 +11,7 @@ import { import { Input } from "@components/UI/Input.tsx"; import { Label } from "@components/UI/Label.tsx"; import { channelSetToUrl } from "@core/utils/channelUrl.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useChannels } from "@meshtastic/sdk-react"; import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/Dialog/TracerouteResponseDialog.tsx b/apps/web/src/components/Dialog/TracerouteResponseDialog.tsx index 8971373ff..644e2f0d0 100644 --- a/apps/web/src/components/Dialog/TracerouteResponseDialog.tsx +++ b/apps/web/src/components/Dialog/TracerouteResponseDialog.tsx @@ -1,5 +1,5 @@ import { useNodeAsProto } from "@core/hooks/useNodesAsProto.ts"; -import type { Protobuf, Types } from "@meshtastic/sdk"; +import type { Protobuf, Types } from "@core/protobuf.ts"; import { numberToHexUnpadded } from "@noble/curves/utils.js"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/Channels/BeaconOffers.tsx b/apps/web/src/components/PageComponents/Channels/BeaconOffers.tsx index 9e98e042c..e75970a1b 100644 --- a/apps/web/src/components/PageComponents/Channels/BeaconOffers.tsx +++ b/apps/web/src/components/PageComponents/Channels/BeaconOffers.tsx @@ -3,7 +3,8 @@ import { type JoinableBeaconOffer, useBeaconOffers, } from "@core/hooks/useBeaconOffers.ts"; -import { type Node, Protobuf } from "@meshtastic/sdk"; +import type { Node } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useNodes } from "@meshtastic/sdk-react"; import { RadioTowerIcon } from "lucide-react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/Channels/ChannelCard.tsx b/apps/web/src/components/PageComponents/Channels/ChannelCard.tsx index 7669df7f1..5dfc52885 100644 --- a/apps/web/src/components/PageComponents/Channels/ChannelCard.tsx +++ b/apps/web/src/components/PageComponents/Channels/ChannelCard.tsx @@ -1,5 +1,5 @@ import { cn } from "@core/utils/cn.ts"; -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { CloudDownloadIcon, CloudUploadIcon, diff --git a/apps/web/src/components/PageComponents/Channels/Channels.tsx b/apps/web/src/components/PageComponents/Channels/Channels.tsx index befef0f81..57d35d684 100644 --- a/apps/web/src/components/PageComponents/Channels/Channels.tsx +++ b/apps/web/src/components/PageComponents/Channels/Channels.tsx @@ -2,7 +2,8 @@ import { BeaconOffers } from "@app/components/PageComponents/Channels/BeaconOffe import { Button } from "@components/UI/Button.tsx"; import { useDeviceCapabilities } from "@core/hooks/useDeviceCapabilities.ts"; import { useDevice } from "@core/stores"; -import { firmwareAtLeast, type Protobuf } from "@meshtastic/sdk"; +import { firmwareAtLeast } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { useChannels, useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import i18next from "i18next"; import { PlusIcon, QrCodeIcon, UploadIcon } from "lucide-react"; diff --git a/apps/web/src/components/PageComponents/Channels/EditChannelDialog.test.tsx b/apps/web/src/components/PageComponents/Channels/EditChannelDialog.test.tsx index 62bec41a2..72d23a557 100644 --- a/apps/web/src/components/PageComponents/Channels/EditChannelDialog.test.tsx +++ b/apps/web/src/components/PageComponents/Channels/EditChannelDialog.test.tsx @@ -1,5 +1,5 @@ import { create } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { fireEvent, render, screen } from "@testing-library/react"; import { describe, expect, it, vi } from "vitest"; import { diff --git a/apps/web/src/components/PageComponents/Channels/EditChannelDialog.tsx b/apps/web/src/components/PageComponents/Channels/EditChannelDialog.tsx index 72478a7b7..e0865abb7 100644 --- a/apps/web/src/components/PageComponents/Channels/EditChannelDialog.tsx +++ b/apps/web/src/components/PageComponents/Channels/EditChannelDialog.tsx @@ -20,7 +20,7 @@ import { Input } from "@components/UI/Input.tsx"; import { Label } from "@components/UI/Label.tsx"; import { Slider } from "@components/UI/Slider.tsx"; import { Switch } from "@components/UI/Switch.tsx"; -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { type ReactNode, useId, useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; import { diff --git a/apps/web/src/components/PageComponents/Channels/channelStaging.test.ts b/apps/web/src/components/PageComponents/Channels/channelStaging.test.ts index fb8317b42..695cc9952 100644 --- a/apps/web/src/components/PageComponents/Channels/channelStaging.test.ts +++ b/apps/web/src/components/PageComponents/Channels/channelStaging.test.ts @@ -1,5 +1,5 @@ import { create } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { fromByteArray, toByteArray } from "base64-js"; import { describe, expect, it } from "vitest"; import { diff --git a/apps/web/src/components/PageComponents/Channels/channelStaging.ts b/apps/web/src/components/PageComponents/Channels/channelStaging.ts index b2dfd8dba..37bbbf833 100644 --- a/apps/web/src/components/PageComponents/Channels/channelStaging.ts +++ b/apps/web/src/components/PageComponents/Channels/channelStaging.ts @@ -5,7 +5,7 @@ import { POSITION_PRECISION_PRECISE, } from "@app/validation/channel.ts"; import { create } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { fromByteArray, toByteArray } from "base64-js"; /** The firmware supports 8 channels: index 0 (primary) and 1-7. */ diff --git a/apps/web/src/components/PageComponents/Map/Layers/HeatmapLayer.tsx b/apps/web/src/components/PageComponents/Map/Layers/HeatmapLayer.tsx index 9df005f33..838310834 100644 --- a/apps/web/src/components/PageComponents/Map/Layers/HeatmapLayer.tsx +++ b/apps/web/src/components/PageComponents/Map/Layers/HeatmapLayer.tsx @@ -1,5 +1,5 @@ import { hasPos, toLngLat } from "@core/utils/geo"; -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import type { Feature, FeatureCollection } from "geojson"; import type { HeatmapLayerSpecification } from "maplibre-gl"; import { useMemo } from "react"; diff --git a/apps/web/src/components/PageComponents/Map/Layers/NodesLayer.tsx b/apps/web/src/components/PageComponents/Map/Layers/NodesLayer.tsx index 3a16b6740..2630a9ec0 100644 --- a/apps/web/src/components/PageComponents/Map/Layers/NodesLayer.tsx +++ b/apps/web/src/components/PageComponents/Map/Layers/NodesLayer.tsx @@ -14,7 +14,7 @@ import type { PopupState } from "@components/PageComponents/Map/Popups/PopupWrap import { PopupWrapper } from "@components/PageComponents/Map/Popups/PopupWrapper.tsx"; import { useMapFitting } from "@core/hooks/useMapFitting"; import { hasPos, toLngLat } from "@core/utils/geo.ts"; -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { useNodeErrors } from "@meshtastic/sdk-react"; import { useCallback, useMemo } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/Map/Layers/PrecisionLayer.tsx b/apps/web/src/components/PageComponents/Map/Layers/PrecisionLayer.tsx index c40dbc0ab..f181c7e9d 100644 --- a/apps/web/src/components/PageComponents/Map/Layers/PrecisionLayer.tsx +++ b/apps/web/src/components/PageComponents/Map/Layers/PrecisionLayer.tsx @@ -1,6 +1,6 @@ import { getColorFromNodeNum, isLightColor } from "@app/core/utils/color"; import { precisionBitsToMeters, toLngLat } from "@core/utils/geo.ts"; -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { circle } from "@turf/turf"; import type { Feature, FeatureCollection, Polygon } from "geojson"; import { Layer, Source } from "react-map-gl/maplibre"; diff --git a/apps/web/src/components/PageComponents/Map/Layers/SNRLayer.tsx b/apps/web/src/components/PageComponents/Map/Layers/SNRLayer.tsx index d87dd1f42..acce6ffe6 100644 --- a/apps/web/src/components/PageComponents/Map/Layers/SNRLayer.tsx +++ b/apps/web/src/components/PageComponents/Map/Layers/SNRLayer.tsx @@ -11,7 +11,7 @@ import { mercatorToLngLat, toLngLat, } from "@core/utils/geo"; -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import type { Feature, FeatureCollection } from "geojson"; import { useTranslation } from "react-i18next"; import { Layer, Source } from "react-map-gl/maplibre"; diff --git a/apps/web/src/components/PageComponents/Map/Layers/WaypointLayer.tsx b/apps/web/src/components/PageComponents/Map/Layers/WaypointLayer.tsx index 429bb1ef2..1082cfa29 100644 --- a/apps/web/src/components/PageComponents/Map/Layers/WaypointLayer.tsx +++ b/apps/web/src/components/PageComponents/Map/Layers/WaypointLayer.tsx @@ -4,7 +4,7 @@ import { PopupWrapper } from "@components/PageComponents/Map/Popups/PopupWrapper import { WaypointDetail } from "@components/PageComponents/Map/Popups/WaypointDetail.tsx"; import { useMapFitting } from "@core/hooks/useMapFitting"; import { useDevice, type WaypointWithMetadata } from "@core/stores"; -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { useCallback } from "react"; import type { MapRef } from "react-map-gl/maplibre"; diff --git a/apps/web/src/components/PageComponents/Map/Popups/NodeDetail.tsx b/apps/web/src/components/PageComponents/Map/Popups/NodeDetail.tsx index 548d819d7..3be875959 100644 --- a/apps/web/src/components/PageComponents/Map/Popups/NodeDetail.tsx +++ b/apps/web/src/components/PageComponents/Map/Popups/NodeDetail.tsx @@ -8,7 +8,7 @@ import { Heading } from "@components/UI/Typography/Heading.tsx"; import { Subtle } from "@components/UI/Typography/Subtle.tsx"; import { formatQuantity } from "@core/utils/string.ts"; import type { NodeInfoWithStatus } from "@core/hooks/useNodesAsProto.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { Tooltip, TooltipContent, diff --git a/apps/web/src/components/PageComponents/Map/Popups/WaypointDetail.tsx b/apps/web/src/components/PageComponents/Map/Popups/WaypointDetail.tsx index b938d39f3..f93f60884 100644 --- a/apps/web/src/components/PageComponents/Map/Popups/WaypointDetail.tsx +++ b/apps/web/src/components/PageComponents/Map/Popups/WaypointDetail.tsx @@ -8,7 +8,7 @@ import { hasPos, toLngLat, } from "@core/utils/geo"; -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { ClockFadingIcon, ClockPlusIcon, diff --git a/apps/web/src/components/PageComponents/Map/cluster.ts b/apps/web/src/components/PageComponents/Map/cluster.ts index 88c9d0d1b..049d0da76 100644 --- a/apps/web/src/components/PageComponents/Map/cluster.ts +++ b/apps/web/src/components/PageComponents/Map/cluster.ts @@ -1,4 +1,4 @@ -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; export type ClusterKey = string; export type PxOffset = [number, number]; diff --git a/apps/web/src/components/PageComponents/Messages/MessageDiagnostics.tsx b/apps/web/src/components/PageComponents/Messages/MessageDiagnostics.tsx index d119ffb00..481b3982e 100644 --- a/apps/web/src/components/PageComponents/Messages/MessageDiagnostics.tsx +++ b/apps/web/src/components/PageComponents/Messages/MessageDiagnostics.tsx @@ -7,7 +7,7 @@ import { type SignalQuality, snrQuality, } from "@core/utils/signalQuality.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import type { LucideIcon } from "lucide-react"; import { Cable, Cloud, Network, Route, ShieldCheck } from "lucide-react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/Messages/MessageItem.test.tsx b/apps/web/src/components/PageComponents/Messages/MessageItem.test.tsx index b4434ea79..a1d8d2eb2 100644 --- a/apps/web/src/components/PageComponents/Messages/MessageItem.test.tsx +++ b/apps/web/src/components/PageComponents/Messages/MessageItem.test.tsx @@ -3,7 +3,7 @@ import { MessageState, MessageType, } from "@core/stores/messageStore"; -import { Protobuf, type Types } from "@meshtastic/sdk"; +import { Protobuf, type Types } from "@core/protobuf.ts"; import { fireEvent, render, screen } from "@testing-library/react"; import { describe, expect, it, vi } from "vitest"; import { MessageItem } from "./MessageItem.tsx"; diff --git a/apps/web/src/components/PageComponents/Messages/MessageItem.tsx b/apps/web/src/components/PageComponents/Messages/MessageItem.tsx index 77a302d64..03bc243f2 100644 --- a/apps/web/src/components/PageComponents/Messages/MessageItem.tsx +++ b/apps/web/src/components/PageComponents/Messages/MessageItem.tsx @@ -6,7 +6,7 @@ import { import { useAppStore, useDevice } from "@core/stores"; import type { Message } from "@core/stores/messageStore"; import { cn } from "@core/utils/cn.ts"; -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { useMemo } from "react"; import { MessageDiagnostics } from "./MessageDiagnostics.tsx"; import { MessageStatus } from "./MessageStatus.tsx"; diff --git a/apps/web/src/components/PageComponents/Messages/TraceRoute.test.tsx b/apps/web/src/components/PageComponents/Messages/TraceRoute.test.tsx index 0d12a1c41..7d5d6e757 100644 --- a/apps/web/src/components/PageComponents/Messages/TraceRoute.test.tsx +++ b/apps/web/src/components/PageComponents/Messages/TraceRoute.test.tsx @@ -1,6 +1,6 @@ import { TraceRoute } from "@components/PageComponents/Messages/TraceRoute.tsx"; import { useNodesAsProto } from "@core/hooks/useNodesAsProto.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { render, screen } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; diff --git a/apps/web/src/components/PageComponents/Messages/TraceRoute.tsx b/apps/web/src/components/PageComponents/Messages/TraceRoute.tsx index 2555bd215..4c84b2bbb 100644 --- a/apps/web/src/components/PageComponents/Messages/TraceRoute.tsx +++ b/apps/web/src/components/PageComponents/Messages/TraceRoute.tsx @@ -1,5 +1,5 @@ import { useNodesAsProto } from "@core/hooks/useNodesAsProto.ts"; -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { numberToHexUnpadded } from "@noble/curves/utils.js"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/AmbientLighting.tsx b/apps/web/src/components/PageComponents/ModuleConfig/AmbientLighting.tsx index e7b892828..ac3de1008 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/AmbientLighting.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/AmbientLighting.tsx @@ -8,7 +8,7 @@ import { type DynamicFormFormInit, } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useState } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/Audio.tsx b/apps/web/src/components/PageComponents/ModuleConfig/Audio.tsx index 5ef079e29..0d78387df 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/Audio.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/Audio.tsx @@ -8,7 +8,7 @@ import { type DynamicFormFormInit, } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/CannedMessage.tsx b/apps/web/src/components/PageComponents/ModuleConfig/CannedMessage.tsx index dfc30bc8b..8d6f2aceb 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/CannedMessage.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/CannedMessage.tsx @@ -9,7 +9,8 @@ import { } from "@components/Form/DynamicForm.tsx"; import { useDeviceCapabilities } from "@core/hooks/useDeviceCapabilities.ts"; import { useDevice } from "@core/stores"; -import { firmwareAtLeast, Protobuf } from "@meshtastic/sdk"; +import { firmwareAtLeast } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useCannedMessages, useConfigEditor, diff --git a/apps/web/src/components/PageComponents/ModuleConfig/DetectionSensor.tsx b/apps/web/src/components/PageComponents/ModuleConfig/DetectionSensor.tsx index 14598c392..8d7502142 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/DetectionSensor.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/DetectionSensor.tsx @@ -8,7 +8,7 @@ import { type DynamicFormFormInit, } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/ExternalNotification.tsx b/apps/web/src/components/PageComponents/ModuleConfig/ExternalNotification.tsx index 4b269ccc4..129d972ca 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/ExternalNotification.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/ExternalNotification.tsx @@ -8,7 +8,7 @@ import { type DynamicFormFormInit, } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useRingtone, useSignal } from "@meshtastic/sdk-react"; import { useMemo } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/MQTT.test.tsx b/apps/web/src/components/PageComponents/ModuleConfig/MQTT.test.tsx index a51aacd1b..64e3bcd26 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/MQTT.test.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/MQTT.test.tsx @@ -1,6 +1,6 @@ import { create } from "@bufbuild/protobuf"; import { renderSettingsForm } from "@app/tests/renderSettingsForm.tsx"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { describe, expect, it } from "vitest"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/MQTT.tsx b/apps/web/src/components/PageComponents/ModuleConfig/MQTT.tsx index e6315ca51..fc0dc875c 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/MQTT.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/MQTT.tsx @@ -10,7 +10,7 @@ import { } from "@components/Form/DynamicForm.tsx"; import { useDeviceCapabilities } from "@core/hooks/useDeviceCapabilities.ts"; import { useDevice } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/MeshBeacon.tsx b/apps/web/src/components/PageComponents/ModuleConfig/MeshBeacon.tsx index f7d3efcb4..6955530c5 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/MeshBeacon.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/MeshBeacon.tsx @@ -17,7 +17,7 @@ import { useDeviceCapabilities } from "@core/hooks/useDeviceCapabilities.ts"; import { useDevice } from "@core/stores"; import { channelSettingsByIndex } from "@core/utils/beaconJoin.ts"; import { getRegionPresetGroup } from "@core/utils/loraPresets.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useChannels, useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useMemo } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/MeshBeaconTargets.tsx b/apps/web/src/components/PageComponents/ModuleConfig/MeshBeaconTargets.tsx index 7042692d3..c65d0a2d5 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/MeshBeaconTargets.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/MeshBeaconTargets.tsx @@ -14,7 +14,7 @@ import { SelectTrigger, SelectValue, } from "@components/UI/Select.tsx"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { PlusIcon } from "lucide-react"; import { type SubmitHandler, diff --git a/apps/web/src/components/PageComponents/ModuleConfig/NeighborInfo.tsx b/apps/web/src/components/PageComponents/ModuleConfig/NeighborInfo.tsx index ff68d96ea..b14b9336d 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/NeighborInfo.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/NeighborInfo.tsx @@ -8,7 +8,7 @@ import { type DynamicFormFormInit, } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/Paxcounter.tsx b/apps/web/src/components/PageComponents/ModuleConfig/Paxcounter.tsx index 70697a94e..a7538e50c 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/Paxcounter.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/Paxcounter.tsx @@ -8,7 +8,7 @@ import { type DynamicFormFormInit, } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/RangeTest.tsx b/apps/web/src/components/PageComponents/ModuleConfig/RangeTest.tsx index 692305b90..74b39b107 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/RangeTest.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/RangeTest.tsx @@ -8,7 +8,7 @@ import { type DynamicFormFormInit, } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useChannel, useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/RemoteHardware.tsx b/apps/web/src/components/PageComponents/ModuleConfig/RemoteHardware.tsx index 3023f3e0a..aa0eb2c02 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/RemoteHardware.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/RemoteHardware.tsx @@ -9,7 +9,7 @@ import { type DynamicFormFormInit, } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useTranslation } from "react-i18next"; import { RemoteHardwarePins } from "./RemoteHardwarePins.tsx"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/RemoteHardwarePins.tsx b/apps/web/src/components/PageComponents/ModuleConfig/RemoteHardwarePins.tsx index 8cd72b35f..20b1630b8 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/RemoteHardwarePins.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/RemoteHardwarePins.tsx @@ -12,7 +12,7 @@ import { SelectTrigger, SelectValue, } from "@components/UI/Select.tsx"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { PlusIcon, TrashIcon } from "lucide-react"; import { Controller, diff --git a/apps/web/src/components/PageComponents/ModuleConfig/Serial.tsx b/apps/web/src/components/PageComponents/ModuleConfig/Serial.tsx index cc86c648d..2ab70a07f 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/Serial.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/Serial.tsx @@ -8,7 +8,7 @@ import { type DynamicFormFormInit, } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/StoreForward.tsx b/apps/web/src/components/PageComponents/ModuleConfig/StoreForward.tsx index b8fc772f0..929c3407c 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/StoreForward.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/StoreForward.tsx @@ -8,7 +8,7 @@ import { type DynamicFormFormInit, } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/Tak.tsx b/apps/web/src/components/PageComponents/ModuleConfig/Tak.tsx index f31ea2dc2..4666a3079 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/Tak.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/Tak.tsx @@ -8,7 +8,7 @@ import { type DynamicFormFormInit, } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useTranslation } from "react-i18next"; import { TakTeamSwatches } from "./TakTeamSwatches.tsx"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/TakTeamSwatches.tsx b/apps/web/src/components/PageComponents/ModuleConfig/TakTeamSwatches.tsx index 5e14417db..0b61ac151 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/TakTeamSwatches.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/TakTeamSwatches.tsx @@ -1,7 +1,7 @@ import type { TakValidation } from "@app/validation/moduleConfig/tak.ts"; import { FieldWrapper } from "@components/Form/FormWrapper.tsx"; import { cn } from "@core/utils/cn.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { type SubmitHandler, useFormContext, useWatch } from "react-hook-form"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/Telemetry.tsx b/apps/web/src/components/PageComponents/ModuleConfig/Telemetry.tsx index c15f1c3b6..005907425 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/Telemetry.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/Telemetry.tsx @@ -8,7 +8,7 @@ import { type DynamicFormFormInit, } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/useStagedAdminString.ts b/apps/web/src/components/PageComponents/ModuleConfig/useStagedAdminString.ts index 53fe0cf86..013254715 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/useStagedAdminString.ts +++ b/apps/web/src/components/PageComponents/ModuleConfig/useStagedAdminString.ts @@ -1,5 +1,5 @@ import { create } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useCallback } from "react"; diff --git a/apps/web/src/components/PageComponents/Settings/Bluetooth.tsx b/apps/web/src/components/PageComponents/Settings/Bluetooth.tsx index 1b0182810..e2e0f043a 100644 --- a/apps/web/src/components/PageComponents/Settings/Bluetooth.tsx +++ b/apps/web/src/components/PageComponents/Settings/Bluetooth.tsx @@ -8,7 +8,7 @@ import { type DynamicFormFormInit, } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/Settings/Device/index.tsx b/apps/web/src/components/PageComponents/Settings/Device/index.tsx index f17fe0ef4..898ce4dd4 100644 --- a/apps/web/src/components/PageComponents/Settings/Device/index.tsx +++ b/apps/web/src/components/PageComponents/Settings/Device/index.tsx @@ -11,7 +11,7 @@ import { type DynamicFormFormInit, } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/Settings/DeviceConfig.test.tsx b/apps/web/src/components/PageComponents/Settings/DeviceConfig.test.tsx index c0c5b2f74..e1e8956cc 100644 --- a/apps/web/src/components/PageComponents/Settings/DeviceConfig.test.tsx +++ b/apps/web/src/components/PageComponents/Settings/DeviceConfig.test.tsx @@ -3,7 +3,7 @@ import { renderSettingsForm } from "@app/tests/renderSettingsForm.tsx"; import { BluetoothValidationSchema } from "@app/validation/config/bluetooth.ts"; import { Bluetooth } from "@components/PageComponents/Settings/Bluetooth.tsx"; import { Device } from "@components/PageComponents/Settings/Device/index.tsx"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { describe, expect, it } from "vitest"; diff --git a/apps/web/src/components/PageComponents/Settings/Display.tsx b/apps/web/src/components/PageComponents/Settings/Display.tsx index e7eaf81a3..0c9e11904 100644 --- a/apps/web/src/components/PageComponents/Settings/Display.tsx +++ b/apps/web/src/components/PageComponents/Settings/Display.tsx @@ -8,7 +8,7 @@ import { type DynamicFormFormInit, } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/Settings/LoRa.test.tsx b/apps/web/src/components/PageComponents/Settings/LoRa.test.tsx index 7bbb1e82d..f2bc7ec34 100644 --- a/apps/web/src/components/PageComponents/Settings/LoRa.test.tsx +++ b/apps/web/src/components/PageComponents/Settings/LoRa.test.tsx @@ -1,5 +1,5 @@ import { create } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { render, screen } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { LoRa } from "./LoRa.tsx"; diff --git a/apps/web/src/components/PageComponents/Settings/LoRa.tsx b/apps/web/src/components/PageComponents/Settings/LoRa.tsx index bd6f9f852..9363cf062 100644 --- a/apps/web/src/components/PageComponents/Settings/LoRa.tsx +++ b/apps/web/src/components/PageComponents/Settings/LoRa.tsx @@ -24,7 +24,8 @@ import { getLicensedOnlyRegions, pickEnumValues, } from "@core/utils/loraPresets.ts"; -import { firmwareAtLeast, Protobuf } from "@meshtastic/sdk"; +import { firmwareAtLeast } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useEffect, useMemo, useState } from "react"; import { useForm, useWatch } from "react-hook-form"; diff --git a/apps/web/src/components/PageComponents/Settings/Network/Network.test.tsx b/apps/web/src/components/PageComponents/Settings/Network/Network.test.tsx index 2e0948f4b..dc748370c 100644 --- a/apps/web/src/components/PageComponents/Settings/Network/Network.test.tsx +++ b/apps/web/src/components/PageComponents/Settings/Network/Network.test.tsx @@ -1,5 +1,5 @@ import { create } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { Network } from "./index.tsx"; diff --git a/apps/web/src/components/PageComponents/Settings/Network/index.tsx b/apps/web/src/components/PageComponents/Settings/Network/index.tsx index 3fd0c6520..3427de7f3 100644 --- a/apps/web/src/components/PageComponents/Settings/Network/index.tsx +++ b/apps/web/src/components/PageComponents/Settings/Network/index.tsx @@ -16,7 +16,7 @@ import { convertIntToIpAddress, convertIpAddressToInt, } from "@core/utils/ip.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/Settings/Position.test.tsx b/apps/web/src/components/PageComponents/Settings/Position.test.tsx index 12ec583de..cce473fd9 100644 --- a/apps/web/src/components/PageComponents/Settings/Position.test.tsx +++ b/apps/web/src/components/PageComponents/Settings/Position.test.tsx @@ -1,6 +1,6 @@ import { create } from "@bufbuild/protobuf"; import { STAGED_FIXED_POSITION } from "@core/utils/stagedAdminKeys.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { Position } from "./Position.tsx"; diff --git a/apps/web/src/components/PageComponents/Settings/Position.tsx b/apps/web/src/components/PageComponents/Settings/Position.tsx index 63f9d1d41..724083b40 100644 --- a/apps/web/src/components/PageComponents/Settings/Position.tsx +++ b/apps/web/src/components/PageComponents/Settings/Position.tsx @@ -17,7 +17,7 @@ import { useMyNodeAsProto } from "@core/hooks/useNodesAsProto.ts"; import { useToast } from "@core/hooks/useToast.ts"; import { useDevice } from "@core/stores"; import { STAGED_FIXED_POSITION } from "@core/utils/stagedAdminKeys.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { LocateFixed } from "lucide-react"; import { useCallback, useMemo, useState } from "react"; diff --git a/apps/web/src/components/PageComponents/Settings/Power.test.tsx b/apps/web/src/components/PageComponents/Settings/Power.test.tsx index 01d721398..f1cb7627c 100644 --- a/apps/web/src/components/PageComponents/Settings/Power.test.tsx +++ b/apps/web/src/components/PageComponents/Settings/Power.test.tsx @@ -1,5 +1,5 @@ import { create } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { fireEvent, render, screen } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { Power } from "./Power.tsx"; diff --git a/apps/web/src/components/PageComponents/Settings/Power.tsx b/apps/web/src/components/PageComponents/Settings/Power.tsx index 486f6c254..46bf90397 100644 --- a/apps/web/src/components/PageComponents/Settings/Power.tsx +++ b/apps/web/src/components/PageComponents/Settings/Power.tsx @@ -12,7 +12,7 @@ import { } from "@components/Form/DynamicForm.tsx"; import type { FieldProps } from "@components/Form/DynamicFormField.tsx"; import { useDevice } from "@core/stores"; -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useEffect } from "react"; import { useForm, useWatch } from "react-hook-form"; diff --git a/apps/web/src/components/PageComponents/Settings/Security/LockdownSection.test.tsx b/apps/web/src/components/PageComponents/Settings/Security/LockdownSection.test.tsx index 42c97ef43..29cfd79d5 100644 --- a/apps/web/src/components/PageComponents/Settings/Security/LockdownSection.test.tsx +++ b/apps/web/src/components/PageComponents/Settings/Security/LockdownSection.test.tsx @@ -1,5 +1,5 @@ import { create } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { fireEvent, render, screen } from "@testing-library/react"; import type { ReactNode } from "react"; import { beforeEach, describe, expect, it, vi } from "vitest"; diff --git a/apps/web/src/components/PageComponents/Settings/Security/LockdownSection.tsx b/apps/web/src/components/PageComponents/Settings/Security/LockdownSection.tsx index 72ae88a05..0ee1fbf18 100644 --- a/apps/web/src/components/PageComponents/Settings/Security/LockdownSection.tsx +++ b/apps/web/src/components/PageComponents/Settings/Security/LockdownSection.tsx @@ -4,7 +4,7 @@ import { Button } from "@components/UI/Button.tsx"; import { Subtle } from "@components/UI/Typography/Subtle.tsx"; import { useLockdown } from "@core/hooks/useLockdown.ts"; import { useToast } from "@core/hooks/useToast.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useState } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/Settings/Security/Security.test.tsx b/apps/web/src/components/PageComponents/Settings/Security/Security.test.tsx index 0c130c83b..1ba7a15d5 100644 --- a/apps/web/src/components/PageComponents/Settings/Security/Security.test.tsx +++ b/apps/web/src/components/PageComponents/Settings/Security/Security.test.tsx @@ -1,5 +1,5 @@ import { create } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { render, screen } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { Security } from "./Security.tsx"; diff --git a/apps/web/src/components/PageComponents/Settings/Security/Security.tsx b/apps/web/src/components/PageComponents/Settings/Security/Security.tsx index a70834262..2d9676ee3 100644 --- a/apps/web/src/components/PageComponents/Settings/Security/Security.tsx +++ b/apps/web/src/components/PageComponents/Settings/Security/Security.tsx @@ -14,7 +14,7 @@ import { import { useDeviceCapabilities } from "@core/hooks/useDeviceCapabilities.ts"; import { useDevice } from "@core/stores"; import { getX25519PrivateKey, getX25519PublicKey } from "@core/utils/x25519.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { fromByteArray, toByteArray } from "base64-js"; import { useEffect, useState } from "react"; diff --git a/apps/web/src/components/PageComponents/Settings/User.test.tsx b/apps/web/src/components/PageComponents/Settings/User.test.tsx index 06cdda59a..769baea44 100644 --- a/apps/web/src/components/PageComponents/Settings/User.test.tsx +++ b/apps/web/src/components/PageComponents/Settings/User.test.tsx @@ -1,5 +1,5 @@ import { create } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { User } from "./User.tsx"; diff --git a/apps/web/src/components/PageComponents/Settings/User.tsx b/apps/web/src/components/PageComponents/Settings/User.tsx index 7a8a2f1d2..82f78a0db 100644 --- a/apps/web/src/components/PageComponents/Settings/User.tsx +++ b/apps/web/src/components/PageComponents/Settings/User.tsx @@ -12,7 +12,8 @@ import { useDeviceCapabilities } from "@core/hooks/useDeviceCapabilities.ts"; import { useMyNodeAsProto } from "@core/hooks/useNodesAsProto.ts"; import { useDevice } from "@core/stores"; import { isModuleExcluded } from "@core/utils/excludedModules.ts"; -import { firmwareAtLeast, Protobuf } from "@meshtastic/sdk"; +import { firmwareAtLeast } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { useEffect } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/SettingsPages/useDeviceConnected.ts b/apps/web/src/components/PageComponents/SettingsPages/useDeviceConnected.ts index 3a870aefe..64f99a681 100644 --- a/apps/web/src/components/PageComponents/SettingsPages/useDeviceConnected.ts +++ b/apps/web/src/components/PageComponents/SettingsPages/useDeviceConnected.ts @@ -1,5 +1,5 @@ import { useDevice } from "@core/stores"; -import { Types } from "@meshtastic/sdk"; +import { Types } from "@core/protobuf.ts"; /** True once the active node is connected and configured. */ export function useDeviceConnected(): boolean { diff --git a/apps/web/src/components/generic/Filter/FilterControl.tsx b/apps/web/src/components/generic/Filter/FilterControl.tsx index ad2a1abb5..c1601c19f 100644 --- a/apps/web/src/components/generic/Filter/FilterControl.tsx +++ b/apps/web/src/components/generic/Filter/FilterControl.tsx @@ -15,7 +15,7 @@ import { } from "@components/UI/Popover.tsx"; import { cn } from "@core/utils/cn.ts"; import { debounce } from "@core/utils/debounce.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { FunnelIcon } from "lucide-react"; import { type ComponentProps, diff --git a/apps/web/src/components/generic/Filter/useFilterNode.test.ts b/apps/web/src/components/generic/Filter/useFilterNode.test.ts index f8b782e9c..8ebaaefa8 100644 --- a/apps/web/src/components/generic/Filter/useFilterNode.test.ts +++ b/apps/web/src/components/generic/Filter/useFilterNode.test.ts @@ -1,5 +1,5 @@ import { useFilterNode } from "@components/generic/Filter/useFilterNode.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { renderHook } from "@testing-library/react"; import { describe, expect, it } from "vitest"; diff --git a/apps/web/src/components/generic/Filter/useFilterNode.ts b/apps/web/src/components/generic/Filter/useFilterNode.ts index e35fa6816..79c8f20e1 100644 --- a/apps/web/src/components/generic/Filter/useFilterNode.ts +++ b/apps/web/src/components/generic/Filter/useFilterNode.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { numberToHexUnpadded } from "@noble/curves/utils.js"; import { useCallback, useMemo } from "react"; diff --git a/apps/web/src/components/generic/NodeTrustIndicators.tsx b/apps/web/src/components/generic/NodeTrustIndicators.tsx index 439860260..0630f53d5 100644 --- a/apps/web/src/components/generic/NodeTrustIndicators.tsx +++ b/apps/web/src/components/generic/NodeTrustIndicators.tsx @@ -6,7 +6,8 @@ import { TooltipTrigger, } from "@components/UI/Tooltip.tsx"; import { cn } from "@core/utils/cn.ts"; -import { isUnheardOnCurrentLora, type Protobuf } from "@meshtastic/sdk"; +import { isUnheardOnCurrentLora } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import type { LucideIcon } from "lucide-react"; import { RadioTowerIcon, SignatureIcon, VolumeXIcon } from "lucide-react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/core/dto/NodeNumToNodeInfoDTO.ts b/apps/web/src/core/dto/NodeNumToNodeInfoDTO.ts index 2af378456..bfafa5ac2 100644 --- a/apps/web/src/core/dto/NodeNumToNodeInfoDTO.ts +++ b/apps/web/src/core/dto/NodeNumToNodeInfoDTO.ts @@ -1,5 +1,5 @@ import { create } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; function createDefaultUser(num: number): Protobuf.Mesh.User { const userIdHex = num.toString(16).toUpperCase().padStart(2, "0"); diff --git a/apps/web/src/core/dto/PacketToMessageDTO.test.ts b/apps/web/src/core/dto/PacketToMessageDTO.test.ts index 24631e1a9..d94359cf5 100644 --- a/apps/web/src/core/dto/PacketToMessageDTO.test.ts +++ b/apps/web/src/core/dto/PacketToMessageDTO.test.ts @@ -1,4 +1,4 @@ -import type { Types } from "@meshtastic/sdk"; +import type { Types } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import PacketToMessageDTO from "./PacketToMessageDTO.ts"; diff --git a/apps/web/src/core/dto/PacketToMessageDTO.ts b/apps/web/src/core/dto/PacketToMessageDTO.ts index e193a1221..301491795 100644 --- a/apps/web/src/core/dto/PacketToMessageDTO.ts +++ b/apps/web/src/core/dto/PacketToMessageDTO.ts @@ -1,6 +1,6 @@ import { MessageState, MessageType } from "@core/stores"; import type { Message } from "@core/stores/messageStore/types.ts"; -import type { Types } from "@meshtastic/sdk"; +import type { Types } from "@core/protobuf.ts"; class PacketToMessageDTO { channel: Types.ChannelNumber; diff --git a/apps/web/src/core/hooks/useChatAsLegacyMessages.test.ts b/apps/web/src/core/hooks/useChatAsLegacyMessages.test.ts index a7e566209..af13e3b7e 100644 --- a/apps/web/src/core/hooks/useChatAsLegacyMessages.test.ts +++ b/apps/web/src/core/hooks/useChatAsLegacyMessages.test.ts @@ -2,9 +2,8 @@ import { MessageState, MessageType } from "@core/stores/messageStore"; import { type Message as SdkMessage, MessageState as SdkMessageState, - Protobuf, - type Types, } from "@meshtastic/sdk"; +import { Protobuf, type Types } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { toLegacy } from "./useChatAsLegacyMessages.ts"; diff --git a/apps/web/src/core/hooks/useChatAsLegacyMessages.ts b/apps/web/src/core/hooks/useChatAsLegacyMessages.ts index 3a9c9eb8d..d697f44ee 100644 --- a/apps/web/src/core/hooks/useChatAsLegacyMessages.ts +++ b/apps/web/src/core/hooks/useChatAsLegacyMessages.ts @@ -4,7 +4,8 @@ import { MessageType, } from "@core/stores/messageStore"; import type { Message as SdkMessage } from "@meshtastic/sdk"; -import { MessageState as SdkMessageState, type Types } from "@meshtastic/sdk"; +import { MessageState as SdkMessageState } from "@meshtastic/sdk"; +import type { Types } from "@core/protobuf.ts"; import { useChat, useDirectChat } from "@meshtastic/sdk-react"; import { useMemo } from "react"; diff --git a/apps/web/src/core/hooks/useChatLegacy.ts b/apps/web/src/core/hooks/useChatLegacy.ts index bdf8d4f93..0f0810d3a 100644 --- a/apps/web/src/core/hooks/useChatLegacy.ts +++ b/apps/web/src/core/hooks/useChatLegacy.ts @@ -2,7 +2,7 @@ import { type Message as LegacyMessage, MessageType, } from "@core/stores/messageStore"; -import type { Types } from "@meshtastic/sdk"; +import type { Types } from "@core/protobuf.ts"; import { useChat, useDirectChat } from "@meshtastic/sdk-react"; import { useMemo } from "react"; import { toLegacy } from "./useChatAsLegacyMessages.ts"; diff --git a/apps/web/src/core/hooks/useDeviceCapabilities.ts b/apps/web/src/core/hooks/useDeviceCapabilities.ts index 09fcd5ab9..02dc52a52 100644 --- a/apps/web/src/core/hooks/useDeviceCapabilities.ts +++ b/apps/web/src/core/hooks/useDeviceCapabilities.ts @@ -1,5 +1,6 @@ import { useDevice } from "@core/stores"; -import { firmwareAtLeast, type Protobuf } from "@meshtastic/sdk"; +import { firmwareAtLeast } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { useActiveClient, useSignal } from "@meshtastic/sdk-react"; const EMPTY_REGION_PRESETS_SIGNAL = { diff --git a/apps/web/src/core/hooks/useLockdown.ts b/apps/web/src/core/hooks/useLockdown.ts index 5892c2af6..eb5b77f37 100644 --- a/apps/web/src/core/hooks/useLockdown.ts +++ b/apps/web/src/core/hooks/useLockdown.ts @@ -1,4 +1,5 @@ -import type { MeshClient, Protobuf } from "@meshtastic/sdk"; +import type { MeshClient } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { useActiveClient, useSignal } from "@meshtastic/sdk-react"; type LockdownStatus = Protobuf.Mesh.LockdownStatus | undefined; diff --git a/apps/web/src/core/hooks/useMapFitting.ts b/apps/web/src/core/hooks/useMapFitting.ts index 0229b1b78..39f732add 100644 --- a/apps/web/src/core/hooks/useMapFitting.ts +++ b/apps/web/src/core/hooks/useMapFitting.ts @@ -1,5 +1,5 @@ import { boundsFromLngLat, type LngLat, toLngLat } from "@core/utils/geo"; -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { useCallback } from "react"; import type { MapRef } from "react-map-gl/maplibre"; diff --git a/apps/web/src/core/hooks/useNewNodeNum.ts b/apps/web/src/core/hooks/useNewNodeNum.ts index 0c6c6f2fa..aee714be1 100644 --- a/apps/web/src/core/hooks/useNewNodeNum.ts +++ b/apps/web/src/core/hooks/useNewNodeNum.ts @@ -1,5 +1,5 @@ import { useDeviceStore } from "@core/stores"; -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; export function useNewNodeNum( id: number, diff --git a/apps/web/src/core/hooks/useNodesAsProto.ts b/apps/web/src/core/hooks/useNodesAsProto.ts index df00d99e6..9f3a4b60a 100644 --- a/apps/web/src/core/hooks/useNodesAsProto.ts +++ b/apps/web/src/core/hooks/useNodesAsProto.ts @@ -1,6 +1,6 @@ import { create } from "@bufbuild/protobuf"; import type { Node as SdkNode } from "@meshtastic/sdk"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useActiveClient, useSignal } from "@meshtastic/sdk-react"; import { useMemo } from "react"; diff --git a/apps/web/src/core/hooks/useNodesLegacy.ts b/apps/web/src/core/hooks/useNodesLegacy.ts index 5e5f81aa5..30de94a12 100644 --- a/apps/web/src/core/hooks/useNodesLegacy.ts +++ b/apps/web/src/core/hooks/useNodesLegacy.ts @@ -1,4 +1,4 @@ -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { useMeshDevice, useNodes } from "@meshtastic/sdk-react"; import { useMemo } from "react"; import { toNodeInfo } from "./useNodesAsProto.ts"; diff --git a/apps/web/src/core/kmp/transport.test.ts b/apps/web/src/core/kmp/transport.test.ts index d47dc7e9f..2dcee922a 100644 --- a/apps/web/src/core/kmp/transport.test.ts +++ b/apps/web/src/core/kmp/transport.test.ts @@ -1,5 +1,6 @@ import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; -import { DeviceStatusEnum, type DeviceOutput, Protobuf } from "@meshtastic/sdk"; +import { DeviceStatusEnum, type DeviceOutput } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { FakeKmpClient, state } from "./fakeClient.ts"; import { kmpTransport } from "./transport.ts"; diff --git a/apps/web/src/core/protobuf.ts b/apps/web/src/core/protobuf.ts new file mode 100644 index 000000000..70ce332b4 --- /dev/null +++ b/apps/web/src/core/protobuf.ts @@ -0,0 +1,2 @@ +export * as Protobuf from "@meshtastic/protobufs"; +export { Types } from "@meshtastic/sdk"; diff --git a/apps/web/src/core/stores/deviceStore/deviceStore.mock.ts b/apps/web/src/core/stores/deviceStore/deviceStore.mock.ts index 237214348..90204c4a4 100644 --- a/apps/web/src/core/stores/deviceStore/deviceStore.mock.ts +++ b/apps/web/src/core/stores/deviceStore/deviceStore.mock.ts @@ -1,4 +1,4 @@ -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { vi } from "vitest"; import type { Device } from "./index.ts"; diff --git a/apps/web/src/core/stores/deviceStore/deviceStore.test.ts b/apps/web/src/core/stores/deviceStore/deviceStore.test.ts index 9f9ea895b..18d608f09 100644 --- a/apps/web/src/core/stores/deviceStore/deviceStore.test.ts +++ b/apps/web/src/core/stores/deviceStore/deviceStore.test.ts @@ -1,5 +1,5 @@ import { create, toBinary } from "@bufbuild/protobuf"; -import { Protobuf, type Types } from "@meshtastic/sdk"; +import { Protobuf, type Types } from "@core/protobuf.ts"; import { beforeEach, describe, expect, it, vi } from "vitest"; const idbMem = new Map(); diff --git a/apps/web/src/core/stores/deviceStore/index.ts b/apps/web/src/core/stores/deviceStore/index.ts index 4142efdc6..21c4beb83 100644 --- a/apps/web/src/core/stores/deviceStore/index.ts +++ b/apps/web/src/core/stores/deviceStore/index.ts @@ -1,7 +1,8 @@ import { create, toBinary } from "@bufbuild/protobuf"; import { evictOldestEntries } from "@core/stores/utils/evictOldestEntries.ts"; import { createStorage } from "@core/stores/utils/indexDB.ts"; -import { type MeshDevice, Protobuf, Types } from "@meshtastic/sdk"; +import type { MeshDevice } from "@meshtastic/sdk"; +import { Protobuf, Types } from "@core/protobuf.ts"; import { type Draft, produce } from "immer"; import { create as createStore, type StateCreator } from "zustand"; import { diff --git a/apps/web/src/core/stores/deviceStore/types.ts b/apps/web/src/core/stores/deviceStore/types.ts index 7415fa584..6c55645f9 100644 --- a/apps/web/src/core/stores/deviceStore/types.ts +++ b/apps/web/src/core/stores/deviceStore/types.ts @@ -1,4 +1,4 @@ -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; type ValidConfigType = Exclude< keyof Protobuf.LocalOnly.LocalConfig, diff --git a/apps/web/src/core/stores/messageStore/index.ts b/apps/web/src/core/stores/messageStore/index.ts index 4d945cd00..65ae128d5 100644 --- a/apps/web/src/core/stores/messageStore/index.ts +++ b/apps/web/src/core/stores/messageStore/index.ts @@ -5,7 +5,7 @@ * persistence is owned by the SDK ChatClient + SqlocalMessageRepository. */ -import type { Protobuf, Types } from "@meshtastic/sdk"; +import type { Protobuf, Types } from "@core/protobuf.ts"; export enum MessageState { /** The addressed node acked it (and every inbound message). */ diff --git a/apps/web/src/core/stores/messageStore/types.ts b/apps/web/src/core/stores/messageStore/types.ts index 549ef5bea..f6e0436d2 100644 --- a/apps/web/src/core/stores/messageStore/types.ts +++ b/apps/web/src/core/stores/messageStore/types.ts @@ -1,5 +1,5 @@ import type { MessageState, MessageType } from "@core/stores"; -import type { Protobuf, Types } from "@meshtastic/sdk"; +import type { Protobuf, Types } from "@core/protobuf.ts"; type NodeNum = number; type MessageId = number; diff --git a/apps/web/src/core/subscriptions.ts b/apps/web/src/core/subscriptions.ts index c7b6701d1..02ef8c434 100644 --- a/apps/web/src/core/subscriptions.ts +++ b/apps/web/src/core/subscriptions.ts @@ -1,6 +1,7 @@ import { useNewNodeNum } from "@core/hooks/useNewNodeNum"; import { type Device } from "@core/stores"; -import { type MeshDevice, Protobuf } from "@meshtastic/sdk"; +import type { MeshDevice } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; /** * Wires up the legacy MeshDevice event stream into the web's Zustand stores. diff --git a/apps/web/src/core/utils/beaconJoin.test.ts b/apps/web/src/core/utils/beaconJoin.test.ts index 124c720d0..1f901b918 100644 --- a/apps/web/src/core/utils/beaconJoin.test.ts +++ b/apps/web/src/core/utils/beaconJoin.test.ts @@ -1,6 +1,6 @@ import { create, type MessageInitShape } from "@bufbuild/protobuf"; import type { Channel, MeshBeaconOffer } from "@meshtastic/sdk"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { beaconOfferKey, diff --git a/apps/web/src/core/utils/beaconJoin.ts b/apps/web/src/core/utils/beaconJoin.ts index d9932f6fb..c147a06bb 100644 --- a/apps/web/src/core/utils/beaconJoin.ts +++ b/apps/web/src/core/utils/beaconJoin.ts @@ -7,8 +7,8 @@ import { type Channel, isBeaconAlreadyJoined, type MeshBeaconOffer, - Protobuf, } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; type ChannelSettings = Protobuf.Channel.ChannelSettings; diff --git a/apps/web/src/core/utils/channelUrl.ts b/apps/web/src/core/utils/channelUrl.ts index 210ca5237..bb11fa642 100644 --- a/apps/web/src/core/utils/channelUrl.ts +++ b/apps/web/src/core/utils/channelUrl.ts @@ -1,5 +1,5 @@ import { fromBinary, toBinary } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { fromByteArray, toByteArray } from "base64-js"; /** diff --git a/apps/web/src/core/utils/cleanNodes.test.ts b/apps/web/src/core/utils/cleanNodes.test.ts index c2b027e2d..1467f0293 100644 --- a/apps/web/src/core/utils/cleanNodes.test.ts +++ b/apps/web/src/core/utils/cleanNodes.test.ts @@ -1,5 +1,6 @@ import { create } from "@bufbuild/protobuf"; -import { type Node, Protobuf } from "@meshtastic/sdk"; +import type { Node } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { minDays, nodesToClean } from "./cleanNodes.ts"; diff --git a/apps/web/src/core/utils/excludedModules.test.ts b/apps/web/src/core/utils/excludedModules.test.ts index cc5debd04..f5a1e3667 100644 --- a/apps/web/src/core/utils/excludedModules.test.ts +++ b/apps/web/src/core/utils/excludedModules.test.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { isModuleExcluded, MODULE_EXCLUSION_BITS } from "./excludedModules.ts"; diff --git a/apps/web/src/core/utils/excludedModules.ts b/apps/web/src/core/utils/excludedModules.ts index 53b41216e..c59aadf0c 100644 --- a/apps/web/src/core/utils/excludedModules.ts +++ b/apps/web/src/core/utils/excludedModules.ts @@ -1,5 +1,5 @@ import type { ValidModuleConfigType } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; const Excluded = Protobuf.Mesh.ExcludedModules; diff --git a/apps/web/src/core/utils/logRecords.test.ts b/apps/web/src/core/utils/logRecords.test.ts index c199bc1ce..45564f835 100644 --- a/apps/web/src/core/utils/logRecords.test.ts +++ b/apps/web/src/core/utils/logRecords.test.ts @@ -1,5 +1,5 @@ import { create, type MessageInitShape } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { type DeviceLogEntry, diff --git a/apps/web/src/core/utils/logRecords.ts b/apps/web/src/core/utils/logRecords.ts index d97e7d658..56ecf2dec 100644 --- a/apps/web/src/core/utils/logRecords.ts +++ b/apps/web/src/core/utils/logRecords.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; /** A device log record as kept by the debug panel. */ export interface DeviceLogEntry { diff --git a/apps/web/src/core/utils/loraPresets.test.ts b/apps/web/src/core/utils/loraPresets.test.ts index 20aec0dfc..34eebd953 100644 --- a/apps/web/src/core/utils/loraPresets.test.ts +++ b/apps/web/src/core/utils/loraPresets.test.ts @@ -1,6 +1,6 @@ import { makeLoRaValidationSchema } from "@app/validation/config/lora.ts"; import { create } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { getAllowedPresets, diff --git a/apps/web/src/core/utils/loraPresets.ts b/apps/web/src/core/utils/loraPresets.ts index 0671874d7..6461b7fb3 100644 --- a/apps/web/src/core/utils/loraPresets.ts +++ b/apps/web/src/core/utils/loraPresets.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; type ModemPreset = Protobuf.Config.Config_LoRaConfig_ModemPreset; type RegionCode = Protobuf.Config.Config_LoRaConfig_RegionCode; diff --git a/apps/web/src/core/utils/messageStatus.test.ts b/apps/web/src/core/utils/messageStatus.test.ts index 2262c0505..b2f787fd3 100644 --- a/apps/web/src/core/utils/messageStatus.test.ts +++ b/apps/web/src/core/utils/messageStatus.test.ts @@ -1,5 +1,5 @@ import { MessageState } from "@core/stores/messageStore"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { messageStatus } from "./messageStatus.ts"; diff --git a/apps/web/src/core/utils/messageStatus.ts b/apps/web/src/core/utils/messageStatus.ts index 77e79228e..53242ffe1 100644 --- a/apps/web/src/core/utils/messageStatus.ts +++ b/apps/web/src/core/utils/messageStatus.ts @@ -1,5 +1,5 @@ import { MessageState } from "@core/stores/messageStore"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; const RoutingError = Protobuf.Mesh.Routing_Error; const AckProof = Protobuf.Mesh.MeshPacket_AckProofStatus; diff --git a/apps/web/src/core/utils/profileExport.test.ts b/apps/web/src/core/utils/profileExport.test.ts index 4b2fec4d7..547a5769f 100644 --- a/apps/web/src/core/utils/profileExport.test.ts +++ b/apps/web/src/core/utils/profileExport.test.ts @@ -1,5 +1,5 @@ import { create } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { Result } from "better-result"; import { describe, expect, it } from "vitest"; import { diff --git a/apps/web/src/core/utils/profileExport.ts b/apps/web/src/core/utils/profileExport.ts index 1ac71a197..918c8097d 100644 --- a/apps/web/src/core/utils/profileExport.ts +++ b/apps/web/src/core/utils/profileExport.ts @@ -1,6 +1,6 @@ import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; import { channelSetFromUrl, channelSetToUrl } from "@core/utils/channelUrl.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { Result } from "better-result"; /** diff --git a/apps/web/src/core/utils/signalQuality.test.ts b/apps/web/src/core/utils/signalQuality.test.ts index 8b35f9303..dbb9db221 100644 --- a/apps/web/src/core/utils/signalQuality.test.ts +++ b/apps/web/src/core/utils/signalQuality.test.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { rssiQuality, snrLimit, snrQuality } from "./signalQuality.ts"; diff --git a/apps/web/src/core/utils/signalQuality.ts b/apps/web/src/core/utils/signalQuality.ts index 89ee00723..fda2dee48 100644 --- a/apps/web/src/core/utils/signalQuality.ts +++ b/apps/web/src/core/utils/signalQuality.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; type ModemPreset = Protobuf.Config.Config_LoRaConfig_ModemPreset; const Preset = Protobuf.Config.Config_LoRaConfig_ModemPreset; diff --git a/apps/web/src/core/utils/telemetry.test.ts b/apps/web/src/core/utils/telemetry.test.ts index 5f67c4e53..3bdd22466 100644 --- a/apps/web/src/core/utils/telemetry.test.ts +++ b/apps/web/src/core/utils/telemetry.test.ts @@ -1,5 +1,6 @@ import { create } from "@bufbuild/protobuf"; -import { Protobuf, type TelemetryReading } from "@meshtastic/sdk"; +import type { TelemetryReading } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { describeTelemetry, diff --git a/apps/web/src/pages/Connections/useConnections.kmp.test.ts b/apps/web/src/pages/Connections/useConnections.kmp.test.ts index b9d226346..340826ad2 100644 --- a/apps/web/src/pages/Connections/useConnections.kmp.test.ts +++ b/apps/web/src/pages/Connections/useConnections.kmp.test.ts @@ -2,7 +2,7 @@ import { fromBinary } from "@bufbuild/protobuf"; import { FakeKmpClient, state } from "@core/kmp/fakeClient.ts"; import type { Connection } from "@app/core/stores/deviceStore/types"; import { useDeviceStore } from "@core/stores"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { act, renderHook } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { useConnections } from "./useConnections.ts"; diff --git a/apps/web/src/pages/Connections/useConnections.test.ts b/apps/web/src/pages/Connections/useConnections.test.ts index 95765d66e..692915815 100644 --- a/apps/web/src/pages/Connections/useConnections.test.ts +++ b/apps/web/src/pages/Connections/useConnections.test.ts @@ -2,7 +2,8 @@ import { create } from "@bufbuild/protobuf"; import { UNKNOWN_NODE_SCOPE } from "@app/core/connections/sdkClient.ts"; import type { Connection } from "@app/core/stores/deviceStore/types"; import { useDeviceStore } from "@core/stores"; -import { type MeshDevice, Protobuf } from "@meshtastic/sdk"; +import type { MeshDevice } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { act, renderHook } from "@testing-library/react"; import { afterEach, describe, expect, it, vi } from "vitest"; import { useConnections } from "./useConnections.ts"; diff --git a/apps/web/src/pages/Map/index.tsx b/apps/web/src/pages/Map/index.tsx index 5b52f3eec..212c0531e 100644 --- a/apps/web/src/pages/Map/index.tsx +++ b/apps/web/src/pages/Map/index.tsx @@ -31,7 +31,8 @@ import { } from "@core/hooks/useNodesAsProto.ts"; import { cn } from "@core/utils/cn.ts"; import { hasPos, toLngLat } from "@core/utils/geo.ts"; -import { createLogger, type Protobuf } from "@meshtastic/sdk"; +import { createLogger } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { numberToHexUnpadded } from "@noble/curves/utils.js"; import { FunnelIcon, LocateFixedIcon } from "lucide-react"; import { diff --git a/apps/web/src/pages/Messages.tsx b/apps/web/src/pages/Messages.tsx index 67caf3afd..53e8bc848 100644 --- a/apps/web/src/pages/Messages.tsx +++ b/apps/web/src/pages/Messages.tsx @@ -12,7 +12,7 @@ import { useNodesAsProto } from "@core/hooks/useNodesAsProto.ts"; import { useToast } from "@core/hooks/useToast.ts"; import { MessageType, useSidebar } from "@core/stores"; import { cn } from "@core/utils/cn.ts"; -import { Protobuf, Types } from "@meshtastic/sdk"; +import { Protobuf, Types } from "@core/protobuf.ts"; import { useActiveClient, useChannels, diff --git a/apps/web/src/pages/Nodes/index.tsx b/apps/web/src/pages/Nodes/index.tsx index b58d1baab..c192a2a9b 100644 --- a/apps/web/src/pages/Nodes/index.tsx +++ b/apps/web/src/pages/Nodes/index.tsx @@ -23,7 +23,7 @@ import { Input } from "@components/UI/Input.tsx"; import useLang from "@core/hooks/useLang.ts"; import { useNodesAsProto } from "@core/hooks/useNodesAsProto.ts"; import { useAppStore, useDevice } from "@core/stores"; -import { Protobuf, type Types } from "@meshtastic/sdk"; +import { Protobuf, type Types } from "@core/protobuf.ts"; import { useNodeErrors } from "@meshtastic/sdk-react"; import { numberToHexUnpadded } from "@noble/curves/utils.js"; import { LockIcon, LockOpenIcon } from "lucide-react"; diff --git a/apps/web/src/pages/Settings/BackupRestore.tsx b/apps/web/src/pages/Settings/BackupRestore.tsx index 041b7e976..ceb9d61dc 100644 --- a/apps/web/src/pages/Settings/BackupRestore.tsx +++ b/apps/web/src/pages/Settings/BackupRestore.tsx @@ -22,7 +22,8 @@ import { profileContents, selectProfileFields, } from "@core/utils/profileExport.ts"; -import { type ConfigEditor, Protobuf } from "@meshtastic/sdk"; +import type { ConfigEditor } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useActiveClient, useConfigEditor, diff --git a/apps/web/src/pages/Settings/DebugPanel.tsx b/apps/web/src/pages/Settings/DebugPanel.tsx index 793c7a27e..401b23f09 100644 --- a/apps/web/src/pages/Settings/DebugPanel.tsx +++ b/apps/web/src/pages/Settings/DebugPanel.tsx @@ -11,7 +11,7 @@ import { filterLogEntries, formatLogEntry, } from "@core/utils/logRecords.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useActiveClient } from "@meshtastic/sdk-react"; import { useNavigate } from "@tanstack/react-router"; import { DownloadIcon, ShieldIcon, Trash2Icon } from "lucide-react"; diff --git a/apps/web/src/pages/Settings/DeviceConfig.tsx b/apps/web/src/pages/Settings/DeviceConfig.tsx index 1e6f889a9..d5686be33 100644 --- a/apps/web/src/pages/Settings/DeviceConfig.tsx +++ b/apps/web/src/pages/Settings/DeviceConfig.tsx @@ -6,7 +6,7 @@ import { Position } from "@components/PageComponents/Settings/Position.tsx"; import { Power } from "@components/PageComponents/Settings/Power.tsx"; import { useDeviceCapabilities } from "@core/hooks/useDeviceCapabilities.ts"; import type { ValidConfigType } from "@core/stores"; -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { type ComponentType, useMemo } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/pages/Settings/ModuleConfig.tsx b/apps/web/src/pages/Settings/ModuleConfig.tsx index 13b65afbe..e0b07fc6f 100644 --- a/apps/web/src/pages/Settings/ModuleConfig.tsx +++ b/apps/web/src/pages/Settings/ModuleConfig.tsx @@ -16,7 +16,7 @@ import { Telemetry } from "@components/PageComponents/ModuleConfig/Telemetry.tsx import { useDeviceCapabilities } from "@core/hooks/useDeviceCapabilities.ts"; import { useDevice, type ValidModuleConfigType } from "@core/stores"; import { isModuleExcluded } from "@core/utils/excludedModules.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; import { type ComponentType, useMemo } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/tests/renderSettingsForm.tsx b/apps/web/src/tests/renderSettingsForm.tsx index 6efc689fd..dd9144510 100644 --- a/apps/web/src/tests/renderSettingsForm.tsx +++ b/apps/web/src/tests/renderSettingsForm.tsx @@ -1,5 +1,6 @@ import { CurrentDeviceContext, useDeviceStore } from "@core/stores"; -import { MeshClient, MeshRegistry, type Protobuf } from "@meshtastic/sdk"; +import { MeshClient, MeshRegistry } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { createFakeTransport, interceptAdminMessages, diff --git a/apps/web/src/validation/config/bluetooth.test.ts b/apps/web/src/validation/config/bluetooth.test.ts index fdcba8551..612d12a6c 100644 --- a/apps/web/src/validation/config/bluetooth.test.ts +++ b/apps/web/src/validation/config/bluetooth.test.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { BluetoothValidationSchema } from "./bluetooth.ts"; diff --git a/apps/web/src/validation/config/bluetooth.ts b/apps/web/src/validation/config/bluetooth.ts index 5ce2b5eff..26592ce4f 100644 --- a/apps/web/src/validation/config/bluetooth.ts +++ b/apps/web/src/validation/config/bluetooth.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { z } from "zod/v4"; const PairingModeEnum = z.enum( diff --git a/apps/web/src/validation/config/device.test.ts b/apps/web/src/validation/config/device.test.ts index c1b0bf6e6..20c3eac4e 100644 --- a/apps/web/src/validation/config/device.test.ts +++ b/apps/web/src/validation/config/device.test.ts @@ -1,5 +1,5 @@ import { create } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { toDeviceConfig, toDeviceFormValues } from "./device.ts"; diff --git a/apps/web/src/validation/config/device.ts b/apps/web/src/validation/config/device.ts index 2ecade3cb..f294d58aa 100644 --- a/apps/web/src/validation/config/device.ts +++ b/apps/web/src/validation/config/device.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { z } from "zod/v4"; const RoleEnum = z.enum(Protobuf.Config.Config_DeviceConfig_Role); diff --git a/apps/web/src/validation/config/display.ts b/apps/web/src/validation/config/display.ts index 2dfb5a821..ce83571c9 100644 --- a/apps/web/src/validation/config/display.ts +++ b/apps/web/src/validation/config/display.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { z } from "zod/v4"; const GpsCoordinateEnum = z.enum( diff --git a/apps/web/src/validation/config/lora.test.ts b/apps/web/src/validation/config/lora.test.ts index 68da04a1e..f5ec7213a 100644 --- a/apps/web/src/validation/config/lora.test.ts +++ b/apps/web/src/validation/config/lora.test.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { codingRateOverride, diff --git a/apps/web/src/validation/config/lora.ts b/apps/web/src/validation/config/lora.ts index 43407a3aa..9c1863d81 100644 --- a/apps/web/src/validation/config/lora.ts +++ b/apps/web/src/validation/config/lora.ts @@ -3,7 +3,7 @@ import { isRegionAllowed, type LoRaCapabilities, } from "@core/utils/loraPresets.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { z } from "zod/v4"; const ModemPresetEnum = z.enum(Protobuf.Config.Config_LoRaConfig_ModemPreset); diff --git a/apps/web/src/validation/config/network.test.ts b/apps/web/src/validation/config/network.test.ts index e2cc750c1..4e06b59a3 100644 --- a/apps/web/src/validation/config/network.test.ts +++ b/apps/web/src/validation/config/network.test.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { hasUdpBroadcast, withUdpBroadcast } from "./network.ts"; diff --git a/apps/web/src/validation/config/network.ts b/apps/web/src/validation/config/network.ts index 61a9a0859..b31135254 100644 --- a/apps/web/src/validation/config/network.ts +++ b/apps/web/src/validation/config/network.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { z } from "zod/v4"; const AddressModeEnum = z.enum( diff --git a/apps/web/src/validation/config/position.ts b/apps/web/src/validation/config/position.ts index 33419b60f..adbe937ae 100644 --- a/apps/web/src/validation/config/position.ts +++ b/apps/web/src/validation/config/position.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { z } from "zod/v4"; const GpsModeEnum = z.enum(Protobuf.Config.Config_PositionConfig_GpsMode); diff --git a/apps/web/src/validation/config/power.test.ts b/apps/web/src/validation/config/power.test.ts index 1edd3ea01..06c90762b 100644 --- a/apps/web/src/validation/config/power.test.ts +++ b/apps/web/src/validation/config/power.test.ts @@ -1,5 +1,5 @@ import { create } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { type PowerValidation, diff --git a/apps/web/src/validation/config/power.ts b/apps/web/src/validation/config/power.ts index f180a8235..3e24eb06d 100644 --- a/apps/web/src/validation/config/power.ts +++ b/apps/web/src/validation/config/power.ts @@ -1,4 +1,4 @@ -import type { Protobuf } from "@meshtastic/sdk"; +import type { Protobuf } from "@core/protobuf.ts"; import { z } from "zod/v4"; export const PowerValidationSchema = z.object({ diff --git a/apps/web/src/validation/config/security.test.ts b/apps/web/src/validation/config/security.test.ts index 5ec3e1290..af5ea0d41 100644 --- a/apps/web/src/validation/config/security.test.ts +++ b/apps/web/src/validation/config/security.test.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { fromByteArray } from "base64-js"; import { describe, expect, it } from "vitest"; import { ParsedSecuritySchema, RawSecuritySchema } from "./security.ts"; diff --git a/apps/web/src/validation/config/security.ts b/apps/web/src/validation/config/security.ts index 0a0a02aad..198b17208 100644 --- a/apps/web/src/validation/config/security.ts +++ b/apps/web/src/validation/config/security.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { type ZodType, z } from "zod/v4"; import { makePskHelpers } from "./../pskSchema.ts"; diff --git a/apps/web/src/validation/formSchemaCoverage.test.ts b/apps/web/src/validation/formSchemaCoverage.test.ts index 8fd758873..3da1e4c15 100644 --- a/apps/web/src/validation/formSchemaCoverage.test.ts +++ b/apps/web/src/validation/formSchemaCoverage.test.ts @@ -1,5 +1,5 @@ import { create, type DescMessage } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { BluetoothValidationSchema } from "./config/bluetooth.ts"; import { DeviceValidationSchema, toDeviceFormValues } from "./config/device.ts"; diff --git a/apps/web/src/validation/moduleConfig/audio.ts b/apps/web/src/validation/moduleConfig/audio.ts index ec4e40472..b5cdcad37 100644 --- a/apps/web/src/validation/moduleConfig/audio.ts +++ b/apps/web/src/validation/moduleConfig/audio.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { z } from "zod/v4"; const Audio_BaudEnum = z.enum( diff --git a/apps/web/src/validation/moduleConfig/cannedMessage.ts b/apps/web/src/validation/moduleConfig/cannedMessage.ts index 697509d1d..0dc565656 100644 --- a/apps/web/src/validation/moduleConfig/cannedMessage.ts +++ b/apps/web/src/validation/moduleConfig/cannedMessage.ts @@ -1,5 +1,6 @@ import { validateMaxByteLength } from "@core/utils/string.ts"; -import { CANNED_MESSAGES_MAX_BYTES, Protobuf } from "@meshtastic/sdk"; +import { CANNED_MESSAGES_MAX_BYTES } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { z } from "zod/v4"; const InputEventCharEnum = z.enum( diff --git a/apps/web/src/validation/moduleConfig/detectionSensor.ts b/apps/web/src/validation/moduleConfig/detectionSensor.ts index bc59a766d..84e1fe91e 100644 --- a/apps/web/src/validation/moduleConfig/detectionSensor.ts +++ b/apps/web/src/validation/moduleConfig/detectionSensor.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { z } from "zod/v4"; const detectionTriggerTypeEnum = z.enum( diff --git a/apps/web/src/validation/moduleConfig/meshBeacon.test.ts b/apps/web/src/validation/moduleConfig/meshBeacon.test.ts index 71e994f87..2184492ce 100644 --- a/apps/web/src/validation/moduleConfig/meshBeacon.test.ts +++ b/apps/web/src/validation/moduleConfig/meshBeacon.test.ts @@ -1,5 +1,5 @@ import { create } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { beaconBroadcastGate, diff --git a/apps/web/src/validation/moduleConfig/meshBeacon.ts b/apps/web/src/validation/moduleConfig/meshBeacon.ts index 47ad6b1dc..f5883cbfd 100644 --- a/apps/web/src/validation/moduleConfig/meshBeacon.ts +++ b/apps/web/src/validation/moduleConfig/meshBeacon.ts @@ -1,6 +1,6 @@ import { clone, create } from "@bufbuild/protobuf"; import { validateMaxByteLength } from "@core/utils/string.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { z } from "zod/v4"; type MeshBeaconConfig = Protobuf.ModuleConfig.ModuleConfig_MeshBeaconConfig; diff --git a/apps/web/src/validation/moduleConfig/moduleMessages.test.ts b/apps/web/src/validation/moduleConfig/moduleMessages.test.ts index fbb27286e..957612e03 100644 --- a/apps/web/src/validation/moduleConfig/moduleMessages.test.ts +++ b/apps/web/src/validation/moduleConfig/moduleMessages.test.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { CannedMessageValidationSchema } from "./cannedMessage.ts"; import { ExternalNotificationValidationSchema } from "./externalNotification.ts"; diff --git a/apps/web/src/validation/moduleConfig/remoteHardware.test.ts b/apps/web/src/validation/moduleConfig/remoteHardware.test.ts index a0000148d..b5a1a07cd 100644 --- a/apps/web/src/validation/moduleConfig/remoteHardware.test.ts +++ b/apps/web/src/validation/moduleConfig/remoteHardware.test.ts @@ -1,5 +1,5 @@ import { isMessage } from "@bufbuild/protobuf"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { REMOTE_HARDWARE_MAX_PINS, diff --git a/apps/web/src/validation/moduleConfig/remoteHardware.ts b/apps/web/src/validation/moduleConfig/remoteHardware.ts index 0727d6431..f0945ef53 100644 --- a/apps/web/src/validation/moduleConfig/remoteHardware.ts +++ b/apps/web/src/validation/moduleConfig/remoteHardware.ts @@ -1,6 +1,6 @@ import { create } from "@bufbuild/protobuf"; import { validateMaxByteLength } from "@core/utils/string.ts"; -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { z } from "zod/v4"; /** nanopb max_count for available_pins. */ diff --git a/apps/web/src/validation/moduleConfig/serial.ts b/apps/web/src/validation/moduleConfig/serial.ts index 59dc5cea2..c692fd08c 100644 --- a/apps/web/src/validation/moduleConfig/serial.ts +++ b/apps/web/src/validation/moduleConfig/serial.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { z } from "zod/v4"; const Serial_BaudEnum = z.enum( diff --git a/apps/web/src/validation/moduleConfig/tak.ts b/apps/web/src/validation/moduleConfig/tak.ts index 248598dc5..79cf8d44b 100644 --- a/apps/web/src/validation/moduleConfig/tak.ts +++ b/apps/web/src/validation/moduleConfig/tak.ts @@ -1,4 +1,4 @@ -import { Protobuf } from "@meshtastic/sdk"; +import { Protobuf } from "@core/protobuf.ts"; import { z } from "zod/v4"; const TeamEnum = z.enum(Protobuf.ATAK.Team); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3f3b8d19a..447f90ecc 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -60,9 +60,15 @@ importers: apps/web: dependencies: + '@bufbuild/protobuf': + specifier: ^2.16.0 + version: 2.16.0 '@hookform/resolvers': specifier: ^5.9.1 version: 5.9.1(@standard-schema/spec@1.1.0)(ajv@8.20.0)(react-hook-form@7.90.0(@types/react@19.3.0)(react@19.3.1))(zod@4.6.7) + '@meshtastic/protobufs': + specifier: workspace:* + version: link:../../packages/protobufs '@meshtastic/sdk': specifier: workspace:* version: link:../../packages/sdk From a735d46102c9183c926eca46b0e9d2e44e602cbc Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 08:13:02 -0500 Subject: [PATCH 10/49] feat(sdk-kmp): expose admin, telemetry, routing, nodes and sends on the facade --- apps/web/src/core/kmp/admin.test.ts | 118 ++++++++++++ apps/web/src/core/kmp/admin.ts | 128 +++++++++++++ apps/web/src/core/kmp/fakeClient.ts | 170 +++++++++++++++++- .../kotlin/org/meshtastic/sdk/js/Admin.kt | 148 +++++++++++++++ .../kotlin/org/meshtastic/sdk/js/Client.kt | 120 ++++++++++++- .../kotlin/org/meshtastic/sdk/js/Data.kt | 122 +++++++++++++ 6 files changed, 798 insertions(+), 8 deletions(-) create mode 100644 apps/web/src/core/kmp/admin.test.ts create mode 100644 apps/web/src/core/kmp/admin.ts create mode 100644 packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Admin.kt create mode 100644 packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Data.kt diff --git a/apps/web/src/core/kmp/admin.test.ts b/apps/web/src/core/kmp/admin.test.ts new file mode 100644 index 000000000..571afd834 --- /dev/null +++ b/apps/web/src/core/kmp/admin.test.ts @@ -0,0 +1,118 @@ +import { Protobuf } from "@core/protobuf.ts"; +import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; +import { Result } from "better-result"; +import { describe, expect, it } from "vitest"; +import { + adminMessage, + editSettings, + getConfig, + getText, + sendAdmin, +} from "./admin.ts"; +import { adminFailed, adminOk, FakeKmpClient } from "./fakeClient.ts"; + +function decodeSent(bytes: Uint8Array): Protobuf.Admin.AdminMessage { + return fromBinary(Protobuf.Admin.AdminMessageSchema, bytes); +} + +describe("sendAdmin", () => { + it("encodes the variant and sends it to the local node", async () => { + const client = new FakeKmpClient(); + const result = await sendAdmin(client, { + case: "rebootSeconds", + value: 5, + }); + expect(Result.isOk(result)).toBe(true); + const admin = client.admin(); + expect(admin.sent.map((m) => decodeSent(m).payloadVariant)).toEqual([ + { case: "rebootSeconds", value: 5 }, + ]); + }); + + it("targets a remote node when dest is given", async () => { + const client = new FakeKmpClient(); + await sendAdmin(client, { case: "shutdownSeconds", value: 1 }, 0x1234); + expect(client.admin(0x1234).sent).toHaveLength(1); + expect(client.admins.has(0)).toBe(false); + }); + + it("maps a failed result to an error carrying the reason", async () => { + const client = new FakeKmpClient(); + client.admin().results.push(adminFailed("timeout")); + const result = await sendAdmin(client, { + case: "nodedbReset", + value: true, + }); + expect(Result.isError(result)).toBe(true); + if (Result.isError(result)) { + expect(result.error.message).toContain("timeout"); + } + }); +}); + +describe("getConfig", () => { + it("decodes the returned Config", async () => { + const client = new FakeKmpClient(); + const config = create(Protobuf.Config.ConfigSchema, { + payloadVariant: { + case: "lora", + value: { region: Protobuf.Config.Config_LoRaConfig_RegionCode.EU_868 }, + }, + }); + client + .admin() + .results.push(adminOk(toBinary(Protobuf.Config.ConfigSchema, config))); + const result = await getConfig( + client, + Protobuf.Admin.AdminMessage_ConfigType.LORA_CONFIG, + ); + expect(Result.isOk(result)).toBe(true); + if (Result.isOk(result)) { + expect(result.value.payloadVariant.case).toBe("lora"); + } + }); + + it("fails on an empty response", async () => { + const client = new FakeKmpClient(); + client.admin().results.push(adminOk()); + const result = await getConfig( + client, + Protobuf.Admin.AdminMessage_ConfigType.LORA_CONFIG, + ); + expect(Result.isError(result)).toBe(true); + }); +}); + +describe("getText", () => { + it("returns the text answer", async () => { + const client = new FakeKmpClient(); + client.admin().results.push(adminOk(undefined, "a|b|c")); + const result = await getText(client, { + case: "getCannedMessageModuleMessagesRequest", + value: true, + }); + expect(result).toEqual(Result.ok("a|b|c")); + }); +}); + +describe("editSettings", () => { + it("sends every message in one transaction", async () => { + const client = new FakeKmpClient(); + const messages = [ + adminMessage({ case: "beginEditSettings", value: true }), + adminMessage({ + case: "setOwner", + value: create(Protobuf.Mesh.UserSchema, { longName: "Alice" }), + }), + ]; + const result = await editSettings(client, messages); + expect(Result.isOk(result)).toBe(true); + expect( + client + .admin() + .transactions.map((t) => + t.map((m) => decodeSent(m).payloadVariant.case), + ), + ).toEqual([["beginEditSettings", "setOwner"]]); + }); +}); diff --git a/apps/web/src/core/kmp/admin.ts b/apps/web/src/core/kmp/admin.ts new file mode 100644 index 000000000..b582817ff --- /dev/null +++ b/apps/web/src/core/kmp/admin.ts @@ -0,0 +1,128 @@ +import { Protobuf } from "@core/protobuf.ts"; +import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; +import type { AdminResultJs, MeshtasticClient } from "@meshtastic/sdk-kmp"; +import { Result } from "better-result"; + +export type AdminVariant = Protobuf.Admin.AdminMessage["payloadVariant"]; + +export class AdminError extends Error { + constructor(readonly reason: string) { + super(`Admin request failed: ${reason}`); + this.name = "AdminError"; + } +} + +export function encodeAdminMessage( + message: Protobuf.Admin.AdminMessage, +): Uint8Array { + return toBinary(Protobuf.Admin.AdminMessageSchema, message); +} + +export function adminMessage( + payloadVariant: AdminVariant, +): Protobuf.Admin.AdminMessage { + return create(Protobuf.Admin.AdminMessageSchema, { payloadVariant }); +} + +export function toResult(result: AdminResultJs): Result { + return result.ok + ? Result.ok(result) + : Result.err(new AdminError(result.reason ?? "unknown")); +} + +/** Sends one admin message to `dest` (the local node when omitted). */ +export async function sendAdmin( + client: MeshtasticClient, + payloadVariant: AdminVariant, + dest?: number, +): Promise> { + return toResult( + await client + .admin(dest) + .send(encodeAdminMessage(adminMessage(payloadVariant))), + ); +} + +/** Sends admin messages as one begin/commit settings transaction. */ +export async function editSettings( + client: MeshtasticClient, + messages: readonly Protobuf.Admin.AdminMessage[], + dest?: number, +): Promise> { + const result = await client + .admin(dest) + .editSettings(messages.map(encodeAdminMessage)); + return result.ok + ? Result.ok(undefined) + : Result.err(new AdminError(result.reason ?? "unknown")); +} + +export async function getConfig( + client: MeshtasticClient, + type: Protobuf.Admin.AdminMessage_ConfigType, + dest?: number, +): Promise> { + const result = await sendAdmin( + client, + { case: "getConfigRequest", value: type }, + dest, + ); + return decodeValue(result, Protobuf.Config.ConfigSchema); +} + +export async function getModuleConfig( + client: MeshtasticClient, + type: Protobuf.Admin.AdminMessage_ModuleConfigType, + dest?: number, +): Promise> { + const result = await sendAdmin( + client, + { case: "getModuleConfigRequest", value: type }, + dest, + ); + return decodeValue(result, Protobuf.ModuleConfig.ModuleConfigSchema); +} + +export async function getDeviceMetadata( + client: MeshtasticClient, + dest?: number, +): Promise> { + const result = await sendAdmin( + client, + { case: "getDeviceMetadataRequest", value: true }, + dest, + ); + return decodeValue(result, Protobuf.Mesh.DeviceMetadataSchema); +} + +export async function getOwner( + client: MeshtasticClient, + dest?: number, +): Promise> { + const result = await sendAdmin( + client, + { case: "getOwnerRequest", value: true }, + dest, + ); + return decodeValue(result, Protobuf.Mesh.UserSchema); +} + +export async function getText( + client: MeshtasticClient, + payloadVariant: AdminVariant, + dest?: number, +): Promise> { + const result = await sendAdmin(client, payloadVariant, dest); + if (Result.isError(result)) return Result.err(result.error); + return Result.ok(result.value.text ?? ""); +} + +function decodeValue[0]>( + result: Result, + schema: T, +): Result>, Error> { + if (Result.isError(result)) return Result.err(result.error); + const bytes = result.value.value; + if (!bytes) return Result.err(new AdminError("empty-response")); + return Result.ok(fromBinary(schema, bytes)); +} diff --git a/apps/web/src/core/kmp/fakeClient.ts b/apps/web/src/core/kmp/fakeClient.ts index b6535517f..39ac4bf08 100644 --- a/apps/web/src/core/kmp/fakeClient.ts +++ b/apps/web/src/core/kmp/fakeClient.ts @@ -1,4 +1,12 @@ -import type { ConnectionStateJs, MeshtasticClient } from "@meshtastic/sdk-kmp"; +import type { + AdminJs, + AdminResultJs, + ConfigBundleJs, + ConnectionStateJs, + MeshtasticClient, + NodeChangeJs, + SendOutcomeJs, +} from "@meshtastic/sdk-kmp"; export function state( kind: string, @@ -16,17 +24,64 @@ export function state( }; } +export function adminOk(value?: Uint8Array, text?: string): AdminResultJs { + return { ok: true, reason: null, value: value ?? null, text: text ?? null }; +} + +export function adminFailed(reason: string): AdminResultJs { + return { ok: false, reason, value: null, text: null }; +} + +type Listeners = Set<(value: T) => void>; + +/** + * A scripted stand-in for the facade's admin API: records every message + * and answers from `results`, or `ok` once that runs out. + */ +export class FakeAdmin implements AdminJs { + readonly sent: Uint8Array[] = []; + readonly transactions: Uint8Array[][] = []; + readonly results: AdminResultJs[] = []; + + constructor(readonly dest: number) {} + + async send(adminMessage: Uint8Array): Promise { + this.sent.push(adminMessage); + return this.results.shift() ?? adminOk(); + } + + async editSettings(adminMessages: Uint8Array[]): Promise { + this.transactions.push(adminMessages); + this.sent.push(...adminMessages); + return this.results.shift() ?? adminOk(); + } +} + /** * A scripted stand-in for the facade's client, for tests: callers push - * frames and states and record what the web client sent. + * frames, states, nodes and packets, and record what the web client sent. */ export class FakeKmpClient implements MeshtasticClient { connectionState: ConnectionStateJs = state("disconnected"); myNodeNum: number | null = null; + configBundle: ConfigBundleJs | null = null; + channels: Uint8Array[] | null = null; + nodeList: Uint8Array[] = []; readonly sent: Uint8Array[] = []; + readonly texts: Array<{ text: string; to: number; channel: number }> = []; + readonly packets: Uint8Array[] = []; + readonly requests: Array<{ kind: string; nodeNum: number }> = []; readonly disconnects: number[] = []; - private frameListeners = new Set<(bytes: Uint8Array) => void>(); - private stateListeners = new Set<(s: ConnectionStateJs) => void>(); + readonly admins = new Map(); + sendOutcome: SendOutcomeJs = { id: 1, ok: true, reason: null }; + adminResult: AdminResultJs = adminOk(); + private frameListeners: Listeners = new Set(); + private stateListeners: Listeners = new Set(); + private bundleListeners: Listeners = new Set(); + private channelListeners: Listeners = new Set(); + private nodeListeners: Listeners = new Set(); + private packetListeners: Listeners = new Set(); + private telemetryListeners = new Map>(); async connect(): Promise { this.setState(state("connected")); @@ -43,11 +98,86 @@ export class FakeKmpClient implements MeshtasticClient { return () => this.stateListeners.delete(cb); } + onConfigBundle(cb: (bundle: ConfigBundleJs | null) => void): () => void { + this.bundleListeners.add(cb); + cb(this.configBundle); + return () => this.bundleListeners.delete(cb); + } + + onChannels(cb: (channels: Uint8Array[] | null) => void): () => void { + this.channelListeners.add(cb); + cb(this.channels); + return () => this.channelListeners.delete(cb); + } + + onNodeChange(cb: (change: NodeChangeJs) => void): () => void { + this.nodeListeners.add(cb); + return () => this.nodeListeners.delete(cb); + } + + onPacket(cb: (bytes: Uint8Array) => void): () => void { + this.packetListeners.add(cb); + return () => this.packetListeners.delete(cb); + } + + onTelemetry(nodeNum: number, cb: (bytes: Uint8Array) => void): () => void { + const listeners = this.telemetryListeners.get(nodeNum) ?? new Set(); + listeners.add(cb); + this.telemetryListeners.set(nodeNum, listeners); + return () => listeners.delete(cb); + } + onFromRadio(cb: (bytes: Uint8Array) => void): () => void { this.frameListeners.add(cb); return () => this.frameListeners.delete(cb); } + async nodes(): Promise { + return this.nodeList; + } + + admin(dest = 0): FakeAdmin { + const existing = this.admins.get(dest); + if (existing) return existing; + const created = new FakeAdmin(dest); + this.admins.set(dest, created); + return created; + } + + async sendText( + text: string, + to: number, + channel: number, + ): Promise { + this.texts.push({ text, to, channel }); + return this.sendOutcome; + } + + async sendPacket(meshPacket: Uint8Array): Promise { + this.packets.push(meshPacket); + return this.sendOutcome; + } + + async requestNodeInfo(nodeNum: number): Promise { + this.requests.push({ kind: "nodeInfo", nodeNum }); + return this.sendOutcome; + } + + async requestPosition(nodeNum: number): Promise { + this.requests.push({ kind: "position", nodeNum }); + return this.sendOutcome; + } + + async traceRoute(dest: number): Promise { + this.requests.push({ kind: "traceRoute", nodeNum: dest }); + return this.adminResult; + } + + async requestTelemetry(kind: string, nodeNum = 0): Promise { + this.requests.push({ kind: `telemetry:${kind}`, nodeNum }); + return this.adminResult; + } + sendRaw(toRadio: Uint8Array): void { if (this.connectionState.kind !== "connected") { const error = new Error("Client not connected"); @@ -63,6 +193,38 @@ export class FakeKmpClient implements MeshtasticClient { } } + emitPacket(bytes: Uint8Array): void { + for (const cb of this.packetListeners) { + cb(bytes); + } + } + + emitNodeChange(change: NodeChangeJs): void { + for (const cb of this.nodeListeners) { + cb(change); + } + } + + emitTelemetry(nodeNum: number, bytes: Uint8Array): void { + for (const cb of this.telemetryListeners.get(nodeNum) ?? []) { + cb(bytes); + } + } + + setConfigBundle(bundle: ConfigBundleJs | null): void { + this.configBundle = bundle; + for (const cb of this.bundleListeners) { + cb(bundle); + } + } + + setChannels(channels: Uint8Array[] | null): void { + this.channels = channels; + for (const cb of this.channelListeners) { + cb(channels); + } + } + setState(next: ConnectionStateJs): void { this.connectionState = next; for (const cb of this.stateListeners) { diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Admin.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Admin.kt new file mode 100644 index 000000000..97b2e30fc --- /dev/null +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Admin.kt @@ -0,0 +1,148 @@ +@file:OptIn(ExperimentalJsExport::class) + +package org.meshtastic.sdk.js + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.promise +import org.khronos.webgl.Uint8Array +import org.meshtastic.proto.AdminMessage +import org.meshtastic.proto.Channel +import org.meshtastic.proto.Config +import org.meshtastic.proto.DeviceMetadata +import org.meshtastic.proto.ModuleConfig +import org.meshtastic.proto.User +import org.meshtastic.sdk.AdminApi +import org.meshtastic.sdk.AdminEdit +import org.meshtastic.sdk.AdminResult +import org.meshtastic.sdk.ChannelIndex +import org.meshtastic.sdk.NodeId +import kotlin.js.ExperimentalJsExport +import kotlin.js.JsExport +import kotlin.js.Promise +import kotlin.time.Duration.Companion.seconds + +/** + * Outcome of an admin request. `value` carries the encoded response message + * for getters that answer with a protobuf, `text` for those that answer + * with a string. + */ +@JsExport +external interface AdminResultJs { + val ok: Boolean + val reason: String? + val value: Uint8Array? + val text: String? +} + +/** Admin messages addressed to one node; `MeshtasticClient.admin(dest)`. */ +@JsExport +class AdminJs internal constructor(private val api: AdminApi, private val scope: CoroutineScope) { + /** Sends one encoded `AdminMessage` and waits for its result. */ + fun send(adminMessage: Uint8Array): Promise = scope.promise { + api.dispatch(AdminMessage.ADAPTER.decode(adminMessage.toByteArray())) + } + + /** + * Sends encoded `AdminMessage`s as one settings transaction. Config, + * module config, owner, channel, favorite and ignored writes go between + * `begin_edit_settings` and `commit_edit_settings`; anything else is + * sent before them on its own. + */ + fun editSettings(adminMessages: Array): Promise = scope.promise { + val decoded = adminMessages.map { AdminMessage.ADAPTER.decode(it.toByteArray()) } + val (batched, standalone) = decoded.partition { it.isBatchable() } + for (message in standalone) { + val result = api.dispatch(message) + if (!result.ok) return@promise result + } + if (batched.isEmpty()) return@promise AdminResult.Success(Unit).toJs() + api.editSettings { for (message in batched) apply(message) }.toJs() + } +} + +private fun AdminMessage.isBatchable(): Boolean = + set_config != null || set_module_config != null || set_owner != null || set_channel != null || + set_favorite_node != null || remove_favorite_node != null || + set_ignored_node != null || remove_ignored_node != null + +private suspend fun AdminEdit.apply(message: AdminMessage) { + message.set_config?.let { setConfig(it) } + message.set_module_config?.let { setModuleConfig(it) } + message.set_owner?.let { setOwner(it) } + message.set_channel?.let { setChannel(it) } + message.set_favorite_node?.let { setFavorite(NodeId(it), true) } + message.remove_favorite_node?.let { setFavorite(NodeId(it), false) } + message.set_ignored_node?.let { setIgnored(NodeId(it), true) } + message.remove_ignored_node?.let { setIgnored(NodeId(it), false) } +} + +private suspend fun AdminApi.dispatch(message: AdminMessage): AdminResultJs { + message.set_config?.let { return setConfig(it).toJs() } + message.set_module_config?.let { return setModuleConfig(it).toJs() } + message.set_owner?.let { return setOwner(it).toJs() } + message.set_channel?.let { return setChannel(it).toJs() } + message.set_fixed_position?.let { return setFixedPosition(it).toJs() } + if (message.remove_fixed_position == true) return removeFixedPosition().toJs() + message.set_canned_message_module_messages?.let { return setCannedMessages(it).toJs() } + message.set_ringtone_message?.let { return setRingtone(it).toJs() } + message.set_favorite_node?.let { return setFavorite(NodeId(it), true).toJs() } + message.remove_favorite_node?.let { return setFavorite(NodeId(it), false).toJs() } + message.set_ignored_node?.let { return setIgnored(NodeId(it), true).toJs() } + message.remove_ignored_node?.let { return setIgnored(NodeId(it), false).toJs() } + message.remove_by_nodenum?.let { return removeNode(NodeId(it)).toJs() } + message.get_config_request?.let { return getConfig(it).toJs { Config.ADAPTER.encode(it).toUint8Array() } } + message.get_module_config_request?.let { + return getModuleConfig(it).toJs { ModuleConfig.ADAPTER.encode(it).toUint8Array() } + } + if (message.get_owner_request == true) return getOwner().toJs { User.ADAPTER.encode(it).toUint8Array() } + message.get_channel_request?.let { + return getChannel(ChannelIndex(it - 1)).toJs { Channel.ADAPTER.encode(it).toUint8Array() } + } + if (message.get_device_metadata_request == true) { + return getDeviceMetadata().toJs { DeviceMetadata.ADAPTER.encode(it).toUint8Array() } + } + if (message.get_canned_message_module_messages_request == true) return getCannedMessages().toJsText { it } + if (message.get_ringtone_request == true) return getRingtone().toJsText { it } + message.reboot_seconds?.let { return reboot(it.seconds).toJs() } + message.reboot_ota_seconds?.let { return rebootOta(it.seconds).toJs() } + message.shutdown_seconds?.let { return shutdown(it.seconds).toJs() } + message.factory_reset_device?.let { if (it != 0) return factoryReset().toJs() } + if (message.nodedb_reset == true) return nodeDbReset().toJs() + if (message.enter_dfu_mode_request == true) return enterDfuMode().toJs() + message.set_time_only?.let { return setTimeOnly(it).toJs() } + return failure("unsupported") +} + +internal fun AdminResult.toJs(encode: (T) -> Uint8Array? = { null }): AdminResultJs = toJs(encode) { null } + +internal fun AdminResult.toJsText(text: (T) -> String?): AdminResultJs = toJs({ null }, text) + +private fun AdminResult.toJs(encode: (T) -> Uint8Array?, text: (T) -> String?): AdminResultJs { + val result = jso() + result.ok = this is AdminResult.Success + result.reason = null + result.value = null + result.text = null + when (this) { + is AdminResult.Success -> { + result.value = encode(value) + result.text = text(value) + } + AdminResult.SessionKeyExpired -> result.reason = "session-key-expired" + AdminResult.Unauthorized -> result.reason = "unauthorized" + AdminResult.Timeout -> result.reason = "timeout" + AdminResult.RateLimited -> result.reason = "rate-limited" + AdminResult.NodeUnreachable -> result.reason = "node-unreachable" + is AdminResult.Failed -> result.reason = routingError.name + } + return result.unsafeCast() +} + +internal fun failure(reason: String): AdminResultJs { + val result = jso() + result.ok = false + result.reason = reason + result.value = null + result.text = null + return result.unsafeCast() +} diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt index 7d5c81258..c96e1d748 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt @@ -5,15 +5,34 @@ package org.meshtastic.sdk.js import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.promise +import okio.ByteString import org.khronos.webgl.Uint8Array +import org.meshtastic.proto.AirQualityMetrics +import org.meshtastic.proto.Data +import org.meshtastic.proto.DeviceMetrics +import org.meshtastic.proto.EnvironmentMetrics +import org.meshtastic.proto.HealthMetrics +import org.meshtastic.proto.HostMetrics +import org.meshtastic.proto.LocalStats +import org.meshtastic.proto.MeshPacket +import org.meshtastic.proto.PortNum +import org.meshtastic.proto.PowerMetrics +import org.meshtastic.proto.RouteDiscovery +import org.meshtastic.proto.Telemetry import org.meshtastic.proto.ToRadio +import org.meshtastic.proto.TrafficManagementStats import org.meshtastic.sdk.AutoReconnectConfig +import org.meshtastic.sdk.ChannelIndex import org.meshtastic.sdk.InMemoryStorageProvider +import org.meshtastic.sdk.MessageHandle +import org.meshtastic.sdk.NodeId import org.meshtastic.sdk.RadioClient import org.meshtastic.sdk.RadioTransport +import org.meshtastic.sdk.RoutingApi import kotlin.js.ExperimentalJsExport import kotlin.js.JsExport import kotlin.js.Promise @@ -42,16 +61,95 @@ class MeshtasticClient internal constructor(transport: RadioTransport, private v val myNodeNum: Int? get() = client.ownNode.value?.num - fun onConnectionState(cb: (ConnectionStateJs) -> Unit): () -> Unit { - val job = client.connection.onEach { cb(it.toJs(maxAttempts)) }.launchIn(scope) - return { job.cancel() } - } + /** The handshake's config bundle, or null before the device has delivered one. */ + val configBundle: ConfigBundleJs? get() = client.configBundle.value?.toJs() + + /** The device's channels as encoded `Channel`s, or null before the handshake delivers them. */ + val channels: Array? get() = client.channels.value?.toJs() + + fun onConnectionState(cb: (ConnectionStateJs) -> Unit): () -> Unit = + client.connection.onEach { cb(it.toJs(maxAttempts)) }.subscribe() + + fun onConfigBundle(cb: (ConfigBundleJs?) -> Unit): () -> Unit = + client.configBundle.onEach { cb(it?.toJs()) }.subscribe() + + fun onChannels(cb: (Array?) -> Unit): () -> Unit = + client.channels.onEach { cb(it?.toJs()) }.subscribe() + + fun onNodeChange(cb: (NodeChangeJs) -> Unit): () -> Unit = + client.nodes.onEach { cb(it.toJs()) }.subscribe() + + /** Every decoded `MeshPacket` the device forwards, encoded. */ + fun onPacket(cb: (Uint8Array) -> Unit): () -> Unit = + client.packets.onEach { cb(MeshPacket.ADAPTER.encode(it).toUint8Array()) }.subscribe() + + fun onTelemetry(nodeNum: Int, cb: (Uint8Array) -> Unit): () -> Unit = + client.telemetry.observe(NodeId(nodeNum)).onEach { cb(Telemetry.ADAPTER.encode(it).toUint8Array()) }.subscribe() fun onFromRadio(cb: (Uint8Array) -> Unit): () -> Unit { frameListeners.add(cb) return { frameListeners.remove(cb) } } + /** Every `NodeInfo` the SDK holds, encoded. */ + fun nodes(): Promise> = scope.promise { + client.nodeSnapshot().values.map { it.encodeJs() }.toTypedArray() + } + + /** Admin messages for the local node, or for `dest` when given. */ + fun admin(dest: Int = 0): AdminJs = + AdminJs(if (dest == 0) client.admin else client.admin.forNode(NodeId(dest)), scope) + + fun sendText(text: String, to: Int, channel: Int, replyId: Int = 0): Promise = + sending { client.sendText(text, NodeId(to), ChannelIndex(channel), replyId) } + + /** Sends an encoded `MeshPacket`; the SDK assigns the id and reports the outcome. */ + fun sendPacket(meshPacket: Uint8Array): Promise = + sending { client.send(MeshPacket.ADAPTER.decode(meshPacket.toByteArray())) } + + fun requestNodeInfo(nodeNum: Int): Promise = sending { client.requestNodeInfo(NodeId(nodeNum)) } + + fun requestPosition(nodeNum: Int): Promise = sending { + client.send( + MeshPacket.Builder().also { packet -> + packet.to = nodeNum + packet.want_ack = true + packet.decoded = Data.Builder().also { data -> + data.portnum = PortNum.POSITION_APP + data.payload = ByteString.EMPTY + data.want_response = true + }.build() + }.build(), + ) + } + + /** Trace the route to `dest`; `value` is the encoded `RouteDiscovery`. */ + fun traceRoute(dest: Int, hopLimit: Int = RoutingApi.DEFAULT_HOP_LIMIT): Promise = scope.promise { + client.routing.traceRoute(NodeId(dest), hopLimit).toJs { RouteDiscovery.ADAPTER.encode(it).toUint8Array() } + } + + /** + * Requests one telemetry `kind` (`device`, `environment`, `power`, + * `airQuality`, `localStats`, `health`, `host`, `trafficManagement`) + * from `nodeNum`; `value` is the encoded metrics message. + */ + fun requestTelemetry(kind: String, nodeNum: Int = 0): Promise = scope.promise { + val node = NodeId(nodeNum) + val telemetry = client.telemetry + when (kind) { + "device" -> telemetry.requestDevice(node).toJs { DeviceMetrics.ADAPTER.encode(it).toUint8Array() } + "environment" -> telemetry.requestEnvironment(node).toJs { EnvironmentMetrics.ADAPTER.encode(it).toUint8Array() } + "power" -> telemetry.requestPower(node).toJs { PowerMetrics.ADAPTER.encode(it).toUint8Array() } + "airQuality" -> telemetry.requestAirQuality(node).toJs { AirQualityMetrics.ADAPTER.encode(it).toUint8Array() } + "localStats" -> telemetry.requestLocalStats().toJs { LocalStats.ADAPTER.encode(it).toUint8Array() } + "health" -> telemetry.requestHealth(node).toJs { HealthMetrics.ADAPTER.encode(it).toUint8Array() } + "host" -> telemetry.requestHost(node).toJs { HostMetrics.ADAPTER.encode(it).toUint8Array() } + "trafficManagement" -> + telemetry.requestTrafficManagement(node).toJs { TrafficManagementStats.ADAPTER.encode(it).toUint8Array() } + else -> failure("unsupported") + } + } + fun sendRaw(toRadio: Uint8Array) { try { client.sendRaw(ToRadio.ADAPTER.decode(toRadio.toByteArray())) @@ -59,6 +157,20 @@ class MeshtasticClient internal constructor(transport: RadioTransport, private v throw e.toJsError().unsafeCast() } } + + private fun sending(send: suspend () -> MessageHandle): Promise = scope.promise { + val handle = try { + send() + } catch (e: Throwable) { + throw e.toJsError().unsafeCast() + } + handle.await().toJs(handle.id.raw) + } + + private fun Flow.subscribe(): () -> Unit { + val job = launchIn(scope) + return { job.cancel() } + } } @JsExport diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Data.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Data.kt new file mode 100644 index 000000000..d0aef815c --- /dev/null +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Data.kt @@ -0,0 +1,122 @@ +@file:OptIn(ExperimentalJsExport::class) + +package org.meshtastic.sdk.js + +import org.khronos.webgl.Uint8Array +import org.meshtastic.proto.Channel +import org.meshtastic.proto.Config +import org.meshtastic.proto.DeviceMetadata +import org.meshtastic.proto.ModuleConfig +import org.meshtastic.proto.MyNodeInfo +import org.meshtastic.proto.NodeInfo +import org.meshtastic.sdk.ConfigBundle +import org.meshtastic.sdk.NodeChange +import org.meshtastic.sdk.SendFailure +import org.meshtastic.sdk.SendOutcome +import kotlin.js.ExperimentalJsExport +import kotlin.js.JsExport + +/** The device's config as the handshake delivered it; every field is an encoded protobuf. */ +@JsExport +external interface ConfigBundleJs { + val myInfo: Uint8Array + val metadata: Uint8Array + val configs: Array + val moduleConfigs: Array +} + +/** + * One change to the node database. `snapshot` carries `nodes`, `added` and + * `updated` carry `node` (an encoded `NodeInfo`), `removed`, `went-offline` + * and `came-online` carry `nodeNum`. + */ +@JsExport +external interface NodeChangeJs { + val kind: String + val nodes: Array? + val node: Uint8Array? + val nodeNum: Int +} + +/** Terminal state of a sent packet. */ +@JsExport +external interface SendOutcomeJs { + val id: Int + val ok: Boolean + val reason: String? +} + +internal fun ConfigBundle.toJs(): ConfigBundleJs { + val bundle = jso() + bundle.myInfo = MyNodeInfo.ADAPTER.encode(myInfo).toUint8Array() + bundle.metadata = DeviceMetadata.ADAPTER.encode(metadata).toUint8Array() + bundle.configs = configs.map { Config.ADAPTER.encode(it).toUint8Array() }.toTypedArray() + bundle.moduleConfigs = moduleConfigs.map { ModuleConfig.ADAPTER.encode(it).toUint8Array() }.toTypedArray() + return bundle.unsafeCast() +} + +internal fun List.toJs(): Array = map { Channel.ADAPTER.encode(it).toUint8Array() }.toTypedArray() + +internal fun NodeInfo.encodeJs(): Uint8Array = NodeInfo.ADAPTER.encode(this).toUint8Array() + +internal fun NodeChange.toJs(): NodeChangeJs { + val change = jso() + change.nodes = null + change.node = null + change.nodeNum = 0 + when (this) { + is NodeChange.Snapshot -> { + change.kind = "snapshot" + change.nodes = nodes.values.map { it.encodeJs() }.toTypedArray() + } + is NodeChange.Added -> { + change.kind = "added" + change.node = node.encodeJs() + change.nodeNum = node.num + } + is NodeChange.Updated -> { + change.kind = "updated" + change.node = node.encodeJs() + change.nodeNum = node.num + } + is NodeChange.Removed -> { + change.kind = "removed" + change.nodeNum = nodeId.raw + } + is NodeChange.WentOffline -> { + change.kind = "went-offline" + change.nodeNum = nodeId.raw + } + is NodeChange.CameOnline -> { + change.kind = "came-online" + change.nodeNum = nodeId.raw + } + } + return change.unsafeCast() +} + +internal fun SendOutcome.toJs(id: Int): SendOutcomeJs { + val outcome = jso() + outcome.id = id + outcome.ok = this is SendOutcome.Success + outcome.reason = when (this) { + SendOutcome.Success -> null + is SendOutcome.Failure -> reason.kind() + } + return outcome.unsafeCast() +} + +internal fun SendFailure.kind(): String = when (this) { + SendFailure.NoRoute -> "no-route" + SendFailure.MaxRetransmit -> "max-retransmit" + SendFailure.Timeout -> "timeout" + SendFailure.DutyCycleLimit -> "duty-cycle-limit" + SendFailure.Disconnected -> "disconnected" + SendFailure.HandshakeFailed -> "handshake-failed" + SendFailure.Cancelled -> "cancelled" + SendFailure.IdCollision -> "id-collision" + SendFailure.AckTimeout -> "ack-timeout" + is SendFailure.QueueRejected -> "queue-rejected" + is SendFailure.Other -> routingError.name + is SendFailure.Unknown -> message +} From f21603f8910a785d4e24cba7a5842fc06176bae9 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 08:27:03 -0500 Subject: [PATCH 11/49] refactor(web): port ConfigEditor and its hooks into core/kmp --- .../src/components/Dialog/ImportDialog.tsx | 2 +- .../LockdownDialog/LockdownDialog.test.tsx | 3 + .../PageComponents/Channels/Channels.tsx | 3 +- .../ModuleConfig/AmbientLighting.tsx | 2 +- .../PageComponents/ModuleConfig/Audio.tsx | 2 +- .../ModuleConfig/CannedMessage.tsx | 6 +- .../ModuleConfig/DetectionSensor.tsx | 2 +- .../ModuleConfig/ExternalNotification.tsx | 2 +- .../PageComponents/ModuleConfig/MQTT.tsx | 2 +- .../ModuleConfig/MeshBeacon.tsx | 3 +- .../ModuleConfig/NeighborInfo.tsx | 2 +- .../ModuleConfig/Paxcounter.tsx | 2 +- .../PageComponents/ModuleConfig/RangeTest.tsx | 3 +- .../ModuleConfig/RemoteHardware.tsx | 2 +- .../PageComponents/ModuleConfig/Serial.tsx | 2 +- .../ModuleConfig/StoreForward.tsx | 2 +- .../PageComponents/ModuleConfig/Tak.tsx | 2 +- .../PageComponents/ModuleConfig/Telemetry.tsx | 2 +- .../ModuleConfig/useStagedAdminString.ts | 2 +- .../PageComponents/Settings/Bluetooth.tsx | 2 +- .../PageComponents/Settings/Device/index.tsx | 2 +- .../PageComponents/Settings/Display.tsx | 2 +- .../PageComponents/Settings/LoRa.test.tsx | 2 +- .../PageComponents/Settings/LoRa.tsx | 2 +- .../Settings/Network/Network.test.tsx | 2 +- .../PageComponents/Settings/Network/index.tsx | 2 +- .../PageComponents/Settings/Position.test.tsx | 2 +- .../PageComponents/Settings/Position.tsx | 2 +- .../PageComponents/Settings/Power.test.tsx | 2 +- .../PageComponents/Settings/Power.tsx | 2 +- .../Settings/Security/Security.test.tsx | 2 +- .../Settings/Security/Security.tsx | 2 +- .../PageComponents/Settings/User.test.tsx | 2 +- .../PageComponents/Settings/User.tsx | 2 +- apps/web/src/core/hooks/useBeaconOffers.ts | 3 +- .../src/core/hooks/useDeviceCapabilities.ts | 3 +- apps/web/src/core/hooks/useLockdown.ts | 3 +- .../src/core/hooks/useNodeTelemetryHistory.ts | 3 +- apps/web/src/core/hooks/useNodesAsProto.ts | 3 +- apps/web/src/core/kmp/configEditor.test.ts | 488 ++++++++++++++ apps/web/src/core/kmp/configEditor.ts | 636 ++++++++++++++++++ apps/web/src/core/kmp/configEditorIo.test.ts | 151 +++++ apps/web/src/core/kmp/configEditorIo.ts | 170 +++++ apps/web/src/core/kmp/hooks/index.ts | 8 + .../web/src/core/kmp/hooks/useConfigEditor.ts | 12 + .../src/core/kmp/hooks/useModuleMessages.ts | 82 +++ apps/web/src/core/kmp/hooks/useSignal.ts | 11 + apps/web/src/core/kmp/moduleMessages.ts | 74 ++ apps/web/src/core/kmp/signals.ts | 39 ++ .../src/pages/Connections/useConnections.ts | 3 + apps/web/src/pages/Settings/BackupRestore.tsx | 9 +- apps/web/src/pages/Settings/CleanNodeDb.tsx | 3 +- apps/web/src/pages/Settings/DeviceConfig.tsx | 2 +- apps/web/src/pages/Settings/ModuleConfig.tsx | 2 +- apps/web/src/pages/Settings/index.tsx | 2 +- apps/web/src/tests/renderSettingsForm.tsx | 4 +- 56 files changed, 1734 insertions(+), 53 deletions(-) create mode 100644 apps/web/src/core/kmp/configEditor.test.ts create mode 100644 apps/web/src/core/kmp/configEditor.ts create mode 100644 apps/web/src/core/kmp/configEditorIo.test.ts create mode 100644 apps/web/src/core/kmp/configEditorIo.ts create mode 100644 apps/web/src/core/kmp/hooks/index.ts create mode 100644 apps/web/src/core/kmp/hooks/useConfigEditor.ts create mode 100644 apps/web/src/core/kmp/hooks/useModuleMessages.ts create mode 100644 apps/web/src/core/kmp/hooks/useSignal.ts create mode 100644 apps/web/src/core/kmp/moduleMessages.ts create mode 100644 apps/web/src/core/kmp/signals.ts diff --git a/apps/web/src/components/Dialog/ImportDialog.tsx b/apps/web/src/components/Dialog/ImportDialog.tsx index a7e3f7708..4f8393fa1 100644 --- a/apps/web/src/components/Dialog/ImportDialog.tsx +++ b/apps/web/src/components/Dialog/ImportDialog.tsx @@ -23,7 +23,7 @@ import { useDevice } from "@core/stores"; import type { BeaconJoinPlan } from "@core/utils/beaconJoin.ts"; import { channelSetFromUrl } from "@core/utils/channelUrl.ts"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor } from "@meshtastic/sdk-react"; +import { useConfigEditor } from "@core/kmp/hooks"; import { useNavigate } from "@tanstack/react-router"; import { useEffect, useState } from "react"; import { Trans, useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/Dialog/LockdownDialog/LockdownDialog.test.tsx b/apps/web/src/components/Dialog/LockdownDialog/LockdownDialog.test.tsx index 459e29de8..dfcd893ec 100644 --- a/apps/web/src/components/Dialog/LockdownDialog/LockdownDialog.test.tsx +++ b/apps/web/src/components/Dialog/LockdownDialog/LockdownDialog.test.tsx @@ -35,6 +35,9 @@ const fakeClient = () => ({ vi.mock("@meshtastic/sdk-react", () => ({ useActiveClient: () => fakeClient(), +})); + +vi.mock("@core/kmp/hooks", () => ({ useSignal: (sig: { value: unknown }) => sig.value, })); diff --git a/apps/web/src/components/PageComponents/Channels/Channels.tsx b/apps/web/src/components/PageComponents/Channels/Channels.tsx index 57d35d684..5ed8bec05 100644 --- a/apps/web/src/components/PageComponents/Channels/Channels.tsx +++ b/apps/web/src/components/PageComponents/Channels/Channels.tsx @@ -4,7 +4,8 @@ import { useDeviceCapabilities } from "@core/hooks/useDeviceCapabilities.ts"; import { useDevice } from "@core/stores"; import { firmwareAtLeast } from "@meshtastic/sdk"; import type { Protobuf } from "@core/protobuf.ts"; -import { useChannels, useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useChannels } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import i18next from "i18next"; import { PlusIcon, QrCodeIcon, UploadIcon } from "lucide-react"; import { useEffect, useMemo, useState } from "react"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/AmbientLighting.tsx b/apps/web/src/components/PageComponents/ModuleConfig/AmbientLighting.tsx index ac3de1008..249ba52b4 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/AmbientLighting.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/AmbientLighting.tsx @@ -9,7 +9,7 @@ import { } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useState } from "react"; import { useTranslation } from "react-i18next"; import { AmbientLightingColor } from "./AmbientLightingColor.tsx"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/Audio.tsx b/apps/web/src/components/PageComponents/ModuleConfig/Audio.tsx index 0d78387df..78ab4e95d 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/Audio.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/Audio.tsx @@ -9,7 +9,7 @@ import { } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useTranslation } from "react-i18next"; interface AudioModuleConfigProps { diff --git a/apps/web/src/components/PageComponents/ModuleConfig/CannedMessage.tsx b/apps/web/src/components/PageComponents/ModuleConfig/CannedMessage.tsx index 8d6f2aceb..0d7a5b669 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/CannedMessage.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/CannedMessage.tsx @@ -11,11 +11,7 @@ import { useDeviceCapabilities } from "@core/hooks/useDeviceCapabilities.ts"; import { useDevice } from "@core/stores"; import { firmwareAtLeast } from "@meshtastic/sdk"; import { Protobuf } from "@core/protobuf.ts"; -import { - useCannedMessages, - useConfigEditor, - useSignal, -} from "@meshtastic/sdk-react"; +import { useCannedMessages, useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useMemo } from "react"; import { useTranslation } from "react-i18next"; import { useStagedAdminString } from "./useStagedAdminString.ts"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/DetectionSensor.tsx b/apps/web/src/components/PageComponents/ModuleConfig/DetectionSensor.tsx index 8d7502142..65e9c5d88 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/DetectionSensor.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/DetectionSensor.tsx @@ -9,7 +9,7 @@ import { } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useTranslation } from "react-i18next"; interface DetectionSensorModuleConfigProps { diff --git a/apps/web/src/components/PageComponents/ModuleConfig/ExternalNotification.tsx b/apps/web/src/components/PageComponents/ModuleConfig/ExternalNotification.tsx index 129d972ca..dee87b867 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/ExternalNotification.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/ExternalNotification.tsx @@ -9,7 +9,7 @@ import { } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useRingtone, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useRingtone, useSignal } from "@core/kmp/hooks"; import { useMemo } from "react"; import { useTranslation } from "react-i18next"; import { useStagedAdminString } from "./useStagedAdminString.ts"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/MQTT.tsx b/apps/web/src/components/PageComponents/ModuleConfig/MQTT.tsx index fc0dc875c..7476d3ea2 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/MQTT.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/MQTT.tsx @@ -11,7 +11,7 @@ import { import { useDeviceCapabilities } from "@core/hooks/useDeviceCapabilities.ts"; import { useDevice } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useTranslation } from "react-i18next"; interface MqttModuleConfigProps { diff --git a/apps/web/src/components/PageComponents/ModuleConfig/MeshBeacon.tsx b/apps/web/src/components/PageComponents/ModuleConfig/MeshBeacon.tsx index 6955530c5..bfe06c507 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/MeshBeacon.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/MeshBeacon.tsx @@ -18,7 +18,8 @@ import { useDevice } from "@core/stores"; import { channelSettingsByIndex } from "@core/utils/beaconJoin.ts"; import { getRegionPresetGroup } from "@core/utils/loraPresets.ts"; import { Protobuf } from "@core/protobuf.ts"; -import { useChannels, useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useChannels } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useMemo } from "react"; import { useTranslation } from "react-i18next"; import { MeshBeaconTargets } from "./MeshBeaconTargets.tsx"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/NeighborInfo.tsx b/apps/web/src/components/PageComponents/ModuleConfig/NeighborInfo.tsx index b14b9336d..118796e96 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/NeighborInfo.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/NeighborInfo.tsx @@ -9,7 +9,7 @@ import { } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useTranslation } from "react-i18next"; interface NeighborInfoModuleConfigProps { diff --git a/apps/web/src/components/PageComponents/ModuleConfig/Paxcounter.tsx b/apps/web/src/components/PageComponents/ModuleConfig/Paxcounter.tsx index a7538e50c..0b37a2af3 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/Paxcounter.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/Paxcounter.tsx @@ -9,7 +9,7 @@ import { } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useTranslation } from "react-i18next"; interface PaxcounterModuleConfigProps { diff --git a/apps/web/src/components/PageComponents/ModuleConfig/RangeTest.tsx b/apps/web/src/components/PageComponents/ModuleConfig/RangeTest.tsx index 74b39b107..25454771c 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/RangeTest.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/RangeTest.tsx @@ -9,7 +9,8 @@ import { } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; -import { useChannel, useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useChannel } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useTranslation } from "react-i18next"; interface RangeTestModuleConfigProps { diff --git a/apps/web/src/components/PageComponents/ModuleConfig/RemoteHardware.tsx b/apps/web/src/components/PageComponents/ModuleConfig/RemoteHardware.tsx index aa0eb2c02..4d941871f 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/RemoteHardware.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/RemoteHardware.tsx @@ -10,7 +10,7 @@ import { } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useTranslation } from "react-i18next"; import { RemoteHardwarePins } from "./RemoteHardwarePins.tsx"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/Serial.tsx b/apps/web/src/components/PageComponents/ModuleConfig/Serial.tsx index 2ab70a07f..1f737e747 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/Serial.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/Serial.tsx @@ -9,7 +9,7 @@ import { } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useTranslation } from "react-i18next"; interface SerialModuleConfigProps { diff --git a/apps/web/src/components/PageComponents/ModuleConfig/StoreForward.tsx b/apps/web/src/components/PageComponents/ModuleConfig/StoreForward.tsx index 929c3407c..a9b992046 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/StoreForward.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/StoreForward.tsx @@ -9,7 +9,7 @@ import { } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useTranslation } from "react-i18next"; interface StoreForwardModuleConfigProps { diff --git a/apps/web/src/components/PageComponents/ModuleConfig/Tak.tsx b/apps/web/src/components/PageComponents/ModuleConfig/Tak.tsx index 4666a3079..a9580916c 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/Tak.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/Tak.tsx @@ -9,7 +9,7 @@ import { } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useTranslation } from "react-i18next"; import { TakTeamSwatches } from "./TakTeamSwatches.tsx"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/Telemetry.tsx b/apps/web/src/components/PageComponents/ModuleConfig/Telemetry.tsx index 005907425..06fef8394 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/Telemetry.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/Telemetry.tsx @@ -9,7 +9,7 @@ import { } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useTranslation } from "react-i18next"; interface TelemetryModuleConfigProps { diff --git a/apps/web/src/components/PageComponents/ModuleConfig/useStagedAdminString.ts b/apps/web/src/components/PageComponents/ModuleConfig/useStagedAdminString.ts index 013254715..9f508264d 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/useStagedAdminString.ts +++ b/apps/web/src/components/PageComponents/ModuleConfig/useStagedAdminString.ts @@ -1,6 +1,6 @@ import { create } from "@bufbuild/protobuf"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useCallback } from "react"; /** diff --git a/apps/web/src/components/PageComponents/Settings/Bluetooth.tsx b/apps/web/src/components/PageComponents/Settings/Bluetooth.tsx index e2e0f043a..c04a83d2b 100644 --- a/apps/web/src/components/PageComponents/Settings/Bluetooth.tsx +++ b/apps/web/src/components/PageComponents/Settings/Bluetooth.tsx @@ -9,7 +9,7 @@ import { } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useTranslation } from "react-i18next"; interface BluetoothConfigProps { diff --git a/apps/web/src/components/PageComponents/Settings/Device/index.tsx b/apps/web/src/components/PageComponents/Settings/Device/index.tsx index 898ce4dd4..24ebf563c 100644 --- a/apps/web/src/components/PageComponents/Settings/Device/index.tsx +++ b/apps/web/src/components/PageComponents/Settings/Device/index.tsx @@ -12,7 +12,7 @@ import { } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useTranslation } from "react-i18next"; interface DeviceConfigProps { diff --git a/apps/web/src/components/PageComponents/Settings/Display.tsx b/apps/web/src/components/PageComponents/Settings/Display.tsx index 0c9e11904..b6e56629f 100644 --- a/apps/web/src/components/PageComponents/Settings/Display.tsx +++ b/apps/web/src/components/PageComponents/Settings/Display.tsx @@ -9,7 +9,7 @@ import { } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useTranslation } from "react-i18next"; interface DisplayConfigProps { diff --git a/apps/web/src/components/PageComponents/Settings/LoRa.test.tsx b/apps/web/src/components/PageComponents/Settings/LoRa.test.tsx index f2bc7ec34..ecc958a1e 100644 --- a/apps/web/src/components/PageComponents/Settings/LoRa.test.tsx +++ b/apps/web/src/components/PageComponents/Settings/LoRa.test.tsx @@ -36,7 +36,7 @@ vi.mock("@core/hooks/useNodesAsProto.ts", () => ({ hwModel === undefined ? undefined : { user: { hwModel } }, })); -vi.mock("@meshtastic/sdk-react", () => ({ +vi.mock("@core/kmp/hooks", () => ({ useConfigEditor: () => ({ radio: { value: {} }, setRadioSection: vi.fn(), diff --git a/apps/web/src/components/PageComponents/Settings/LoRa.tsx b/apps/web/src/components/PageComponents/Settings/LoRa.tsx index 9363cf062..f170ba46f 100644 --- a/apps/web/src/components/PageComponents/Settings/LoRa.tsx +++ b/apps/web/src/components/PageComponents/Settings/LoRa.tsx @@ -26,7 +26,7 @@ import { } from "@core/utils/loraPresets.ts"; import { firmwareAtLeast } from "@meshtastic/sdk"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useEffect, useMemo, useState } from "react"; import { useForm, useWatch } from "react-hook-form"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/Settings/Network/Network.test.tsx b/apps/web/src/components/PageComponents/Settings/Network/Network.test.tsx index dc748370c..4d941ba66 100644 --- a/apps/web/src/components/PageComponents/Settings/Network/Network.test.tsx +++ b/apps/web/src/components/PageComponents/Settings/Network/Network.test.tsx @@ -25,7 +25,7 @@ vi.mock("@core/hooks/useDeviceCapabilities.ts", () => ({ useDeviceCapabilities: () => ({ metadata }), })); -vi.mock("@meshtastic/sdk-react", () => ({ +vi.mock("@core/kmp/hooks", () => ({ useConfigEditor: () => ({ radio: { value: {} }, setRadioSection }), useSignal: (signal: { value: unknown }) => signal.value, })); diff --git a/apps/web/src/components/PageComponents/Settings/Network/index.tsx b/apps/web/src/components/PageComponents/Settings/Network/index.tsx index 3427de7f3..c95a7cb9a 100644 --- a/apps/web/src/components/PageComponents/Settings/Network/index.tsx +++ b/apps/web/src/components/PageComponents/Settings/Network/index.tsx @@ -17,7 +17,7 @@ import { convertIpAddressToInt, } from "@core/utils/ip.ts"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useTranslation } from "react-i18next"; interface NetworkConfigProps { diff --git a/apps/web/src/components/PageComponents/Settings/Position.test.tsx b/apps/web/src/components/PageComponents/Settings/Position.test.tsx index cce473fd9..79c72daf1 100644 --- a/apps/web/src/components/PageComponents/Settings/Position.test.tsx +++ b/apps/web/src/components/PageComponents/Settings/Position.test.tsx @@ -31,7 +31,7 @@ vi.mock("@core/stores", () => ({ }), })); -vi.mock("@meshtastic/sdk-react", () => ({ +vi.mock("@core/kmp/hooks", () => ({ useConfigEditor: () => ({ radio: { value: {} }, stagedAdminMessages: { value: staged }, diff --git a/apps/web/src/components/PageComponents/Settings/Position.tsx b/apps/web/src/components/PageComponents/Settings/Position.tsx index 724083b40..7dd7fb8a2 100644 --- a/apps/web/src/components/PageComponents/Settings/Position.tsx +++ b/apps/web/src/components/PageComponents/Settings/Position.tsx @@ -18,7 +18,7 @@ import { useToast } from "@core/hooks/useToast.ts"; import { useDevice } from "@core/stores"; import { STAGED_FIXED_POSITION } from "@core/utils/stagedAdminKeys.ts"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { LocateFixed } from "lucide-react"; import { useCallback, useMemo, useState } from "react"; import { useFormContext } from "react-hook-form"; diff --git a/apps/web/src/components/PageComponents/Settings/Power.test.tsx b/apps/web/src/components/PageComponents/Settings/Power.test.tsx index f1cb7627c..ff17d398f 100644 --- a/apps/web/src/components/PageComponents/Settings/Power.test.tsx +++ b/apps/web/src/components/PageComponents/Settings/Power.test.tsx @@ -17,7 +17,7 @@ vi.mock("@core/stores", () => ({ }), })); -vi.mock("@meshtastic/sdk-react", () => ({ +vi.mock("@core/kmp/hooks", () => ({ useConfigEditor: () => ({ radio: { value: {} }, setRadioSection: vi.fn(), diff --git a/apps/web/src/components/PageComponents/Settings/Power.tsx b/apps/web/src/components/PageComponents/Settings/Power.tsx index 46bf90397..294d13497 100644 --- a/apps/web/src/components/PageComponents/Settings/Power.tsx +++ b/apps/web/src/components/PageComponents/Settings/Power.tsx @@ -13,7 +13,7 @@ import { import type { FieldProps } from "@components/Form/DynamicFormField.tsx"; import { useDevice } from "@core/stores"; import type { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useEffect } from "react"; import { useForm, useWatch } from "react-hook-form"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/Settings/Security/Security.test.tsx b/apps/web/src/components/PageComponents/Settings/Security/Security.test.tsx index 1ba7a15d5..41a0d722f 100644 --- a/apps/web/src/components/PageComponents/Settings/Security/Security.test.tsx +++ b/apps/web/src/components/PageComponents/Settings/Security/Security.test.tsx @@ -30,7 +30,7 @@ vi.mock("@core/hooks/useLockdown.ts", () => ({ useLockdown: () => ({ client: undefined, status: undefined }), })); -vi.mock("@meshtastic/sdk-react", () => ({ +vi.mock("@core/kmp/hooks", () => ({ useConfigEditor: () => ({ radio: { value: {} }, setRadioSection: vi.fn(), diff --git a/apps/web/src/components/PageComponents/Settings/Security/Security.tsx b/apps/web/src/components/PageComponents/Settings/Security/Security.tsx index 2d9676ee3..6917d6ee9 100644 --- a/apps/web/src/components/PageComponents/Settings/Security/Security.tsx +++ b/apps/web/src/components/PageComponents/Settings/Security/Security.tsx @@ -15,7 +15,7 @@ import { useDeviceCapabilities } from "@core/hooks/useDeviceCapabilities.ts"; import { useDevice } from "@core/stores"; import { getX25519PrivateKey, getX25519PublicKey } from "@core/utils/x25519.ts"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { fromByteArray, toByteArray } from "base64-js"; import { useEffect, useState } from "react"; import { type DefaultValues, useForm } from "react-hook-form"; diff --git a/apps/web/src/components/PageComponents/Settings/User.test.tsx b/apps/web/src/components/PageComponents/Settings/User.test.tsx index 769baea44..0b5dfec44 100644 --- a/apps/web/src/components/PageComponents/Settings/User.test.tsx +++ b/apps/web/src/components/PageComponents/Settings/User.test.tsx @@ -41,7 +41,7 @@ vi.mock("@core/hooks/useDeviceCapabilities.ts", () => ({ }), })); -vi.mock("@meshtastic/sdk-react", () => ({ +vi.mock("@core/kmp/hooks", () => ({ useConfigEditor: () => ({ owner: { value: undefined }, modules: { value: {} }, diff --git a/apps/web/src/components/PageComponents/Settings/User.tsx b/apps/web/src/components/PageComponents/Settings/User.tsx index 82f78a0db..c26776b33 100644 --- a/apps/web/src/components/PageComponents/Settings/User.tsx +++ b/apps/web/src/components/PageComponents/Settings/User.tsx @@ -14,7 +14,7 @@ import { useDevice } from "@core/stores"; import { isModuleExcluded } from "@core/utils/excludedModules.ts"; import { firmwareAtLeast } from "@meshtastic/sdk"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useEffect } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/core/hooks/useBeaconOffers.ts b/apps/web/src/core/hooks/useBeaconOffers.ts index cb4363acd..9c3e5a706 100644 --- a/apps/web/src/core/hooks/useBeaconOffers.ts +++ b/apps/web/src/core/hooks/useBeaconOffers.ts @@ -7,7 +7,8 @@ import { planBeaconJoin, } from "@core/utils/beaconJoin.ts"; import type { MeshBeaconOffer } from "@meshtastic/sdk"; -import { useActiveClient, useChannels, useSignal } from "@meshtastic/sdk-react"; +import { useActiveClient, useChannels } from "@meshtastic/sdk-react"; +import { useSignal } from "@core/kmp/hooks"; import { useCallback, useMemo } from "react"; export interface JoinableBeaconOffer { diff --git a/apps/web/src/core/hooks/useDeviceCapabilities.ts b/apps/web/src/core/hooks/useDeviceCapabilities.ts index 02dc52a52..08fffe009 100644 --- a/apps/web/src/core/hooks/useDeviceCapabilities.ts +++ b/apps/web/src/core/hooks/useDeviceCapabilities.ts @@ -1,7 +1,8 @@ import { useDevice } from "@core/stores"; import { firmwareAtLeast } from "@meshtastic/sdk"; import type { Protobuf } from "@core/protobuf.ts"; -import { useActiveClient, useSignal } from "@meshtastic/sdk-react"; +import { useActiveClient } from "@meshtastic/sdk-react"; +import { useSignal } from "@core/kmp/hooks"; const EMPTY_REGION_PRESETS_SIGNAL = { value: undefined as Protobuf.Mesh.LoRaRegionPresetMap | undefined, diff --git a/apps/web/src/core/hooks/useLockdown.ts b/apps/web/src/core/hooks/useLockdown.ts index eb5b77f37..646466e99 100644 --- a/apps/web/src/core/hooks/useLockdown.ts +++ b/apps/web/src/core/hooks/useLockdown.ts @@ -1,6 +1,7 @@ import type { MeshClient } from "@meshtastic/sdk"; import type { Protobuf } from "@core/protobuf.ts"; -import { useActiveClient, useSignal } from "@meshtastic/sdk-react"; +import { useActiveClient } from "@meshtastic/sdk-react"; +import { useSignal } from "@core/kmp/hooks"; type LockdownStatus = Protobuf.Mesh.LockdownStatus | undefined; diff --git a/apps/web/src/core/hooks/useNodeTelemetryHistory.ts b/apps/web/src/core/hooks/useNodeTelemetryHistory.ts index 5a95b0580..2b16f8bef 100644 --- a/apps/web/src/core/hooks/useNodeTelemetryHistory.ts +++ b/apps/web/src/core/hooks/useNodeTelemetryHistory.ts @@ -1,5 +1,6 @@ import type { ReadonlySignal, TelemetryReading } from "@meshtastic/sdk"; -import { useActiveClient, useSignal } from "@meshtastic/sdk-react"; +import { useActiveClient } from "@meshtastic/sdk-react"; +import { useSignal } from "@core/kmp/hooks"; import { useMemo } from "react"; const EMPTY_HISTORY: TelemetryReading[] = []; diff --git a/apps/web/src/core/hooks/useNodesAsProto.ts b/apps/web/src/core/hooks/useNodesAsProto.ts index 9f3a4b60a..0c87b4fc1 100644 --- a/apps/web/src/core/hooks/useNodesAsProto.ts +++ b/apps/web/src/core/hooks/useNodesAsProto.ts @@ -1,7 +1,8 @@ import { create } from "@bufbuild/protobuf"; import type { Node as SdkNode } from "@meshtastic/sdk"; import { Protobuf } from "@core/protobuf.ts"; -import { useActiveClient, useSignal } from "@meshtastic/sdk-react"; +import { useActiveClient } from "@meshtastic/sdk-react"; +import { useSignal } from "@core/kmp/hooks"; import { useMemo } from "react"; /** diff --git a/apps/web/src/core/kmp/configEditor.test.ts b/apps/web/src/core/kmp/configEditor.test.ts new file mode 100644 index 000000000..6afdc5424 --- /dev/null +++ b/apps/web/src/core/kmp/configEditor.test.ts @@ -0,0 +1,488 @@ +import { Protobuf } from "@core/protobuf.ts"; +import { create } from "@bufbuild/protobuf"; +import { Result } from "better-result"; +import { describe, expect, it } from "vitest"; +import { ConfigEditor, type ConfigEditorIo } from "./configEditor.ts"; + +type AdminCase = Protobuf.Admin.AdminMessage["payloadVariant"]["case"]; + +/** + * A device the editor can talk to: tests push config and watch what each + * commit sends. `hold()` keeps the next commit in flight until released, + * `failNext()` makes it fail. + */ +class FakeIo implements ConfigEditorIo { + readonly commits: Protobuf.Admin.AdminMessage[][] = []; + private configs = new Set<(c: Protobuf.Config.Config) => void>(); + private modules = new Set<(c: Protobuf.ModuleConfig.ModuleConfig) => void>(); + private channels = new Set<(c: Protobuf.Channel.Channel) => void>(); + private disconnects = new Set<() => void>(); + private held: { reached: () => void; released: Promise } | undefined; + private failures = 0; + + onConfig(cb: (c: Protobuf.Config.Config) => void): () => void { + this.configs.add(cb); + return () => this.configs.delete(cb); + } + onModuleConfig(cb: (c: Protobuf.ModuleConfig.ModuleConfig) => void) { + this.modules.add(cb); + return () => this.modules.delete(cb); + } + onChannel(cb: (c: Protobuf.Channel.Channel) => void): () => void { + this.channels.add(cb); + return () => this.channels.delete(cb); + } + onDisconnect(cb: () => void): () => void { + this.disconnects.add(cb); + return () => this.disconnects.delete(cb); + } + async commit( + messages: readonly Protobuf.Admin.AdminMessage[], + ): Promise> { + this.commits.push([...messages]); + const held = this.held; + if (held) { + this.held = undefined; + held.reached(); + await held.released; + } + if (this.failures > 0) { + this.failures--; + return Result.err(new Error("send failed")); + } + return Result.ok(undefined); + } + + config(c: Protobuf.Config.Config): void { + for (const cb of this.configs) cb(c); + } + moduleConfig(c: Protobuf.ModuleConfig.ModuleConfig): void { + for (const cb of this.modules) cb(c); + } + channel(c: Protobuf.Channel.Channel): void { + for (const cb of this.channels) cb(c); + } + disconnect(): void { + for (const cb of this.disconnects) cb(); + } + hold(): { reached: Promise; release: () => void } { + let reached = () => {}; + let release = () => {}; + const reachedPromise = new Promise((resolve) => { + reached = resolve; + }); + const released = new Promise((resolve) => { + release = resolve; + }); + this.held = { reached, released }; + return { reached: reachedPromise, release }; + } + failNext(): void { + this.failures++; + } + cases(): AdminCase[] { + return this.commits.flat().map((m) => m.payloadVariant.case); + } + sentConfig( + section: Protobuf.Config.Config["payloadVariant"]["case"], + ): Protobuf.Config.Config["payloadVariant"] | undefined { + for (const m of this.commits.flat()) { + if (m.payloadVariant.case !== "setConfig") continue; + const variant = m.payloadVariant.value.payloadVariant; + if (variant.case === section) return variant; + } + return undefined; + } + sentModuleConfig( + section: Protobuf.ModuleConfig.ModuleConfig["payloadVariant"]["case"], + ): Protobuf.ModuleConfig.ModuleConfig["payloadVariant"] | undefined { + for (const m of this.commits.flat()) { + if (m.payloadVariant.case !== "setModuleConfig") continue; + const variant = m.payloadVariant.value.payloadVariant; + if (variant.case === section) return variant; + } + return undefined; + } +} + +function loraPacket(region: number): Protobuf.Config.Config { + return create(Protobuf.Config.ConfigSchema, { + payloadVariant: { + case: "lora", + value: create(Protobuf.Config.Config_LoRaConfigSchema, { region }), + }, + }); +} + +function mqttPacket(enabled: boolean): Protobuf.ModuleConfig.ModuleConfig { + return create(Protobuf.ModuleConfig.ModuleConfigSchema, { + payloadVariant: { + case: "mqtt", + value: create(Protobuf.ModuleConfig.ModuleConfig_MQTTConfigSchema, { + enabled, + }), + }, + }); +} + +function channelPacket(index: number, name: string): Protobuf.Channel.Channel { + return create(Protobuf.Channel.ChannelSchema, { + index, + role: Protobuf.Channel.Channel_Role.SECONDARY, + settings: create(Protobuf.Channel.ChannelSettingsSchema, { name }), + }); +} + +const lora = (region: number) => + create(Protobuf.Config.Config_LoRaConfigSchema, { region }); + +const enableMqtt = () => + create(Protobuf.ModuleConfig.ModuleConfig_MQTTConfigSchema, { + enabled: true, + }); + +const user = (longName: string) => + create(Protobuf.Mesh.UserSchema, { id: "!00000001", longName }); + +function setup() { + const io = new FakeIo(); + const editor = new ConfigEditor(io); + return { io, editor }; +} + +describe("ConfigEditor", () => { + it("starts clean and tracks dirty when working diverges from baseline", () => { + const { io, editor } = setup(); + expect(editor.isDirty.value).toBe(false); + + io.config(loraPacket(4)); + expect(editor.isDirty.value).toBe(false); + expect(editor.radio.value.lora?.region).toBe(4); + + editor.setRadioSection("lora", lora(7)); + expect(editor.isDirty.value).toBe(true); + expect(editor.dirtyRadioSections.value).toEqual(["lora"]); + }); + + it("tracks module and channel dirtiness independently", () => { + const { io, editor } = setup(); + io.moduleConfig(mqttPacket(false)); + io.channel(channelPacket(1, "primary")); + + editor.setModuleSection("mqtt", enableMqtt()); + expect(editor.dirtyModuleSections.value).toEqual(["mqtt"]); + + editor.setChannel(channelPacket(1, "renamed")); + expect(editor.dirtyChannels.value).toEqual([1]); + expect(editor.isDirty.value).toBe(true); + }); + + it("reset() restores working = baseline and clears dirty flags", () => { + const { io, editor } = setup(); + io.config(loraPacket(4)); + editor.setRadioSection("lora", lora(7)); + expect(editor.isDirty.value).toBe(true); + + editor.reset(); + expect(editor.isDirty.value).toBe(false); + expect(editor.radio.value.lora?.region).toBe(4); + }); + + it("reset() drops queued admin messages", () => { + const { editor } = setup(); + editor.queueAdminMessage( + create(Protobuf.Admin.AdminMessageSchema, { + payloadVariant: { + case: "setFixedPosition", + value: create(Protobuf.Mesh.PositionSchema, { latitudeI: 1 }), + }, + }), + ); + expect(editor.isDirty.value).toBe(true); + + editor.reset(); + expect(editor.isDirty.value).toBe(false); + }); + + it("inbound baseline updates do not stomp pending working edits", () => { + const { io, editor } = setup(); + io.config(loraPacket(4)); + editor.setRadioSection("lora", lora(7)); + + io.config(loraPacket(8)); + + expect(editor.radio.value.lora?.region).toBe(7); + expect(editor.dirtyRadioSections.value).toEqual(["lora"]); + }); + + it("keeps radio fields a partial update leaves out", () => { + const { io, editor } = setup(); + io.config( + create(Protobuf.Config.ConfigSchema, { + payloadVariant: { + case: "lora", + value: create(Protobuf.Config.Config_LoRaConfigSchema, { + region: 4, + paFanDisabled: true, + ignoreIncoming: [1234], + }), + }, + }), + ); + + editor.setRadioSection("lora", { region: 7 }); + + const sent = editor.radio.value.lora; + expect(sent?.region).toBe(7); + expect(sent?.paFanDisabled).toBe(true); + expect(sent?.ignoreIncoming).toEqual([1234]); + expect(editor.dirtyRadioSections.value).toEqual(["lora"]); + }); + + it("keeps module fields a partial update leaves out", () => { + const { io, editor } = setup(); + io.moduleConfig( + create(Protobuf.ModuleConfig.ModuleConfigSchema, { + payloadVariant: { + case: "rangeTest", + value: create( + Protobuf.ModuleConfig.ModuleConfig_RangeTestConfigSchema, + { enabled: false, clearOnReboot: true }, + ), + }, + }), + ); + + editor.setModuleSection("rangeTest", { enabled: true }); + + expect(editor.modules.value.rangeTest?.enabled).toBe(true); + expect(editor.modules.value.rangeTest?.clearOnReboot).toBe(true); + }); + + it("a partial update equal to the baseline is not dirty", () => { + const { io, editor } = setup(); + io.config(loraPacket(4)); + editor.setRadioSection("lora", { region: 4 }); + expect(editor.isDirty.value).toBe(false); + }); + + it("an undefined section reverts to the baseline", async () => { + const { io, editor } = setup(); + io.config(loraPacket(4)); + io.moduleConfig(mqttPacket(false)); + editor.setRadioSection("lora", lora(7)); + editor.setRadioSection("lora", undefined); + editor.setModuleSection("mqtt", undefined); + editor.setRadioSection("position", undefined); + + expect(editor.radio.value.lora?.region).toBe(4); + expect(editor.isDirty.value).toBe(false); + expect((await editor.commit()).status).toBe("ok"); + expect(io.commits).toEqual([]); + }); + + it("disconnect drops baseline and working", () => { + const { io, editor } = setup(); + io.config(loraPacket(4)); + editor.setRadioSection("lora", lora(7)); + expect(editor.isDirty.value).toBe(true); + + io.disconnect(); + + expect(editor.radio.value).toEqual({}); + expect(editor.isDirty.value).toBe(false); + }); + + it("builds a full section from a partial edit when the device sent none", () => { + const { editor } = setup(); + editor.setRadioSection("lora", { region: 7 }); + expect(editor.radio.value.lora?.region).toBe(7); + expect(editor.radio.value.lora?.hopLimit).toBe(0); + expect(editor.dirtyRadioSections.value).toEqual(["lora"]); + }); + + it("dispose() stops listening to the device", () => { + const { io, editor } = setup(); + editor.dispose(); + io.config(loraPacket(4)); + expect(editor.radio.value).toEqual({}); + }); +}); + +/** A connected editor with lora edited from region 1 to 4. */ +function setupCommit() { + const { io, editor } = setup(); + io.config(loraPacket(1)); + io.moduleConfig(mqttPacket(false)); + io.channel(channelPacket(1, "primary")); + editor.setRadioSection("lora", lora(4)); + return { io, editor }; +} + +describe("ConfigEditor.commit", () => { + it("sends dirty sections, channels, owner and staged messages together", async () => { + const { io, editor } = setupCommit(); + editor.setModuleSection("mqtt", enableMqtt()); + editor.setChannel(channelPacket(1, "renamed")); + editor.setBaselineOwner(user("Before")); + editor.setOwner(user("After")); + editor.stageAdminMessage( + "ringtone", + create(Protobuf.Admin.AdminMessageSchema, { + payloadVariant: { case: "setRingtoneMessage", value: "a:d=4" }, + }), + ); + + expect((await editor.commit()).status).toBe("ok"); + + expect(io.cases()).toEqual([ + "setConfig", + "setModuleConfig", + "setChannel", + "setOwner", + "setRingtoneMessage", + ]); + expect(io.sentConfig("lora")?.value).toMatchObject({ region: 4 }); + expect(io.sentModuleConfig("mqtt")?.value).toMatchObject({ + enabled: true, + }); + expect(editor.isDirty.value).toBe(false); + expect(editor.owner.value?.longName).toBe("After"); + }); + + it("reports committed staged messages", async () => { + const io = new FakeIo(); + const committed: Protobuf.Admin.AdminMessage[] = []; + const editor = new ConfigEditor(io, { + onStagedAdminMessageCommitted: (m) => committed.push(m), + }); + const message = create(Protobuf.Admin.AdminMessageSchema, { + payloadVariant: { case: "setCannedMessageModuleMessages", value: "a|b" }, + }); + editor.stageAdminMessage("cannedMessages", message); + + expect((await editor.commit()).status).toBe("ok"); + expect(committed).toEqual([message]); + expect(editor.stagedAdminMessages.value.size).toBe(0); + }); + + it("keeps an edit made while a commit is in flight dirty", async () => { + const { io, editor } = setupCommit(); + const held = io.hold(); + + const pending = editor.commit(); + await held.reached; + editor.setModuleSection("mqtt", enableMqtt()); + held.release(); + expect((await pending).status).toBe("ok"); + + expect(editor.dirtyRadioSections.value).toEqual([]); + expect(editor.dirtyModuleSections.value).toEqual(["mqtt"]); + expect(io.sentModuleConfig("mqtt")).toBeUndefined(); + + expect((await editor.commit()).status).toBe("ok"); + expect(io.sentModuleConfig("mqtt")?.value).toMatchObject({ enabled: true }); + expect(editor.isDirty.value).toBe(false); + }); + + it("keeps device packets for unsent sections that arrive during a commit", async () => { + const { io, editor } = setupCommit(); + const held = io.hold(); + + const pending = editor.commit(); + await held.reached; + io.moduleConfig(mqttPacket(true)); + io.channel(channelPacket(1, "renamed")); + held.release(); + expect((await pending).status).toBe("ok"); + + expect(editor.isDirty.value).toBe(false); + expect(editor.modules.value.mqtt?.enabled).toBe(true); + expect(editor.channels.value.get(1)?.settings?.name).toBe("renamed"); + }); + + it("keeps an owner update that arrives during a commit", async () => { + const { io, editor } = setupCommit(); + editor.setBaselineOwner(user("Before")); + const held = io.hold(); + + const pending = editor.commit(); + await held.reached; + editor.setBaselineOwner(user("After")); + held.release(); + expect((await pending).status).toBe("ok"); + + expect(editor.isOwnerDirty.value).toBe(false); + expect(editor.owner.value?.longName).toBe("After"); + expect(io.cases()).not.toContain("setOwner"); + }); + + it("leaves the editor empty when the device disconnects during a commit", async () => { + const { io, editor } = setupCommit(); + const held = io.hold(); + + const pending = editor.commit(); + await held.reached; + io.disconnect(); + held.release(); + expect((await pending).status).toBe("error"); + + expect(editor.radio.value).toEqual({}); + expect(editor.isDirty.value).toBe(false); + io.config(loraPacket(1)); + expect(editor.isDirty.value).toBe(false); + }); + + it("sends a message queued again during a commit", async () => { + const { io, editor } = setupCommit(); + const message = create(Protobuf.Admin.AdminMessageSchema, { + payloadVariant: { case: "removeFixedPosition", value: true }, + }); + editor.queueAdminMessage(message); + const held = io.hold(); + + const pending = editor.commit(); + await held.reached; + editor.queueAdminMessage(message); + held.release(); + expect((await pending).status).toBe("ok"); + expect(editor.isDirty.value).toBe(true); + + expect((await editor.commit()).status).toBe("ok"); + expect(io.cases().filter((c) => c === "removeFixedPosition")).toHaveLength( + 2, + ); + expect(editor.isDirty.value).toBe(false); + }); + + it("runs a commit requested during another after it finishes", async () => { + const { io, editor } = setupCommit(); + const held = io.hold(); + + const first = editor.commit(); + await held.reached; + editor.setModuleSection("mqtt", enableMqtt()); + const second = editor.commit(); + held.release(); + + expect((await first).status).toBe("ok"); + expect((await second).status).toBe("ok"); + expect(io.commits.map((c) => c.map((m) => m.payloadVariant.case))).toEqual([ + ["setConfig"], + ["setModuleConfig"], + ]); + expect(editor.isDirty.value).toBe(false); + }); + + it("stays dirty when the commit fails", async () => { + const { io, editor } = setupCommit(); + editor.setModuleSection("mqtt", enableMqtt()); + io.failNext(); + + expect((await editor.commit()).status).toBe("error"); + + expect(io.cases()).toEqual(["setConfig", "setModuleConfig"]); + expect(editor.dirtyRadioSections.value).toEqual(["lora"]); + expect(editor.dirtyModuleSections.value).toEqual(["mqtt"]); + }); +}); diff --git a/apps/web/src/core/kmp/configEditor.ts b/apps/web/src/core/kmp/configEditor.ts new file mode 100644 index 000000000..eea43670d --- /dev/null +++ b/apps/web/src/core/kmp/configEditor.ts @@ -0,0 +1,636 @@ +import { Protobuf } from "@core/protobuf.ts"; +import { create } from "@bufbuild/protobuf"; +import { signal } from "@preact/signals-core"; +import { Result } from "better-result"; +import { type ReadonlySignal, toReadonly } from "./signals.ts"; + +export type RadioConfigSection = Exclude< + Protobuf.Config.Config["payloadVariant"]["case"], + undefined +>; + +export type RadioConfig = { + readonly [V in RadioConfigSection]?: Extract< + Protobuf.Config.Config["payloadVariant"], + { case: V } + >["value"]; +}; + +export type ModuleConfigSection = Exclude< + Protobuf.ModuleConfig.ModuleConfig["payloadVariant"]["case"], + undefined +>; + +export type ModuleConfig = { + readonly [V in ModuleConfigSection]?: Extract< + Protobuf.ModuleConfig.ModuleConfig["payloadVariant"], + { case: V } + >["value"]; +}; + +type Channels = ReadonlyMap; + +/** A section as a form hands it over: any subset of its fields. */ +export type SectionInit = { + [P in keyof T as P extends "$unknown" | "$typeName" ? never : P]?: T[P]; +}; +type AdminMessages = readonly Protobuf.Admin.AdminMessage[]; + +/** + * What the editor needs from a connected device: the config it reports, + * when it disconnects, and a way to send a settings transaction. + */ +export interface ConfigEditorIo { + onConfig(cb: (config: Protobuf.Config.Config) => void): () => void; + onModuleConfig( + cb: (config: Protobuf.ModuleConfig.ModuleConfig) => void, + ): () => void; + onChannel(cb: (channel: Protobuf.Channel.Channel) => void): () => void; + onDisconnect(cb: () => void): () => void; + /** Sends `messages` between `begin_edit_settings` and `commit_edit_settings`. */ + commit(messages: AdminMessages): Promise>; +} + +export interface ConfigEditorOptions { + /** Called for each staged admin message after a successful commit. */ + onStagedAdminMessageCommitted?: ( + message: Protobuf.Admin.AdminMessage, + ) => void; +} + +/** + * Per-section editor for radio config, module config, channels and owner. + * + * Tracks what the device most recently sent (the baseline) and the UI's + * edits (the working copy). Baseline updates never discard working edits; + * dirtiness is recomputed against the new baseline. A disconnect resets + * both so a stale working copy cannot leak into the next connection. + */ +export class ConfigEditor { + private readonly io: ConfigEditorIo; + private readonly baselineRadio = signal({}); + private readonly baselineModules = signal({}); + private readonly baselineChannels = signal(new Map()); + private readonly workingRadio = signal({}); + private readonly workingModules = signal({}); + private readonly workingChannels = signal(new Map()); + private readonly baselineOwner = signal( + undefined, + ); + private readonly workingOwner = signal( + undefined, + ); + private readonly queuedAdminMessages = signal([]); + private readonly _stagedAdminMessages = signal< + ReadonlyMap + >(new Map()); + private readonly _dirtyRadioSections = signal( + [], + ); + private readonly _dirtyModuleSections = signal< + readonly ModuleConfigSection[] + >([]); + private readonly _dirtyChannels = signal([]); + private readonly _isOwnerDirty = signal(false); + private readonly _isDirty = signal(false); + + readonly radio: ReadonlySignal = toReadonly(this.workingRadio); + readonly modules: ReadonlySignal = toReadonly( + this.workingModules, + ); + readonly channels: ReadonlySignal = toReadonly( + this.workingChannels, + ); + readonly dirtyRadioSections: ReadonlySignal = + toReadonly(this._dirtyRadioSections); + readonly dirtyModuleSections: ReadonlySignal = + toReadonly(this._dirtyModuleSections); + readonly dirtyChannels: ReadonlySignal = toReadonly( + this._dirtyChannels, + ); + readonly owner: ReadonlySignal = toReadonly( + this.workingOwner, + ); + readonly isOwnerDirty: ReadonlySignal = toReadonly( + this._isOwnerDirty, + ); + readonly isDirty: ReadonlySignal = toReadonly(this._isDirty); + /** + * Admin messages staged with {@link stageAdminMessage}, by key. Sent on + * the next commit; cleared by commit, reset and disconnect. + */ + readonly stagedAdminMessages: ReadonlySignal< + ReadonlyMap + > = toReadonly(this._stagedAdminMessages); + + private readonly onStagedAdminMessageCommitted?: ( + message: Protobuf.Admin.AdminMessage, + ) => void; + private readonly unsubscribe: Array<() => void>; + private commitQueue: Promise = Promise.resolve(); + /** Bumped on disconnect so an in-flight commit can tell. */ + private connectionGeneration = 0; + + constructor(io: ConfigEditorIo, options: ConfigEditorOptions = {}) { + this.io = io; + this.onStagedAdminMessageCommitted = options.onStagedAdminMessageCommitted; + this.unsubscribe = [ + io.onConfig((config) => this.applyConfig(config)), + io.onModuleConfig((config) => this.applyModuleConfig(config)), + io.onChannel((channel) => this.applyChannel(channel)), + io.onDisconnect(() => this.clear()), + ]; + } + + dispose(): void { + for (const off of this.unsubscribe) off(); + } + + private applyConfig(config: Protobuf.Config.Config): void { + const variant = config.payloadVariant; + if (!variant.case) return; + const next: RadioConfig = { + ...this.baselineRadio.peek(), + [variant.case]: variant.value, + }; + this.baselineRadio.value = next; + if (!this._dirtyRadioSections.peek().includes(variant.case)) { + this.workingRadio.value = { + ...this.workingRadio.peek(), + [variant.case]: variant.value, + }; + } + this.recomputeDirty(); + } + + private applyModuleConfig(config: Protobuf.ModuleConfig.ModuleConfig): void { + const variant = config.payloadVariant; + if (!variant.case) return; + const next: ModuleConfig = { + ...this.baselineModules.peek(), + [variant.case]: variant.value, + }; + this.baselineModules.value = next; + if (!this._dirtyModuleSections.peek().includes(variant.case)) { + this.workingModules.value = { + ...this.workingModules.peek(), + [variant.case]: variant.value, + }; + } + this.recomputeDirty(); + } + + private applyChannel(channel: Protobuf.Channel.Channel): void { + const baseline = new Map(this.baselineChannels.peek()); + baseline.set(channel.index, channel); + this.baselineChannels.value = baseline; + if (!this._dirtyChannels.peek().includes(channel.index)) { + const working = new Map(this.workingChannels.peek()); + working.set(channel.index, channel); + this.workingChannels.value = working; + } + this.recomputeDirty(); + } + + private clear(): void { + this.connectionGeneration++; + this.baselineRadio.value = {}; + this.baselineModules.value = {}; + this.baselineChannels.value = new Map(); + this.baselineOwner.value = undefined; + this.workingRadio.value = {}; + this.workingModules.value = {}; + this.workingChannels.value = new Map(); + this.workingOwner.value = undefined; + this.queuedAdminMessages.value = []; + this._stagedAdminMessages.value = new Map(); + this._dirtyRadioSections.value = []; + this._dirtyModuleSections.value = []; + this._dirtyChannels.value = []; + this._isOwnerDirty.value = false; + this._isDirty.value = false; + } + + /** The device's current user, as the node database reports it. */ + setBaselineOwner(owner: Protobuf.Mesh.User | undefined): void { + this.baselineOwner.value = owner; + if (!this._isOwnerDirty.peek()) { + this.workingOwner.value = owner; + } + this.recomputeDirty(); + } + + setOwner(owner: Protobuf.Mesh.User): void { + this.workingOwner.value = owner; + this.recomputeDirty(); + } + + /** Sends `message` inside the next commit; `reset` drops it. */ + queueAdminMessage(message: Protobuf.Admin.AdminMessage): void { + this.queuedAdminMessages.value = [ + ...this.queuedAdminMessages.peek(), + message, + ]; + this.recomputeDirty(); + } + + /** + * Stages `message` under `key`, replacing what was staged there, or + * removes it with `undefined`. For settings outside Config and + * ModuleConfig, such as the canned message list and the ringtone. + */ + stageAdminMessage( + key: string, + message: Protobuf.Admin.AdminMessage | undefined, + ): void { + const current = this._stagedAdminMessages.peek(); + if (message === undefined && !current.has(key)) return; + const next = new Map(current); + if (message === undefined) { + next.delete(key); + } else { + next.set(key, message); + } + this._stagedAdminMessages.value = next; + this.recomputeDirty(); + } + + /** + * Stages a radio config section. `value` is merged over the current + * working (or baseline) section, so fields a form doesn't render keep + * the device's value. `undefined` reverts the section to the baseline. + */ + setRadioSection( + key: K, + value: SectionInit> | undefined, + ): void { + const working = this.workingRadio.peek(); + const baseline = this.baselineRadio.peek()[key]; + const current = working[key] ?? baseline; + this.workingRadio.value = { + ...working, + [key]: + value === undefined + ? baseline + : current + ? { ...current, ...value } + : radioConfigOf[key](value).payloadVariant.value, + }; + this.recomputeDirty(); + } + + /** Stages a module config section, merged like {@link setRadioSection}. */ + setModuleSection( + key: K, + value: SectionInit> | undefined, + ): void { + const working = this.workingModules.peek(); + const baseline = this.baselineModules.peek()[key]; + const current = working[key] ?? baseline; + this.workingModules.value = { + ...working, + [key]: + value === undefined + ? baseline + : current + ? { ...current, ...value } + : moduleConfigOf[key](value).payloadVariant.value, + }; + this.recomputeDirty(); + } + + setChannel(channel: Protobuf.Channel.Channel): void { + const next = new Map(this.workingChannels.peek()); + next.set(channel.index, channel); + this.workingChannels.value = next; + this.recomputeDirty(); + } + + reset(): void { + this.workingRadio.value = this.baselineRadio.peek(); + this.workingModules.value = this.baselineModules.peek(); + this.workingChannels.value = new Map(this.baselineChannels.peek()); + this.workingOwner.value = this.baselineOwner.peek(); + this._stagedAdminMessages.value = new Map(); + this.queuedAdminMessages.value = []; + this.recomputeDirty(); + } + + /** + * Sends every dirty section in one settings transaction. Commits run one + * at a time; edits made during a commit stay dirty for the next one. + */ + commit(): Promise> { + const run = this.commitQueue.then(() => this.runCommit()); + this.commitQueue = run.catch(() => undefined); + return run; + } + + private async runCommit(): Promise> { + if (!this._isDirty.peek()) return Result.ok(undefined); + + const payload = this.collectPayload(); + if (payload.messages.length === 0) return Result.ok(undefined); + const generation = this.connectionGeneration; + + const result = await this.io.commit(payload.messages); + if (Result.isError(result)) return Result.err(result.error); + if (generation !== this.connectionGeneration) { + return Result.err( + new Error("The device disconnected before the commit finished"), + ); + } + + this.reconcileAfterCommit(payload); + for (const message of payload.staged.values()) { + this.onStagedAdminMessageCommitted?.(message); + } + return Result.ok(undefined); + } + + private collectPayload(): CommitPayload { + const radio = this.workingRadio.peek(); + const radioSections = this._dirtyRadioSections + .peek() + .filter((section) => radio[section] !== undefined); + const modules = this.workingModules.peek(); + const moduleSections = this._dirtyModuleSections + .peek() + .filter((section) => modules[section] !== undefined); + const channels = this.workingChannels.peek(); + const channelPayload: Protobuf.Channel.Channel[] = []; + for (const index of this._dirtyChannels.peek()) { + const channel = channels.get(index); + if (channel) channelPayload.push(channel); + } + const owner = this._isOwnerDirty.peek() + ? this.workingOwner.peek() + : undefined; + const queued = this.queuedAdminMessages.peek(); + const staged = this._stagedAdminMessages.peek(); + + const messages: Protobuf.Admin.AdminMessage[] = []; + for (const section of radioSections) { + messages.push( + admin({ case: "setConfig", value: radioConfig(radio, section) }), + ); + } + for (const section of moduleSections) { + messages.push( + admin({ + case: "setModuleConfig", + value: moduleConfig(modules, section), + }), + ); + } + for (const channel of channelPayload) { + messages.push(admin({ case: "setChannel", value: channel })); + } + if (owner) messages.push(admin({ case: "setOwner", value: owner })); + messages.push(...queued, ...staged.values()); + + return { + radio: { ...pick(radio, radioSections) }, + modules: { ...pick(modules, moduleSections) }, + channels: channelPayload, + owner, + queued, + staged, + messages, + }; + } + + /** + * Makes only what was sent the new baseline. Other sections keep theirs, + * including device packets that arrived during the commit. + */ + private reconcileAfterCommit(payload: CommitPayload): void { + if (Object.keys(payload.radio).length > 0) { + this.baselineRadio.value = { + ...this.baselineRadio.peek(), + ...payload.radio, + }; + } + if (Object.keys(payload.modules).length > 0) { + this.baselineModules.value = { + ...this.baselineModules.peek(), + ...payload.modules, + }; + } + if (payload.channels.length > 0) { + const baseline = new Map(this.baselineChannels.peek()); + for (const channel of payload.channels) { + baseline.set(channel.index, channel); + } + this.baselineChannels.value = baseline; + } + if (payload.owner) this.baselineOwner.value = payload.owner; + + // One entry per message sent: the same object may have been queued + // again during the commit, and that copy hasn't been sent. + if (payload.queued.length > 0) { + const remaining = [...this.queuedAdminMessages.peek()]; + for (const message of payload.queued) { + const index = remaining.indexOf(message); + if (index !== -1) remaining.splice(index, 1); + } + this.queuedAdminMessages.value = remaining; + } + if (payload.staged.size > 0) { + const unsent = new Map(this._stagedAdminMessages.peek()); + for (const [key, message] of payload.staged) { + if (unsent.get(key) === message) unsent.delete(key); + } + this._stagedAdminMessages.value = unsent; + } + + this.recomputeDirty(); + } + + private recomputeDirty(): void { + const radioBase = this.baselineRadio.peek(); + const radioWorking = this.workingRadio.peek(); + const radioDirty = sectionsOf(radioBase, radioWorking).filter( + (key) => !shallowEqual(radioBase[key], radioWorking[key]), + ); + + const moduleBase = this.baselineModules.peek(); + const moduleWorking = this.workingModules.peek(); + const moduleDirty = sectionsOf(moduleBase, moduleWorking).filter( + (key) => !shallowEqual(moduleBase[key], moduleWorking[key]), + ); + + const channelBase = this.baselineChannels.peek(); + const channelWorking = this.workingChannels.peek(); + const channelDirty = [ + ...new Set([...channelBase.keys(), ...channelWorking.keys()]), + ].filter( + (idx) => !shallowEqual(channelBase.get(idx), channelWorking.get(idx)), + ); + + const ownerDirty = !shallowEqual( + this.baselineOwner.peek(), + this.workingOwner.peek(), + ); + const hasQueuedAdmin = + this.queuedAdminMessages.peek().length > 0 || + this._stagedAdminMessages.peek().size > 0; + + this._dirtyRadioSections.value = radioDirty; + this._dirtyModuleSections.value = moduleDirty; + this._dirtyChannels.value = channelDirty; + this._isOwnerDirty.value = ownerDirty; + this._isDirty.value = + radioDirty.length > 0 || + moduleDirty.length > 0 || + channelDirty.length > 0 || + ownerDirty || + hasQueuedAdmin; + } +} + +interface CommitPayload { + radio: RadioConfig; + modules: ModuleConfig; + channels: Protobuf.Channel.Channel[]; + /** Set only when the owner was dirty. */ + owner: Protobuf.Mesh.User | undefined; + queued: AdminMessages; + staged: ReadonlyMap; + messages: Protobuf.Admin.AdminMessage[]; +} + +function admin( + payloadVariant: Protobuf.Admin.AdminMessage["payloadVariant"], +): Protobuf.Admin.AdminMessage { + return create(Protobuf.Admin.AdminMessageSchema, { payloadVariant }); +} + +function sectionsOf(a: T, b: T): (keyof T & string)[] { + const keys = new Set([...Object.keys(a), ...Object.keys(b)]); + return [...keys].filter( + (key): key is keyof T & string => key in a || key in b, + ); +} + +function pick( + source: T, + keys: readonly (keyof T)[], +): Partial { + const out: Partial = {}; + for (const key of keys) out[key] = source[key]; + return out; +} + +const radioConfigOf: { + [K in RadioConfigSection]: ( + value: SectionInit>, + ) => Protobuf.Config.Config; +} = { + bluetooth: (value) => config({ case: "bluetooth", value }), + device: (value) => config({ case: "device", value }), + deviceUi: (value) => config({ case: "deviceUi", value }), + display: (value) => config({ case: "display", value }), + lora: (value) => config({ case: "lora", value }), + network: (value) => config({ case: "network", value }), + position: (value) => config({ case: "position", value }), + power: (value) => config({ case: "power", value }), + security: (value) => config({ case: "security", value }), + sessionkey: (value) => config({ case: "sessionkey", value }), +}; + +const moduleConfigOf: { + [K in ModuleConfigSection]: ( + value: SectionInit>, + ) => Protobuf.ModuleConfig.ModuleConfig; +} = { + ambientLighting: (value) => + moduleConfigMessage({ case: "ambientLighting", value }), + audio: (value) => moduleConfigMessage({ case: "audio", value }), + cannedMessage: (value) => + moduleConfigMessage({ case: "cannedMessage", value }), + detectionSensor: (value) => + moduleConfigMessage({ case: "detectionSensor", value }), + externalNotification: (value) => + moduleConfigMessage({ case: "externalNotification", value }), + meshBeacon: (value) => moduleConfigMessage({ case: "meshBeacon", value }), + mqtt: (value) => moduleConfigMessage({ case: "mqtt", value }), + neighborInfo: (value) => moduleConfigMessage({ case: "neighborInfo", value }), + paxcounter: (value) => moduleConfigMessage({ case: "paxcounter", value }), + rangeTest: (value) => moduleConfigMessage({ case: "rangeTest", value }), + remoteHardware: (value) => + moduleConfigMessage({ case: "remoteHardware", value }), + serial: (value) => moduleConfigMessage({ case: "serial", value }), + statusmessage: (value) => + moduleConfigMessage({ case: "statusmessage", value }), + storeForward: (value) => moduleConfigMessage({ case: "storeForward", value }), + tak: (value) => moduleConfigMessage({ case: "tak", value }), + telemetry: (value) => moduleConfigMessage({ case: "telemetry", value }), + trafficManagement: (value) => + moduleConfigMessage({ case: "trafficManagement", value }), +}; + +type ConfigInit = NonNullable< + Parameters>[1] +>; + +type ModuleConfigInit = NonNullable< + Parameters>[1] +>; + +function config( + payloadVariant: ConfigInit["payloadVariant"], +): Protobuf.Config.Config { + return create(Protobuf.Config.ConfigSchema, { payloadVariant }); +} + +function moduleConfigMessage( + payloadVariant: ModuleConfigInit["payloadVariant"], +): Protobuf.ModuleConfig.ModuleConfig { + return create(Protobuf.ModuleConfig.ModuleConfigSchema, { payloadVariant }); +} + +export function radioConfig( + radio: RadioConfig, + section: K, +): Protobuf.Config.Config { + const value = radio[section]; + if (value === undefined) throw new Error(`No ${section} config to send`); + return radioConfigOf[section](value); +} + +export function moduleConfig( + modules: ModuleConfig, + section: K, +): Protobuf.ModuleConfig.ModuleConfig { + const value = modules[section]; + if (value === undefined) throw new Error(`No ${section} config to send`); + return moduleConfigOf[section](value); +} + +function shallowEqual(a: unknown, b: unknown): boolean { + if (a === b) return true; + if ( + a === undefined || + b === undefined || + a === null || + b === null || + typeof a !== "object" || + typeof b !== "object" + ) { + return false; + } + const aEntries = Object.entries(a); + const bEntries = new Map(Object.entries(b)); + if (aEntries.length !== bEntries.size) return false; + for (const [key, av] of aEntries) { + const bv = bEntries.get(key); + if (av === bv) continue; + if (typeof av === "object" && typeof bv === "object") { + if (!shallowEqual(av, bv)) return false; + } else { + return false; + } + } + return true; +} diff --git a/apps/web/src/core/kmp/configEditorIo.test.ts b/apps/web/src/core/kmp/configEditorIo.test.ts new file mode 100644 index 000000000..8af22835a --- /dev/null +++ b/apps/web/src/core/kmp/configEditorIo.test.ts @@ -0,0 +1,151 @@ +import { Protobuf } from "@core/protobuf.ts"; +import { create, toBinary } from "@bufbuild/protobuf"; +import { MeshClient } from "@meshtastic/sdk"; +import { + createFakeTransport, + interceptAdminMessages, +} from "@meshtastic/sdk/testing"; +import { describe, expect, it } from "vitest"; +import { facadeIo, meshClientIo } from "./configEditorIo.ts"; +import { FakeKmpClient } from "./fakeClient.ts"; + +const setOwner = (longName: string) => + create(Protobuf.Admin.AdminMessageSchema, { + payloadVariant: { + case: "setOwner", + value: create(Protobuf.Mesh.UserSchema, { longName }), + }, + }); + +const setLora = () => + create(Protobuf.Admin.AdminMessageSchema, { + payloadVariant: { + case: "setConfig", + value: create(Protobuf.Config.ConfigSchema, { + payloadVariant: { + case: "lora", + value: create(Protobuf.Config.Config_LoRaConfigSchema, { region: 4 }), + }, + }), + }, + }); + +describe("meshClientIo", () => { + function setup() { + const { transport } = createFakeTransport(); + const client = new MeshClient({ transport }); + const radio = interceptAdminMessages(client); + const pending: boolean[] = []; + client.events.onPendingSettingsChange.subscribe((p) => pending.push(p)); + return { client, radio, pending, io: meshClientIo(client) }; + } + + it("wraps the messages in a begin/commit transaction", async () => { + const { io, radio, pending } = setup(); + const result = await io.commit([setLora(), setOwner("Alice")]); + expect(result.status).toBe("ok"); + expect(radio.cases()).toEqual([ + "beginEditSettings", + "setConfig", + "setOwner", + "commitEditSettings", + ]); + expect(pending).toEqual([true, false]); + }); + + it("closes the transaction when a send fails", async () => { + const { io, radio } = setup(); + radio.failNext("setOwner"); + const result = await io.commit([setLora(), setOwner("Alice")]); + expect(result.status).toBe("error"); + expect(radio.cases()).toEqual([ + "beginEditSettings", + "setConfig", + "setOwner", + "commitEditSettings", + ]); + }); + + it("relays config, module config and channel packets", () => { + const { io, client } = setup(); + const seen: string[] = []; + io.onConfig((c) => seen.push(`config:${c.payloadVariant.case}`)); + io.onModuleConfig((c) => seen.push(`module:${c.payloadVariant.case}`)); + io.onChannel((c) => seen.push(`channel:${c.index}`)); + client.events.onConfigPacket.dispatch( + create(Protobuf.Config.ConfigSchema, { + payloadVariant: { case: "lora", value: {} }, + }), + ); + client.events.onModuleConfigPacket.dispatch( + create(Protobuf.ModuleConfig.ModuleConfigSchema, { + payloadVariant: { case: "mqtt", value: {} }, + }), + ); + client.events.onChannelPacket.dispatch( + create(Protobuf.Channel.ChannelSchema, { index: 2 }), + ); + expect(seen).toEqual(["config:lora", "module:mqtt", "channel:2"]); + }); +}); + +describe("facadeIo", () => { + it("relays the config bundle and channels as individual packets", () => { + const client = new FakeKmpClient(); + const io = facadeIo(client); + const seen: string[] = []; + io.onConfig((c) => seen.push(`config:${c.payloadVariant.case}`)); + io.onModuleConfig((c) => seen.push(`module:${c.payloadVariant.case}`)); + io.onChannel((c) => seen.push(`channel:${c.index}`)); + io.onDisconnect(() => seen.push("disconnect")); + + client.setConfigBundle({ + myInfo: new Uint8Array(), + metadata: new Uint8Array(), + configs: [ + toBinary( + Protobuf.Config.ConfigSchema, + create(Protobuf.Config.ConfigSchema, { + payloadVariant: { case: "device", value: {} }, + }), + ), + ], + moduleConfigs: [ + toBinary( + Protobuf.ModuleConfig.ModuleConfigSchema, + create(Protobuf.ModuleConfig.ModuleConfigSchema, { + payloadVariant: { case: "serial", value: {} }, + }), + ), + ], + }); + client.setChannels([ + toBinary( + Protobuf.Channel.ChannelSchema, + create(Protobuf.Channel.ChannelSchema, { index: 1 }), + ), + ]); + client.setState({ + kind: "disconnected", + attempt: 0, + maxAttempts: 10, + progress: 0, + }); + + expect(seen).toEqual([ + "disconnect", + "config:device", + "module:serial", + "channel:1", + "disconnect", + ]); + }); + + it("commits through the facade's settings transaction", async () => { + const client = new FakeKmpClient(); + const io = facadeIo(client); + const result = await io.commit([setLora()]); + expect(result.status).toBe("ok"); + expect(client.admin().transactions).toHaveLength(1); + }); +}); diff --git a/apps/web/src/core/kmp/configEditorIo.ts b/apps/web/src/core/kmp/configEditorIo.ts new file mode 100644 index 000000000..c78345a80 --- /dev/null +++ b/apps/web/src/core/kmp/configEditorIo.ts @@ -0,0 +1,170 @@ +import { Protobuf, Types } from "@core/protobuf.ts"; +import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; +import { DeviceStatusEnum, type MeshClient } from "@meshtastic/sdk"; +import type { MeshtasticClient } from "@meshtastic/sdk-kmp"; +import { Result } from "better-result"; +import { editSettings } from "./admin.ts"; +import { ConfigEditor, type ConfigEditorIo } from "./configEditor.ts"; +import { moduleMessagesFor } from "./moduleMessages.ts"; + +type AdminMessages = readonly Protobuf.Admin.AdminMessage[]; + +/** The editor's device access through the Kotlin SDK facade. */ +export function facadeIo(client: MeshtasticClient): ConfigEditorIo { + return { + onConfig: (cb) => + client.onConfigBundle((bundle) => { + for (const bytes of bundle?.configs ?? []) { + cb(fromBinary(Protobuf.Config.ConfigSchema, bytes)); + } + }), + onModuleConfig: (cb) => + client.onConfigBundle((bundle) => { + for (const bytes of bundle?.moduleConfigs ?? []) { + cb(fromBinary(Protobuf.ModuleConfig.ModuleConfigSchema, bytes)); + } + }), + onChannel: (cb) => + client.onChannels((channels) => { + for (const bytes of channels ?? []) { + cb(fromBinary(Protobuf.Channel.ChannelSchema, bytes)); + } + }), + onDisconnect: (cb) => + client.onConnectionState((state) => { + if (state.kind === "disconnected") cb(); + }), + commit: (messages) => editSettings(client, messages), + }; +} + +/** + * The editor's device access through the TypeScript SDK client, for the + * Serial and Bluetooth connections it still carries. + */ +export function meshClientIo(client: MeshClient): ConfigEditorIo { + return { + onConfig: (cb) => client.events.onConfigPacket.subscribe(cb), + onModuleConfig: (cb) => client.events.onModuleConfigPacket.subscribe(cb), + onChannel: (cb) => client.events.onChannelPacket.subscribe(cb), + onDisconnect: (cb) => + client.events.onDeviceStatus.subscribe((status) => { + if (status === DeviceStatusEnum.DeviceDisconnected) cb(); + }), + commit: (messages) => commitThroughMeshClient(client, messages), + }; +} + +async function commitThroughMeshClient( + client: MeshClient, + messages: AdminMessages, +): Promise> { + let disconnected = false; + const off = client.events.onDeviceStatus.subscribe((status) => { + if (status === DeviceStatusEnum.DeviceDisconnected) disconnected = true; + }); + client.events.onPendingSettingsChange.dispatch(true); + try { + const begin = await sendAdmin(client, { + case: "beginEditSettings", + value: true, + }); + if (Result.isError(begin)) return begin; + for (const message of messages) { + const sent = await sendAdmin(client, message.payloadVariant); + if (Result.isError(sent)) { + // There is no abort message. Close the transaction rather than + // leave it open; the editor keeps everything dirty for a resend. + if (!disconnected) { + await sendAdmin(client, { case: "commitEditSettings", value: true }); + } + return sent; + } + } + return sendAdmin(client, { case: "commitEditSettings", value: true }); + } finally { + off(); + client.events.onPendingSettingsChange.dispatch(false); + } +} + +function isBadSessionKey(e: unknown): boolean { + return ( + typeof e === "object" && + e !== null && + "error" in e && + e.error === Protobuf.Mesh.Routing_Error.ADMIN_BAD_SESSION_KEY + ); +} + +/** + * Sends an admin message to the local node, stamped with its session + * passkey; on `ADMIN_BAD_SESSION_KEY` asks for a fresh one and retries once. + */ +async function sendAdmin( + client: MeshClient, + payloadVariant: Protobuf.Admin.AdminMessage["payloadVariant"], +): Promise> { + const nodeNum = client.myNodeNum; + const send = () => + client.sendPacket( + toBinary( + Protobuf.Admin.AdminMessageSchema, + create(Protobuf.Admin.AdminMessageSchema, { + payloadVariant, + sessionPasskey: client.device.session.get(nodeNum), + }), + ), + Protobuf.Portnums.PortNum.ADMIN_APP, + "self", + Types.ChannelNumber.Primary, + true, + true, + ); + try { + await send(); + return Result.ok(undefined); + } catch (e) { + if (!isBadSessionKey(e)) return Result.err(toError(e)); + client.device.session.forget(nodeNum); + const arrived = client.device.session.waitFor(nodeNum); + client + .sendPacket( + toBinary( + Protobuf.Admin.AdminMessageSchema, + create(Protobuf.Admin.AdminMessageSchema, { + payloadVariant: { case: "getOwnerRequest", value: true }, + }), + ), + Protobuf.Portnums.PortNum.ADMIN_APP, + nodeNum, + Types.ChannelNumber.Primary, + ) + .catch(() => undefined); + if (!(await arrived)) return Result.err(toError(e)); + try { + await send(); + return Result.ok(undefined); + } catch (retry) { + return Result.err(toError(retry)); + } + } +} + +function toError(e: unknown): Error { + return e instanceof Error ? e : new Error(String(e)); +} + +const editors = new WeakMap(); + +/** The one editor for a TypeScript SDK client, created on first use. */ +export function editorFor(client: MeshClient): ConfigEditor { + const existing = editors.get(client); + if (existing) return existing; + const messages = moduleMessagesFor(client); + const editor = new ConfigEditor(meshClientIo(client), { + onStagedAdminMessageCommitted: (message) => messages.applySent(message), + }); + editors.set(client, editor); + return editor; +} diff --git a/apps/web/src/core/kmp/hooks/index.ts b/apps/web/src/core/kmp/hooks/index.ts new file mode 100644 index 000000000..ac770eeec --- /dev/null +++ b/apps/web/src/core/kmp/hooks/index.ts @@ -0,0 +1,8 @@ +export { useConfigEditor } from "./useConfigEditor.ts"; +export { + MODULE_MESSAGES_TIMEOUT_MS, + useCannedMessages, + useRingtone, + type UseModuleMessagesResult, +} from "./useModuleMessages.ts"; +export { useSignal } from "./useSignal.ts"; diff --git a/apps/web/src/core/kmp/hooks/useConfigEditor.ts b/apps/web/src/core/kmp/hooks/useConfigEditor.ts new file mode 100644 index 000000000..b4c1d2d93 --- /dev/null +++ b/apps/web/src/core/kmp/hooks/useConfigEditor.ts @@ -0,0 +1,12 @@ +import type { ConfigEditor } from "@core/kmp/configEditor.ts"; +import { editorFor } from "@core/kmp/configEditorIo.ts"; +import { useActiveClient } from "@meshtastic/sdk-react"; + +/** + * The active connection's `ConfigEditor`, or `undefined` when none is + * active. Components bind to its signals with `useSignal`. + */ +export function useConfigEditor(): ConfigEditor | undefined { + const client = useActiveClient(); + return client ? editorFor(client) : undefined; +} diff --git a/apps/web/src/core/kmp/hooks/useModuleMessages.ts b/apps/web/src/core/kmp/hooks/useModuleMessages.ts new file mode 100644 index 000000000..5b521544e --- /dev/null +++ b/apps/web/src/core/kmp/hooks/useModuleMessages.ts @@ -0,0 +1,82 @@ +import { + type ModuleMessageKind, + moduleMessagesFor, +} from "@core/kmp/moduleMessages.ts"; +import { constantSignal } from "@core/kmp/signals.ts"; +import { useActiveClient } from "@meshtastic/sdk-react"; +import { Result } from "better-result"; +import { useCallback, useEffect, useRef, useState } from "react"; +import { useSignal } from "./useSignal.ts"; + +export const MODULE_MESSAGES_TIMEOUT_MS = 15_000; + +export interface UseModuleMessagesResult { + value: string | undefined; + isLoading: boolean; + error: Error | undefined; + refresh: () => void; +} + +const EMPTY = constantSignal(undefined); + +function useModuleMessages(kind: ModuleMessageKind): UseModuleMessagesResult { + const client = useActiveClient(); + const store = client ? moduleMessagesFor(client) : undefined; + const value = useSignal(store ? store[kind] : EMPTY); + // Loading from the first render, since the request goes out on mount. + const [isLoading, setIsLoading] = useState(store !== undefined); + const [error, setError] = useState(undefined); + const timer = useRef | undefined>(undefined); + + const stopWaiting = useCallback(() => { + clearTimeout(timer.current); + timer.current = undefined; + setIsLoading(false); + }, []); + + // The answer may repeat the cached value, so wait on the response rather + // than on the signal changing. + useEffect(() => { + if (!store) return; + return store.onResponse((answered) => { + if (answered !== kind) return; + setError(undefined); + stopWaiting(); + }); + }, [store, kind, stopWaiting]); + + const refresh = useCallback(() => { + if (!store) return; + clearTimeout(timer.current); + setIsLoading(true); + setError(undefined); + timer.current = setTimeout(() => { + timer.current = undefined; + setIsLoading(false); + setError(new Error("The device did not answer")); + }, MODULE_MESSAGES_TIMEOUT_MS); + store.request(kind).then((result) => { + if (Result.isError(result)) { + setError(result.error); + stopWaiting(); + } + }); + }, [store, kind, stopWaiting]); + + useEffect(() => { + refresh(); + return () => clearTimeout(timer.current); + }, [refresh]); + + return { value, isLoading, error, refresh }; +} + +/** The device's canned message list. Asks the device for it on mount. */ +export function useCannedMessages(): UseModuleMessagesResult { + return useModuleMessages("cannedMessages"); +} + +/** The device's External Notification ringtone. Asks the device for it on mount. */ +export function useRingtone(): UseModuleMessagesResult { + return useModuleMessages("ringtone"); +} diff --git a/apps/web/src/core/kmp/hooks/useSignal.ts b/apps/web/src/core/kmp/hooks/useSignal.ts new file mode 100644 index 000000000..ec38a800f --- /dev/null +++ b/apps/web/src/core/kmp/hooks/useSignal.ts @@ -0,0 +1,11 @@ +import type { ReadonlySignal } from "@core/kmp/signals.ts"; +import { useSyncExternalStore } from "react"; + +/** Subscribes a component to a signal and returns its current value. */ +export function useSignal(sig: ReadonlySignal): T { + return useSyncExternalStore( + sig.subscribe, + () => sig.value, + () => sig.peek(), + ); +} diff --git a/apps/web/src/core/kmp/moduleMessages.ts b/apps/web/src/core/kmp/moduleMessages.ts new file mode 100644 index 000000000..d47b81ebc --- /dev/null +++ b/apps/web/src/core/kmp/moduleMessages.ts @@ -0,0 +1,74 @@ +import type { Protobuf } from "@core/protobuf.ts"; +import { DeviceStatusEnum, type MeshClient } from "@meshtastic/sdk"; +import { signal } from "@preact/signals-core"; +import type { Result } from "better-result"; +import { type ReadonlySignal, toReadonly } from "./signals.ts"; + +export type ModuleMessageKind = "cannedMessages" | "ringtone"; + +/** + * Settings the device keeps outside ModuleConfig, each read and written + * through its own admin message: the canned message list and the + * External Notification ringtone. + */ +export interface ModuleMessages { + cannedMessages: ReadonlySignal; + ringtone: ReadonlySignal; + request(kind: ModuleMessageKind): Promise>; + /** Fires when the device answers a request for `kind`. */ + onResponse(cb: (kind: ModuleMessageKind) => void): () => void; + /** Records a value the device accepted in a commit. */ + applySent(message: Protobuf.Admin.AdminMessage): void; +} + +const stores = new WeakMap(); + +export function moduleMessagesFor(client: MeshClient): ModuleMessages { + const existing = stores.get(client); + if (existing) return existing; + + const cannedMessages = signal(undefined); + const ringtone = signal(undefined); + const listeners = new Set<(kind: ModuleMessageKind) => void>(); + + client.events.onAdminPacket.subscribe((packet) => { + if (packet.from !== client.myNodeNum) return; + const variant = packet.data.payloadVariant; + if (variant.case === "getCannedMessageModuleMessagesResponse") { + cannedMessages.value = variant.value; + for (const cb of listeners) cb("cannedMessages"); + } else if (variant.case === "getRingtoneResponse") { + ringtone.value = variant.value; + for (const cb of listeners) cb("ringtone"); + } + }); + client.events.onDeviceStatus.subscribe((status) => { + if (status === DeviceStatusEnum.DeviceDisconnected) { + cannedMessages.value = undefined; + ringtone.value = undefined; + } + }); + + const store: ModuleMessages = { + cannedMessages: toReadonly(cannedMessages), + ringtone: toReadonly(ringtone), + request: (kind) => + kind === "cannedMessages" + ? client.config.requestCannedMessages() + : client.config.requestRingtone(), + onResponse: (cb) => { + listeners.add(cb); + return () => listeners.delete(cb); + }, + applySent: (message) => { + const variant = message.payloadVariant; + if (variant.case === "setCannedMessageModuleMessages") { + cannedMessages.value = variant.value; + } else if (variant.case === "setRingtoneMessage") { + ringtone.value = variant.value; + } + }, + }; + stores.set(client, store); + return store; +} diff --git a/apps/web/src/core/kmp/signals.ts b/apps/web/src/core/kmp/signals.ts new file mode 100644 index 000000000..b54a1141c --- /dev/null +++ b/apps/web/src/core/kmp/signals.ts @@ -0,0 +1,39 @@ +import type { + ReadonlySignal as PreactReadonlySignal, + Signal, +} from "@preact/signals-core"; + +/** + * Reactive read-only view of a value, matching React's + * `useSyncExternalStore` contract: subscribe for changes, read `value`. + */ +export interface ReadonlySignal { + readonly value: T; + peek(): T; + subscribe(listener: (value: T) => void): () => void; +} + +export function toReadonly( + s: Signal | PreactReadonlySignal, +): ReadonlySignal { + return { + get value() { + return s.value; + }, + peek: () => s.peek(), + subscribe: (listener) => { + let first = true; + return s.subscribe((v) => { + if (first) { + first = false; + return; + } + listener(v); + }); + }, + }; +} + +export function constantSignal(value: T): ReadonlySignal { + return { value, peek: () => value, subscribe: () => () => {} }; +} diff --git a/apps/web/src/pages/Connections/useConnections.ts b/apps/web/src/pages/Connections/useConnections.ts index 4c27d3b88..28530de2f 100644 --- a/apps/web/src/pages/Connections/useConnections.ts +++ b/apps/web/src/pages/Connections/useConnections.ts @@ -5,6 +5,7 @@ import { probeConnection, } from "@app/core/connections/transports.ts"; import { createHttpClient } from "@core/kmp/client.ts"; +import { editorFor } from "@core/kmp/configEditorIo.ts"; import { connectFailure, reconnectAttempt, @@ -184,6 +185,8 @@ export function useConnections() { if (meshRegistry.has(id)) meshRegistry.unregister(id); meshRegistry.register(id, meshDevice.meshClient); meshRegistry.setActive(id); + // Created now so it sees the handshake's config, not on first render. + editorFor(meshDevice.meshClient); setSelectedDevice(deviceId); device.addConnection(meshDevice); diff --git a/apps/web/src/pages/Settings/BackupRestore.tsx b/apps/web/src/pages/Settings/BackupRestore.tsx index ceb9d61dc..8baf58d89 100644 --- a/apps/web/src/pages/Settings/BackupRestore.tsx +++ b/apps/web/src/pages/Settings/BackupRestore.tsx @@ -22,13 +22,10 @@ import { profileContents, selectProfileFields, } from "@core/utils/profileExport.ts"; -import type { ConfigEditor } from "@meshtastic/sdk"; +import type { ConfigEditor } from "@core/kmp/configEditor.ts"; import { Protobuf } from "@core/protobuf.ts"; -import { - useActiveClient, - useConfigEditor, - useSignal, -} from "@meshtastic/sdk-react"; +import { useActiveClient } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { Result } from "better-result"; import { DownloadIcon, UploadIcon } from "lucide-react"; import { type ChangeEvent, useMemo, useRef, useState } from "react"; diff --git a/apps/web/src/pages/Settings/CleanNodeDb.tsx b/apps/web/src/pages/Settings/CleanNodeDb.tsx index 3dc98f82f..915c92c2f 100644 --- a/apps/web/src/pages/Settings/CleanNodeDb.tsx +++ b/apps/web/src/pages/Settings/CleanNodeDb.tsx @@ -17,7 +17,8 @@ import { nodesToClean, } from "@core/utils/cleanNodes.ts"; import type { Node } from "@meshtastic/sdk"; -import { useActiveClient, useSignal } from "@meshtastic/sdk-react"; +import { useActiveClient } from "@meshtastic/sdk-react"; +import { useSignal } from "@core/kmp/hooks"; import { EraserIcon } from "lucide-react"; import { useId, useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/pages/Settings/DeviceConfig.tsx b/apps/web/src/pages/Settings/DeviceConfig.tsx index d5686be33..3734786ec 100644 --- a/apps/web/src/pages/Settings/DeviceConfig.tsx +++ b/apps/web/src/pages/Settings/DeviceConfig.tsx @@ -7,7 +7,7 @@ import { Power } from "@components/PageComponents/Settings/Power.tsx"; import { useDeviceCapabilities } from "@core/hooks/useDeviceCapabilities.ts"; import type { ValidConfigType } from "@core/stores"; import type { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { type ComponentType, useMemo } from "react"; import { useTranslation } from "react-i18next"; import { dirtyDeviceTabs } from "./dirtySections.ts"; diff --git a/apps/web/src/pages/Settings/ModuleConfig.tsx b/apps/web/src/pages/Settings/ModuleConfig.tsx index e0b07fc6f..507a68ebd 100644 --- a/apps/web/src/pages/Settings/ModuleConfig.tsx +++ b/apps/web/src/pages/Settings/ModuleConfig.tsx @@ -17,7 +17,7 @@ import { useDeviceCapabilities } from "@core/hooks/useDeviceCapabilities.ts"; import { useDevice, type ValidModuleConfigType } from "@core/stores"; import { isModuleExcluded } from "@core/utils/excludedModules.ts"; import { Protobuf } from "@core/protobuf.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { type ComponentType, useMemo } from "react"; import { useTranslation } from "react-i18next"; import { dirtyModuleTabs } from "./dirtySections.ts"; diff --git a/apps/web/src/pages/Settings/index.tsx b/apps/web/src/pages/Settings/index.tsx index 2ad84c168..8e139f781 100644 --- a/apps/web/src/pages/Settings/index.tsx +++ b/apps/web/src/pages/Settings/index.tsx @@ -8,7 +8,7 @@ import { SidebarButton } from "@components/UI/Sidebar/SidebarButton.tsx"; import { SidebarSection } from "@components/UI/Sidebar/SidebarSection.tsx"; import { useToast } from "@core/hooks/useToast.ts"; import { cn } from "@core/utils/cn.ts"; -import { useConfigEditor, useSignal } from "@meshtastic/sdk-react"; +import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { About } from "@pages/Settings/About.tsx"; import { Administration } from "@pages/Settings/Administration.tsx"; import { AppSettings } from "@pages/Settings/AppSettings.tsx"; diff --git a/apps/web/src/tests/renderSettingsForm.tsx b/apps/web/src/tests/renderSettingsForm.tsx index dd9144510..3f507efa3 100644 --- a/apps/web/src/tests/renderSettingsForm.tsx +++ b/apps/web/src/tests/renderSettingsForm.tsx @@ -1,3 +1,4 @@ +import { editorFor } from "@core/kmp/configEditorIo.ts"; import { CurrentDeviceContext, useDeviceStore } from "@core/stores"; import { MeshClient, MeshRegistry } from "@meshtastic/sdk"; import type { Protobuf } from "@core/protobuf.ts"; @@ -37,6 +38,7 @@ export function renderSettingsForm( registry.register(id, client); registry.setActive(id); const radio = interceptAdminMessages(client); + const editor = editorFor(client); const stored = useDeviceStore.getState().addDevice(id); for (const config of device.config ?? []) { @@ -61,5 +63,5 @@ export function renderSettingsForm( , ); - return { client, editor: client.config.editor, radio }; + return { client, editor, radio }; } From 8f50a172686053fd5190ab4c5cd8e880a2ca84ee Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 08:28:49 -0500 Subject: [PATCH 12/49] refactor(web): own firmware, logger and admin-size helpers instead of importing them from the TS SDK --- apps/web/package.json | 2 + .../PageComponents/Channels/Channels.tsx | 2 +- .../ModuleConfig/CannedMessage.tsx | 2 +- .../PageComponents/Settings/LoRa.tsx | 2 +- .../PageComponents/Settings/User.tsx | 2 +- .../generic/NodeTrustIndicators.tsx | 12 ++---- apps/web/src/core/connections/sdkClient.ts | 3 +- apps/web/src/core/connections/transports.ts | 3 +- apps/web/src/core/constants.ts | 4 ++ .../src/core/hooks/useDeviceCapabilities.ts | 2 +- apps/web/src/core/log.ts | 27 ++++++++++++ apps/web/src/core/sdkStorage.ts | 2 +- apps/web/src/core/utils/firmware.test.ts | 27 ++++++++++++ apps/web/src/core/utils/firmware.ts | 42 +++++++++++++++++++ .../src/pages/Connections/useConnections.ts | 4 +- apps/web/src/pages/Map/index.tsx | 2 +- .../validation/moduleConfig/cannedMessage.ts | 2 +- .../moduleConfig/externalNotification.ts | 2 +- pnpm-lock.yaml | 3 ++ 19 files changed, 123 insertions(+), 22 deletions(-) create mode 100644 apps/web/src/core/constants.ts create mode 100644 apps/web/src/core/log.ts create mode 100644 apps/web/src/core/utils/firmware.test.ts create mode 100644 apps/web/src/core/utils/firmware.ts diff --git a/apps/web/package.json b/apps/web/package.json index 1ce2898ec..fbcb2406b 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -93,6 +93,7 @@ "react-map-gl": "8.1.3", "react-qrcode-logo": "^4.1.0", "rfc4648": "^1.5.4", + "tslog": "^5.2.0", "vaul": "^1.1.2", "vite": "^8.3.4", "vite-plugin-html": "^3.2.2", @@ -123,6 +124,7 @@ "tailwindcss": "^4.3.3", "tailwindcss-animate": "^1.0.7", "tar": "^7.5.22", + "tslog": "^5.2.0", "typescript": "^7.0.2", "vitest": "^5.0.4" } diff --git a/apps/web/src/components/PageComponents/Channels/Channels.tsx b/apps/web/src/components/PageComponents/Channels/Channels.tsx index 5ed8bec05..6dc7ca3fb 100644 --- a/apps/web/src/components/PageComponents/Channels/Channels.tsx +++ b/apps/web/src/components/PageComponents/Channels/Channels.tsx @@ -2,7 +2,7 @@ import { BeaconOffers } from "@app/components/PageComponents/Channels/BeaconOffe import { Button } from "@components/UI/Button.tsx"; import { useDeviceCapabilities } from "@core/hooks/useDeviceCapabilities.ts"; import { useDevice } from "@core/stores"; -import { firmwareAtLeast } from "@meshtastic/sdk"; +import { firmwareAtLeast } from "@core/utils/firmware.ts"; import type { Protobuf } from "@core/protobuf.ts"; import { useChannels } from "@meshtastic/sdk-react"; import { useConfigEditor, useSignal } from "@core/kmp/hooks"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/CannedMessage.tsx b/apps/web/src/components/PageComponents/ModuleConfig/CannedMessage.tsx index 0d7a5b669..6f8da7de5 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/CannedMessage.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/CannedMessage.tsx @@ -9,7 +9,7 @@ import { } from "@components/Form/DynamicForm.tsx"; import { useDeviceCapabilities } from "@core/hooks/useDeviceCapabilities.ts"; import { useDevice } from "@core/stores"; -import { firmwareAtLeast } from "@meshtastic/sdk"; +import { firmwareAtLeast } from "@core/utils/firmware.ts"; import { Protobuf } from "@core/protobuf.ts"; import { useCannedMessages, useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useMemo } from "react"; diff --git a/apps/web/src/components/PageComponents/Settings/LoRa.tsx b/apps/web/src/components/PageComponents/Settings/LoRa.tsx index f170ba46f..32e697c83 100644 --- a/apps/web/src/components/PageComponents/Settings/LoRa.tsx +++ b/apps/web/src/components/PageComponents/Settings/LoRa.tsx @@ -24,7 +24,7 @@ import { getLicensedOnlyRegions, pickEnumValues, } from "@core/utils/loraPresets.ts"; -import { firmwareAtLeast } from "@meshtastic/sdk"; +import { firmwareAtLeast } from "@core/utils/firmware.ts"; import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useEffect, useMemo, useState } from "react"; diff --git a/apps/web/src/components/PageComponents/Settings/User.tsx b/apps/web/src/components/PageComponents/Settings/User.tsx index c26776b33..27b289154 100644 --- a/apps/web/src/components/PageComponents/Settings/User.tsx +++ b/apps/web/src/components/PageComponents/Settings/User.tsx @@ -12,7 +12,7 @@ import { useDeviceCapabilities } from "@core/hooks/useDeviceCapabilities.ts"; import { useMyNodeAsProto } from "@core/hooks/useNodesAsProto.ts"; import { useDevice } from "@core/stores"; import { isModuleExcluded } from "@core/utils/excludedModules.ts"; -import { firmwareAtLeast } from "@meshtastic/sdk"; +import { firmwareAtLeast } from "@core/utils/firmware.ts"; import { Protobuf } from "@core/protobuf.ts"; import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useEffect } from "react"; diff --git a/apps/web/src/components/generic/NodeTrustIndicators.tsx b/apps/web/src/components/generic/NodeTrustIndicators.tsx index 0630f53d5..a061d843d 100644 --- a/apps/web/src/components/generic/NodeTrustIndicators.tsx +++ b/apps/web/src/components/generic/NodeTrustIndicators.tsx @@ -6,7 +6,6 @@ import { TooltipTrigger, } from "@components/UI/Tooltip.tsx"; import { cn } from "@core/utils/cn.ts"; -import { isUnheardOnCurrentLora } from "@meshtastic/sdk"; import type { Protobuf } from "@core/protobuf.ts"; import type { LucideIcon } from "lucide-react"; import { RadioTowerIcon, SignatureIcon, VolumeXIcon } from "lucide-react"; @@ -19,16 +18,11 @@ type TrustNode = Pick< /** * True for a node the radio hasn't heard on its current LoRa settings. - * Wraps the SDK helper so it accepts the proto NodeInfo the web uses. + * Nodes seen only over MQTT are never "unheard": LoRa settings don't apply. + * Firmware older than 2.8.1 doesn't report it, so every node counts as heard. */ export const isNodeUnheardOnCurrentLora = (node: TrustNode): boolean => - isUnheardOnCurrentLora({ - num: node.num, - isFavorite: false, - isIgnored: false, - heardOnCurrentLora: node.heardOnCurrentLora, - viaMqtt: node.viaMqtt, - }); + node.heardOnCurrentLora === false && !node.viaMqtt; interface IndicatorProps { icon: LucideIcon; diff --git a/apps/web/src/core/connections/sdkClient.ts b/apps/web/src/core/connections/sdkClient.ts index cad03723f..ea4508085 100644 --- a/apps/web/src/core/connections/sdkClient.ts +++ b/apps/web/src/core/connections/sdkClient.ts @@ -1,6 +1,7 @@ import { coordinator, getStorageDb } from "@core/sdkStorage.ts"; import type { ConnectionId } from "@core/stores/deviceStore/types"; -import { createLogger, MeshDevice, type Transport } from "@meshtastic/sdk"; +import { createLogger } from "@core/log.ts"; +import { MeshDevice, type Transport } from "@meshtastic/sdk"; import { SqlocalDraftRepository, SqlocalMessageRepository, diff --git a/apps/web/src/core/connections/transports.ts b/apps/web/src/core/connections/transports.ts index f7057e658..e837180d4 100644 --- a/apps/web/src/core/connections/transports.ts +++ b/apps/web/src/core/connections/transports.ts @@ -1,6 +1,7 @@ import type { Connection } from "@core/stores/deviceStore/types"; import { httpErrorMessage, testHttpReachable } from "@pages/Connections/utils"; -import { createLogger, type Transport } from "@meshtastic/sdk"; +import { createLogger } from "@core/log.ts"; +import type { Transport } from "@meshtastic/sdk"; import { BluetoothConnectError, TransportWebBluetooth, diff --git a/apps/web/src/core/constants.ts b/apps/web/src/core/constants.ts new file mode 100644 index 000000000..3227fb4d4 --- /dev/null +++ b/apps/web/src/core/constants.ts @@ -0,0 +1,4 @@ +/** Longest canned message list the firmware stores, in UTF-8 bytes. */ +export const CANNED_MESSAGES_MAX_BYTES = 200; +/** Longest RTTTL ringtone the firmware stores, in UTF-8 bytes. */ +export const RINGTONE_MAX_BYTES = 230; diff --git a/apps/web/src/core/hooks/useDeviceCapabilities.ts b/apps/web/src/core/hooks/useDeviceCapabilities.ts index 08fffe009..9fbec483f 100644 --- a/apps/web/src/core/hooks/useDeviceCapabilities.ts +++ b/apps/web/src/core/hooks/useDeviceCapabilities.ts @@ -1,5 +1,5 @@ import { useDevice } from "@core/stores"; -import { firmwareAtLeast } from "@meshtastic/sdk"; +import { firmwareAtLeast } from "@core/utils/firmware.ts"; import type { Protobuf } from "@core/protobuf.ts"; import { useActiveClient } from "@meshtastic/sdk-react"; import { useSignal } from "@core/kmp/hooks"; diff --git a/apps/web/src/core/log.ts b/apps/web/src/core/log.ts new file mode 100644 index 000000000..345b65663 --- /dev/null +++ b/apps/web/src/core/log.ts @@ -0,0 +1,27 @@ +import { Logger } from "tslog"; + +const prettyLogTemplate = + "{{hh}}:{{MM}}:{{ss}}:{{ms}}\t{{logLevelName}}\t[{{name}}]\t"; + +/** `debug` when `localStorage["mesh-debug"]` is "1", else `info`. */ +function defaultMinLevel(): number { + try { + if (globalThis.localStorage?.getItem("mesh-debug") === "1") return 2; + } catch { + // localStorage access can throw in private mode and sandboxed iframes. + } + return 3; +} + +export function createLogger( + name: string, + options?: { minLevel?: number }, +): Logger { + return new Logger({ + name, + pretty: { template: prettyLogTemplate }, + minLevel: options?.minLevel ?? defaultMinLevel(), + }); +} + +export type { Logger }; diff --git a/apps/web/src/core/sdkStorage.ts b/apps/web/src/core/sdkStorage.ts index 7a302cfad..8b5222f1c 100644 --- a/apps/web/src/core/sdkStorage.ts +++ b/apps/web/src/core/sdkStorage.ts @@ -1,4 +1,4 @@ -import { createLogger } from "@meshtastic/sdk"; +import { createLogger } from "@core/log.ts"; import { MultiTabCoordinator, type OpenedSqlocalDb, diff --git a/apps/web/src/core/utils/firmware.test.ts b/apps/web/src/core/utils/firmware.test.ts new file mode 100644 index 000000000..69b4f7009 --- /dev/null +++ b/apps/web/src/core/utils/firmware.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from "vitest"; +import { + firmwareAtLeast, + firmwareSupport, + parseFirmwareVersion, +} from "./firmware.ts"; + +describe("firmware versions", () => { + it("parses a version with a hash suffix", () => { + expect(parseFirmwareVersion("2.7.15.abc1234")).toEqual([2, 7, 15]); + expect(parseFirmwareVersion("")).toBeUndefined(); + }); + + it("compares versions numerically", () => { + expect(firmwareAtLeast("2.10.0", "2.9.5")).toBe(true); + expect(firmwareAtLeast("2.7.18", "2.7.18")).toBe(true); + expect(firmwareAtLeast("2.7.17", "2.7.18")).toBe(false); + expect(firmwareAtLeast("garbage", "2.7.18")).toBe(false); + }); + + it("grades support like the Android app", () => { + expect(firmwareSupport("2.8.0")).toBe("supported"); + expect(firmwareSupport("2.4.0")).toBe("shouldUpdate"); + expect(firmwareSupport("2.3.0")).toBe("tooOld"); + expect(firmwareSupport("")).toBe("unknown"); + }); +}); diff --git a/apps/web/src/core/utils/firmware.ts b/apps/web/src/core/utils/firmware.ts new file mode 100644 index 000000000..08ccb2c64 --- /dev/null +++ b/apps/web/src/core/utils/firmware.ts @@ -0,0 +1,42 @@ +/** + * Firmware support levels, matching the Android app's DeviceVersion checks. + * Below {@link MIN_FIRMWARE_VERSION} the client still works but the user + * should update; below {@link ABS_MIN_FIRMWARE_VERSION} the client refuses + * to connect. A version that doesn't parse (lockdown sends an empty one) is + * "unknown", never "too old". + */ +export const MIN_FIRMWARE_VERSION = "2.5.14"; +export const ABS_MIN_FIRMWARE_VERSION = "2.3.15"; + +export type FirmwareSupport = + | "supported" + | "shouldUpdate" + | "tooOld" + | "unknown"; + +type Version = [number, number, number]; + +/** Parses "2.7.15.abc1234" or "2.7.15" into [major, minor, patch]. */ +export function parseFirmwareVersion(version: string): Version | undefined { + const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version.trim()); + if (!match) return undefined; + return [Number(match[1]), Number(match[2]), Number(match[3])]; +} + +export function compareFirmwareVersions(a: Version, b: Version): number { + return a[0] - b[0] || a[1] - b[1] || a[2] - b[2]; +} + +/** True when `version` parses and is at least `minimum`. */ +export function firmwareAtLeast(version: string, minimum: string): boolean { + const v = parseFirmwareVersion(version); + const min = parseFirmwareVersion(minimum); + return !!v && !!min && compareFirmwareVersions(v, min) >= 0; +} + +export function firmwareSupport(version: string): FirmwareSupport { + if (!parseFirmwareVersion(version)) return "unknown"; + if (!firmwareAtLeast(version, ABS_MIN_FIRMWARE_VERSION)) return "tooOld"; + if (!firmwareAtLeast(version, MIN_FIRMWARE_VERSION)) return "shouldUpdate"; + return "supported"; +} diff --git a/apps/web/src/pages/Connections/useConnections.ts b/apps/web/src/pages/Connections/useConnections.ts index 28530de2f..433016aff 100644 --- a/apps/web/src/pages/Connections/useConnections.ts +++ b/apps/web/src/pages/Connections/useConnections.ts @@ -13,11 +13,11 @@ import { } from "@core/kmp/connectionState.ts"; import { kmpTransport } from "@core/kmp/transport.ts"; import { toast } from "@core/hooks/useToast.ts"; +import { createLogger } from "@core/log.ts"; +import { MIN_FIRMWARE_VERSION } from "@core/utils/firmware.ts"; import { - createLogger, DeviceStatusEnum, FirmwareTooOldError, - MIN_FIRMWARE_VERSION, type Transport, } from "@meshtastic/sdk"; import { t } from "i18next"; diff --git a/apps/web/src/pages/Map/index.tsx b/apps/web/src/pages/Map/index.tsx index 212c0531e..f33f92354 100644 --- a/apps/web/src/pages/Map/index.tsx +++ b/apps/web/src/pages/Map/index.tsx @@ -31,7 +31,7 @@ import { } from "@core/hooks/useNodesAsProto.ts"; import { cn } from "@core/utils/cn.ts"; import { hasPos, toLngLat } from "@core/utils/geo.ts"; -import { createLogger } from "@meshtastic/sdk"; +import { createLogger } from "@core/log.ts"; import type { Protobuf } from "@core/protobuf.ts"; import { numberToHexUnpadded } from "@noble/curves/utils.js"; import { FunnelIcon, LocateFixedIcon } from "lucide-react"; diff --git a/apps/web/src/validation/moduleConfig/cannedMessage.ts b/apps/web/src/validation/moduleConfig/cannedMessage.ts index 0dc565656..9c43bc218 100644 --- a/apps/web/src/validation/moduleConfig/cannedMessage.ts +++ b/apps/web/src/validation/moduleConfig/cannedMessage.ts @@ -1,5 +1,5 @@ import { validateMaxByteLength } from "@core/utils/string.ts"; -import { CANNED_MESSAGES_MAX_BYTES } from "@meshtastic/sdk"; +import { CANNED_MESSAGES_MAX_BYTES } from "@core/constants.ts"; import { Protobuf } from "@core/protobuf.ts"; import { z } from "zod/v4"; diff --git a/apps/web/src/validation/moduleConfig/externalNotification.ts b/apps/web/src/validation/moduleConfig/externalNotification.ts index 0c2d7a503..baf7fdc1b 100644 --- a/apps/web/src/validation/moduleConfig/externalNotification.ts +++ b/apps/web/src/validation/moduleConfig/externalNotification.ts @@ -1,5 +1,5 @@ import { validateMaxByteLength } from "@core/utils/string.ts"; -import { RINGTONE_MAX_BYTES } from "@meshtastic/sdk"; +import { RINGTONE_MAX_BYTES } from "@core/constants.ts"; import { z } from "zod/v4"; export const ExternalNotificationValidationSchema = z.object({ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 447f90ecc..15d0fe2e7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -237,6 +237,9 @@ importers: rfc4648: specifier: ^1.5.4 version: 1.5.4 + tslog: + specifier: ^5.2.0 + version: 5.2.0 vaul: specifier: ^1.1.2 version: 1.1.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) From 7c06ea3a7c3a2e81a1c123fb360ca5f46dfe091a Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 08:43:48 -0500 Subject: [PATCH 13/49] feat(sdk-kmp): Web Serial and Web Bluetooth transports for the Kotlin SDK WebSerialTransport and WebBluetoothTransport implement RadioTransport in jsMain. They never prompt: the web client passes the SerialPort or BluetoothDevice it picked inside a click handler, and every automatic connect or SDK reconnect reopens through getPorts() (matched on the saved USB ids) or getDevices(). OS disconnect events become recoverable transport errors so the SDK's auto-reconnect runs. Serial framing comes from a small FrameAssembler over the SDK's WireFraming constants, since SerialFrameAssembler and BleTransport are not in the published js klib. Adds a Node test target with 21 Kotlin tests. --- packages/sdk-kmp/README.md | 28 ++- packages/sdk-kmp/build.gradle.kts | 4 + packages/sdk-kmp/package.json | 3 +- .../kotlin/org/meshtastic/sdk/js/Client.kt | 18 ++ .../kotlin/org/meshtastic/sdk/js/Framing.kt | 91 +++++++ .../org/meshtastic/sdk/js/HttpTransport.kt | 18 +- .../org/meshtastic/sdk/js/TappingTransport.kt | 5 +- .../sdk/js/WebBluetoothTransport.kt | 225 +++++++++++++++++ .../meshtastic/sdk/js/WebSerialTransport.kt | 235 ++++++++++++++++++ .../meshtastic/sdk/js/FrameAssemblerTest.kt | 51 ++++ .../sdk/js/WebBluetoothTransportTest.kt | 207 +++++++++++++++ .../sdk/js/WebSerialTransportTest.kt | 189 ++++++++++++++ 12 files changed, 1049 insertions(+), 25 deletions(-) create mode 100644 packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Framing.kt create mode 100644 packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebBluetoothTransport.kt create mode 100644 packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebSerialTransport.kt create mode 100644 packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/FrameAssemblerTest.kt create mode 100644 packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebBluetoothTransportTest.kt create mode 100644 packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebSerialTransportTest.kt diff --git a/packages/sdk-kmp/README.md b/packages/sdk-kmp/README.md index eeb772310..6506b0e10 100644 --- a/packages/sdk-kmp/README.md +++ b/packages/sdk-kmp/README.md @@ -6,12 +6,30 @@ The SDK owns all mesh and connection behaviour (handshake, connection state, auto-reconnect, node DB, admin); this package owns only the glue: - `src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt`: the `@JsExport` surface - (`createHttpClient`, `MeshtasticClient`, `ConnectionStateJs`). Only plain - objects, `Promise`s, `Uint8Array`s and unsubscribe functions cross into - TypeScript; protobuf messages cross as bytes and are decoded with - `@meshtastic/protobufs`. + (`createHttpClient`, `createSerialClient`, `createBluetoothClient`, + `MeshtasticClient`, `ConnectionStateJs`). Only plain objects, `Promise`s, + `Uint8Array`s and unsubscribe functions cross into TypeScript; protobuf + messages cross as bytes and are decoded with `@meshtastic/protobufs`. - Browser transports implementing the SDK's `RadioTransport`: `HttpTransport.kt` - (device HTTP API with Chrome Local Network Access handling in `Lna.kt`). + (device HTTP API with Chrome Local Network Access handling in `Lna.kt`), + `WebSerialTransport.kt` (stream framing from `Framing.kt`) and + `WebBluetoothTransport.kt` (the Meshtastic GATT service). Neither prompts: + `requestPort` / `requestDevice` are the web client's job, inside a click + handler, and the chosen handle is passed to the factory; every automatic + connect and reconnect reopens through `navigator.serial.getPorts()` (matched + on the saved USB ids) or `navigator.bluetooth.getDevices()`. The SDK's + `BleTransport` (Kable) is not used because `transport-ble` has no `js` + target in the published artifacts. + +## Tests + +```bash +pnpm --filter @meshtastic/sdk-kmp test +``` + +runs the `jsTest` suite on Node (`./gradlew jsNodeTest`): the frame assembler +and both transports against scripted `navigator.serial` / `navigator.bluetooth` +fakes. ## Prerequisites diff --git a/packages/sdk-kmp/build.gradle.kts b/packages/sdk-kmp/build.gradle.kts index 6eb2d3fdf..a89f1bbb4 100644 --- a/packages/sdk-kmp/build.gradle.kts +++ b/packages/sdk-kmp/build.gradle.kts @@ -12,6 +12,7 @@ val sdkVersion = providers.gradleProperty("meshtasticSdkVersion").get() kotlin { js { browser() + nodejs() binaries.library() generateTypeScriptDefinitions() useEsModules() @@ -20,6 +21,9 @@ kotlin { jsMain.dependencies { api("org.meshtastic:sdk-core:$sdkVersion") } + jsTest.dependencies { + implementation(kotlin("test")) + } } } diff --git a/packages/sdk-kmp/package.json b/packages/sdk-kmp/package.json index 4fff403fb..7263a7048 100644 --- a/packages/sdk-kmp/package.json +++ b/packages/sdk-kmp/package.json @@ -24,6 +24,7 @@ "scripts": { "build": "node ./scripts/build.mjs", "ensure-dist": "node ./scripts/build.mjs --if-missing", - "clean": "rm -rf dist build" + "clean": "rm -rf dist build", + "test": "./gradlew jsNodeTest --console=plain -q" } } diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt index c96e1d748..d4ba1e9ce 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt @@ -176,3 +176,21 @@ class MeshtasticClient internal constructor(transport: RadioTransport, private v @JsExport fun createHttpClient(url: String, allowPrompt: Boolean = false, maxAttempts: Int = 10): MeshtasticClient = MeshtasticClient(HttpTransport(url.trimEnd('/'), allowPrompt), maxAttempts) + +/** + * A client over Web Serial. `port` is a `SerialPort` picked inside a user + * gesture, or null to reopen the permitted port matching the USB ids + * without prompting. + */ +@JsExport +fun createSerialClient(port: dynamic, usbVendorId: Int?, usbProductId: Int?, maxAttempts: Int = 10): MeshtasticClient = + MeshtasticClient(WebSerialTransport(port, usbVendorId, usbProductId), maxAttempts) + +/** + * A client over Web Bluetooth. `device` is a `BluetoothDevice` picked inside + * a user gesture, or null to look `deviceId` up through `getDevices()` + * without prompting. + */ +@JsExport +fun createBluetoothClient(device: dynamic, deviceId: String?, maxAttempts: Int = 10): MeshtasticClient = + MeshtasticClient(WebBluetoothTransport(device, deviceId), maxAttempts) diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Framing.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Framing.kt new file mode 100644 index 000000000..c59fd4d18 --- /dev/null +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Framing.kt @@ -0,0 +1,91 @@ +package org.meshtastic.sdk.js + +import okio.Buffer +import okio.ByteString +import okio.ByteString.Companion.toByteString +import org.meshtastic.sdk.Frame +import org.meshtastic.sdk.WireFraming + +/** Wraps a bare protobuf payload in the SDK's stream header (`0x94 0xC3 LEN_HI LEN_LO`). */ +internal fun framed(payload: ByteArray): ByteString { + val frame = ByteArray(WireFraming.HEADER_SIZE + payload.size) + frame[0] = WireFraming.MAGIC_0 + frame[1] = WireFraming.MAGIC_1 + frame[2] = (payload.size shr 8).toByte() + frame[3] = (payload.size and 0xFF).toByte() + payload.copyInto(frame, WireFraming.HEADER_SIZE) + return frame.toByteString() +} + +/** The protobuf payload of a framed packet, header removed. */ +internal fun payloadOf(frame: Frame): ByteArray { + val bytes = frame.bytes.toByteArray() + return if (bytes.size > WireFraming.HEADER_SIZE) bytes.copyOfRange(WireFraming.HEADER_SIZE, bytes.size) else ByteArray(0) +} + +/** + * Re-sync state machine for the serial byte stream, equivalent to the SDK's + * `SerialFrameAssembler` (which is not in the published js klib). Feed it the + * chunks a port delivers; it calls [onFrame] with every complete frame, + * header included, and resynchronises after garbage or an oversized length. + */ +internal class FrameAssembler(private val onFrame: (Frame) -> Unit) { + private enum class State { SCAN_FOR_START1, EXPECT_START2, READ_LEN_HI, READ_LEN_LO, READ_PAYLOAD } + + private var state = State.SCAN_FOR_START1 + private var lenHi = 0 + private var payloadLen = 0 + private var bytesRemaining = 0 + private val payload = Buffer() + + fun feed(bytes: ByteArray) { + for (b in bytes) feed(b) + } + + fun feed(byte: Byte) { + when (state) { + State.SCAN_FOR_START1 -> if (byte == WireFraming.MAGIC_0) state = State.EXPECT_START2 + + State.EXPECT_START2 -> state = when (byte) { + WireFraming.MAGIC_1 -> State.READ_LEN_HI + WireFraming.MAGIC_0 -> State.EXPECT_START2 + else -> State.SCAN_FOR_START1 + } + + State.READ_LEN_HI -> { + lenHi = byte.toInt() and 0xFF + state = State.READ_LEN_LO + } + + State.READ_LEN_LO -> { + payloadLen = (lenHi shl 8) or (byte.toInt() and 0xFF) + when { + payloadLen > WireFraming.MAX_PAYLOAD_SIZE -> { + payload.clear() + state = State.SCAN_FOR_START1 + } + + payloadLen == 0 -> { + state = State.SCAN_FOR_START1 + onFrame(Frame(framed(ByteArray(0)))) + } + + else -> { + bytesRemaining = payloadLen + state = State.READ_PAYLOAD + } + } + } + + State.READ_PAYLOAD -> { + payload.writeByte(byte.toInt()) + if (--bytesRemaining == 0) { + val complete = payload.readByteArray() + payload.clear() + state = State.SCAN_FOR_START1 + onFrame(Frame(framed(complete))) + } + } + } + } +} diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/HttpTransport.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/HttpTransport.kt index d3afcd7a0..b4b4cf1c8 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/HttpTransport.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/HttpTransport.kt @@ -14,14 +14,12 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.isActive import kotlinx.coroutines.launch -import okio.ByteString.Companion.toByteString import org.khronos.webgl.ArrayBuffer import org.khronos.webgl.Uint8Array import org.meshtastic.sdk.Frame import org.meshtastic.sdk.RadioTransport import org.meshtastic.sdk.TransportIdentity import org.meshtastic.sdk.TransportState -import org.meshtastic.sdk.WireFraming import kotlin.js.Promise internal class HttpTransport( @@ -71,7 +69,7 @@ internal class HttpTransport( val response = request("$baseUrl/api/v1/fromradio?all=false", "GET") val buffer = (response.arrayBuffer() as Promise).await() if (buffer.byteLength == 0) return - inbound.trySend(Frame(WireFraming.frame(Uint8Array(buffer).toByteArray()))) + inbound.trySend(Frame(framed(Uint8Array(buffer).toByteArray()))) } } @@ -83,7 +81,7 @@ internal class HttpTransport( override suspend fun send(frame: Frame) { val init = Lna.requestInit(baseUrl, "PUT") - init.body = WireFraming.payload(frame.bytes.toByteArray()).toUint8Array() + init.body = payloadOf(frame).toUint8Array() val response = fetch("$baseUrl/api/v1/toradio", init).await() if (response.ok != true) throw ClientException("transport", "toradio ${response.status}") } @@ -96,15 +94,3 @@ internal class HttpTransport( return response } } - -private fun WireFraming.frame(payload: ByteArray): okio.ByteString { - val framed = ByteArray(HEADER_SIZE + payload.size) - framed[0] = MAGIC_0 - framed[1] = MAGIC_1 - framed[2] = (payload.size shr 8).toByte() - framed[3] = (payload.size and 0xFF).toByte() - payload.copyInto(framed, HEADER_SIZE) - return framed.toByteString() -} - -private fun WireFraming.payload(framed: ByteArray): ByteArray = framed.copyOfRange(HEADER_SIZE, framed.size) diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/TappingTransport.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/TappingTransport.kt index 61bb18a8f..fc52d0feb 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/TappingTransport.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/TappingTransport.kt @@ -7,7 +7,6 @@ import org.meshtastic.sdk.Frame import org.meshtastic.sdk.RadioTransport import org.meshtastic.sdk.TransportIdentity import org.meshtastic.sdk.TransportState -import org.meshtastic.sdk.WireFraming internal class TappingTransport( private val inner: RadioTransport, @@ -23,7 +22,7 @@ internal class TappingTransport( override suspend fun send(frame: Frame) = inner.send(frame) override fun frames(): Flow = inner.frames().onEach { frame -> - val bytes = frame.bytes.toByteArray() - if (bytes.size > WireFraming.HEADER_SIZE) tap(bytes.copyOfRange(WireFraming.HEADER_SIZE, bytes.size)) + val payload = payloadOf(frame) + if (payload.isNotEmpty()) tap(payload) } } diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebBluetoothTransport.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebBluetoothTransport.kt new file mode 100644 index 000000000..fc91989f4 --- /dev/null +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebBluetoothTransport.kt @@ -0,0 +1,225 @@ +package org.meshtastic.sdk.js + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.await +import kotlinx.coroutines.cancel +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.receiveAsFlow +import kotlinx.coroutines.launch +import org.khronos.webgl.ArrayBuffer +import org.khronos.webgl.Uint8Array +import org.meshtastic.sdk.Frame +import org.meshtastic.sdk.RadioTransport +import org.meshtastic.sdk.TransportIdentity +import org.meshtastic.sdk.TransportState +import kotlin.js.Promise + +/** + * Web Bluetooth as an SDK transport, on the Meshtastic GATT service: `fromnum` + * notifications wake a drain of `fromradio` until it reads empty, and sends + * are acknowledged writes to `toradio`. Never prompts: `device` is a + * `BluetoothDevice` the host obtained from `requestDevice()` inside a user + * gesture, or null, in which case connects look `deviceId` up through + * `navigator.bluetooth.getDevices()`. + */ +internal class WebBluetoothTransport( + private var device: dynamic, + deviceId: String?, +) : RadioTransport { + override val identity: TransportIdentity = + TransportIdentity("ble:${deviceId ?: (device?.id as? String) ?: "?"}") + private val wantedId: String? = deviceId ?: device?.id as? String + private val _state = MutableStateFlow(TransportState.Disconnected) + override val state: StateFlow = _state.asStateFlow() + private val inbound = Channel(Channel.UNLIMITED) + private var scope: CoroutineScope? = null + private var server: dynamic = null + private var toRadio: dynamic = null + private var fromRadio: dynamic = null + private var fromNum: dynamic = null + private var closing = false + private var draining = false + private var drainWanted = false + + private val onGattDisconnected: (dynamic) -> Unit = { _ -> dropped("Bluetooth device disconnected") } + private val onFromNumChanged: (dynamic) -> Unit = { _ -> wakeDrain() } + + override suspend fun connect() { + _state.value = TransportState.Connecting + closing = false + try { + val bluetooth = bluetoothApi() ?: throw ClientException( + UNSUPPORTED, + "Web Bluetooth is not supported in this browser", + ) + val d = device ?: findDevice(bluetooth) ?: throw ClientException( + UNAVAILABLE, + "Bluetooth device not available. Re-select the device.", + ) + device = d + val gatt = d.gatt ?: throw ClientException(UNAVAILABLE, "Device does not expose a GATT server. Re-pair the device.") + server = connectGatt(gatt) + val service = try { + (server.getPrimaryService(SERVICE_UUID) as Promise).await() + } catch (e: Throwable) { + throw ClientException( + MISSING_SERVICE, + "Device does not advertise the Meshtastic GATT service. The firmware may be too old or the device is in another mode.", + ) + } + toRadio = (service.getCharacteristic(TORADIO_UUID) as Promise).await() + fromRadio = (service.getCharacteristic(FROMRADIO_UUID) as Promise).await() + fromNum = (service.getCharacteristic(FROMNUM_UUID) as Promise).await() + d.addEventListener("gattserverdisconnected", onGattDisconnected) + (fromNum.startNotifications() as Promise).await() + fromNum.addEventListener("characteristicvaluechanged", onFromNumChanged) + } catch (e: CancellationException) { + _state.value = TransportState.Disconnected + release() + throw e + } catch (e: Throwable) { + _state.value = TransportState.Disconnected + release() + throw if (e is ClientException) e else ClientException(UNAVAILABLE, bluetoothFailure(e)) + } + _state.value = TransportState.Connected + scope = CoroutineScope(SupervisorJob()) + wakeDrain() + } + + override suspend fun disconnect() { + closing = true + scope?.cancel() + scope = null + release() + _state.value = TransportState.Disconnected + } + + override suspend fun send(frame: Frame) { + val characteristic = toRadio ?: throw ClientException("transport", "Bluetooth device is not connected") + val payload = payloadOf(frame).toUint8Array() + val buffer: ArrayBuffer = payload.buffer.slice(payload.byteOffset, payload.byteOffset + payload.length) + try { + val write = if (characteristic.writeValueWithResponse != null) { + characteristic.writeValueWithResponse(buffer) + } else { + characteristic.writeValue(buffer) + } + (write as Promise).await() + } catch (e: Throwable) { + dropped(e.message ?: "Bluetooth write failed") + throw ClientException("transport", e.message ?: "Bluetooth write failed") + } + wakeDrain() + } + + override fun frames(): Flow = inbound.receiveAsFlow() + + private suspend fun findDevice(bluetooth: dynamic): dynamic { + val id = wantedId ?: return null + if (bluetooth.getDevices == null) return null + val known = (bluetooth.getDevices() as Promise>).await() + return known.firstOrNull { it.id == id } + } + + private suspend fun connectGatt(gatt: dynamic): dynamic { + try { + return (gatt.connect() as Promise).await() + } catch (first: Throwable) { + if (!isTransient(first)) throw ClientException(UNAVAILABLE, bluetoothFailure(first)) + delay(TRANSIENT_RETRY_DELAY_MS) + try { + return (gatt.connect() as Promise).await() + } catch (e: Throwable) { + throw ClientException( + UNAVAILABLE, + "Bluetooth connection failed twice. Check the device is in range, powered on, and not paired with a phone or another browser tab. Then click Retry.", + ) + } + } + } + + private fun wakeDrain() { + drainWanted = true + if (draining) return + scope?.launch { drain() } + } + + private suspend fun drain() { + if (draining) return + draining = true + try { + while (drainWanted && !closing) { + drainWanted = false + while (!closing) { + val characteristic = fromRadio ?: return + val value = (characteristic.readValue() as Promise).await() + if (value.byteLength == 0) break + val bytes = Uint8Array(value.buffer as ArrayBuffer, value.byteOffset as Int, value.byteLength as Int) + inbound.trySend(Frame(framed(bytes.toByteArray()))) + } + } + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + dropped(e.message ?: "Bluetooth read failed") + } finally { + draining = false + } + } + + private fun dropped(reason: String) { + if (closing || _state.value !is TransportState.Connected) return + _state.value = TransportState.Error(ClientException(DISCONNECTED, reason), recoverable = true) + scope?.launch { release() } + } + + private fun release() { + val d = device + try { + fromNum?.removeEventListener("characteristicvaluechanged", onFromNumChanged) + fromNum?.stopNotifications() + } catch (_: Throwable) { + } + try { + d?.removeEventListener("gattserverdisconnected", onGattDisconnected) + if (server?.connected == true) server.disconnect() + } catch (_: Throwable) { + } + server = null + toRadio = null + fromRadio = null + fromNum = null + } + + private companion object { + const val SERVICE_UUID = "6ba1b218-15a8-461f-9fa8-5dcae273eafd" + const val TORADIO_UUID = "f75c76d2-129e-4dad-a1dd-7866124401e7" + const val FROMRADIO_UUID = "2c55e69e-4993-11ed-b878-0242ac120002" + const val FROMNUM_UUID = "ed9da18c-a800-4f66-a670-aa7547e34453" + const val UNSUPPORTED = "bluetooth-unsupported" + const val UNAVAILABLE = "bluetooth-unavailable" + const val MISSING_SERVICE = "bluetooth-missing-service" + const val DISCONNECTED = "bluetooth-disconnected" + const val TRANSIENT_RETRY_DELAY_MS = 750L + + fun bluetoothApi(): dynamic { + val bluetooth = js("globalThis.navigator ? globalThis.navigator.bluetooth : undefined") + return if (bluetooth == null) null else bluetooth + } + + fun isTransient(e: Throwable): Boolean = + e.asDynamic().name == "NetworkError" || + Regex("connection attempt failed|gatt", RegexOption.IGNORE_CASE).containsMatchIn(e.message ?: "") + + fun bluetoothFailure(e: Throwable): String = + "Bluetooth connection failed. Make sure the device is in range, powered on, and not connected to a phone or another browser tab. (${e.message})" + } +} diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebSerialTransport.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebSerialTransport.kt new file mode 100644 index 000000000..f43fcf710 --- /dev/null +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebSerialTransport.kt @@ -0,0 +1,235 @@ +package org.meshtastic.sdk.js + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.await +import kotlinx.coroutines.cancel +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.receiveAsFlow +import kotlinx.coroutines.launch +import org.khronos.webgl.Uint8Array +import org.meshtastic.sdk.Frame +import org.meshtastic.sdk.RadioTransport +import org.meshtastic.sdk.TransportIdentity +import org.meshtastic.sdk.TransportState +import kotlin.js.Promise + +/** + * Web Serial as an SDK transport. Never prompts: `port` is a `SerialPort` + * the host obtained from `navigator.serial.requestPort()` inside a user + * gesture, or null, in which case every connect (first or reconnect) reopens + * the one permitted port whose USB ids match through `getPorts()`. + */ +internal class WebSerialTransport( + private var port: dynamic, + private val usbVendorId: Int?, + private val usbProductId: Int?, + private val baudRate: Int = 115_200, +) : RadioTransport { + override val identity: TransportIdentity = + TransportIdentity("serial:${usbVendorId?.toString(16) ?: "?"}:${usbProductId?.toString(16) ?: "?"}") + private val _state = MutableStateFlow(TransportState.Disconnected) + override val state: StateFlow = _state.asStateFlow() + private val inbound = Channel(Channel.UNLIMITED) + private var scope: CoroutineScope? = null + private var reader: dynamic = null + private var writer: dynamic = null + private var closing = false + private var listening = false + + private val onOsDisconnect: (dynamic) -> Unit = { event -> + val gone = event.target ?: event.port + if (gone != null && gone === port) { + port = null + dropped("Serial device disconnected") + } + } + + private val onOsConnect: (dynamic) -> Unit = { event -> + val found = event.target ?: event.port + if (port == null && found != null && matches(found)) port = found + } + + override suspend fun connect() { + _state.value = TransportState.Connecting + closing = false + val opened: dynamic + try { + val serial = serialApi() ?: throw ClientException(UNSUPPORTED, "Web Serial is not supported in this browser") + opened = port ?: findPort(serial) ?: throw ClientException( + UNAVAILABLE, + "Serial port not available. Re-select the port.", + ) + port = opened + open(opened) + if (!listening) { + serial.addEventListener("disconnect", onOsDisconnect) + serial.addEventListener("connect", onOsConnect) + listening = true + } + } catch (e: CancellationException) { + _state.value = TransportState.Disconnected + throw e + } catch (e: Throwable) { + _state.value = TransportState.Disconnected + throw e + } + _state.value = TransportState.Connected + scope = CoroutineScope(SupervisorJob()).also { s -> s.launch { readLoop(opened) } } + } + + override suspend fun disconnect() { + closing = true + scope?.cancel() + scope = null + release() + _state.value = TransportState.Disconnected + } + + override suspend fun send(frame: Frame) { + val w = writer ?: throw ClientException("transport", "Serial port is not open") + try { + (w.write(frame.bytes.toByteArray().toUint8Array()) as Promise).await() + } catch (e: Throwable) { + dropped(e.message ?: "Serial write failed") + throw ClientException("transport", e.message ?: "Serial write failed") + } + } + + override fun frames(): Flow = inbound.receiveAsFlow() + + private fun matches(candidate: dynamic): Boolean { + if (usbVendorId == null || usbProductId == null) return false + val info = try { + candidate.getInfo() + } catch (_: Throwable) { + return false + } + return info != null && info.usbVendorId == usbVendorId && info.usbProductId == usbProductId + } + + private suspend fun findPort(serial: dynamic): dynamic { + val ports = (serial.getPorts() as Promise>).await() + val matching = ports.filter { matches(it) } + return if (matching.size == 1) matching[0] else null + } + + private suspend fun open(p: dynamic) { + if (p.readable != null || p.writable != null) { + try { + (p.close() as Promise).await() + } catch (e: Throwable) { + throw ClientException( + BUSY, + "Serial port is open and could not be released. Close any other tab, terminal, or app using it and try again.", + ) + } + delay(POST_CLOSE_DELAY_MS) + } + val options = jso() + options.baudRate = baudRate + options.bufferSize = READ_BUFFER_SIZE + var attempt = 0 + while (true) { + try { + (p.open(options) as Promise).await() + break + } catch (e: Throwable) { + val busy = isBusy(e) + if (!busy || attempt == OPEN_RETRY_DELAYS_MS.size) { + throw ClientException( + if (busy) BUSY else UNAVAILABLE, + if (busy) { + "Serial port is busy. Another tab, terminal, or app is holding it. Close it and try again." + } else { + "Could not open the serial port. Re-plug the device and try again." + }, + ) + } + delay(OPEN_RETRY_DELAYS_MS[attempt]) + attempt++ + } + } + try { + val signals = jso() + signals.dataTerminalReady = true + signals.requestToSend = true + (p.setSignals(signals) as Promise).await() + } catch (_: Throwable) { + } + writer = p.writable.getWriter() + } + + private suspend fun readLoop(p: dynamic) { + val assembler = FrameAssembler { inbound.trySend(it) } + val r = p.readable.getReader() + reader = r + try { + while (true) { + val result = (r.read() as Promise).await() + if (result.done == true) break + assembler.feed((result.value as Uint8Array).toByteArray()) + } + if (!closing) dropped("Serial port closed") + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + if (!closing) dropped(e.message ?: "Serial read failed") + } + } + + private fun dropped(reason: String) { + if (closing || _state.value !is TransportState.Connected) return + _state.value = TransportState.Error(ClientException(DISCONNECTED, reason), recoverable = true) + scope?.launch { release() } + } + + private suspend fun release() { + val p = port + try { + (reader?.cancel() as? Promise)?.await() + } catch (_: Throwable) { + } + try { + writer?.releaseLock() + } catch (_: Throwable) { + } + reader = null + writer = null + if (p != null) { + try { + (p.close() as Promise).await() + } catch (_: Throwable) { + } + } + } + + private companion object { + const val UNSUPPORTED = "serial-unsupported" + const val UNAVAILABLE = "serial-unavailable" + const val BUSY = "serial-busy" + const val DISCONNECTED = "serial-disconnected" + const val READ_BUFFER_SIZE = 64 * 1024 + const val POST_CLOSE_DELAY_MS = 200L + val OPEN_RETRY_DELAYS_MS = longArrayOf(250, 500, 750) + + fun serialApi(): dynamic { + val serial = js("globalThis.navigator ? globalThis.navigator.serial : undefined") + return if (serial == null) null else serial + } + + fun isBusy(e: Throwable): Boolean { + val name = e.asDynamic().name + if (name == "InvalidStateError") return true + val message = e.message ?: return false + return Regex("already open|failed to open serial port|access is denied", RegexOption.IGNORE_CASE) + .containsMatchIn(message) + } + } +} diff --git a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/FrameAssemblerTest.kt b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/FrameAssemblerTest.kt new file mode 100644 index 000000000..d1606a115 --- /dev/null +++ b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/FrameAssemblerTest.kt @@ -0,0 +1,51 @@ +package org.meshtastic.sdk.js + +import org.meshtastic.sdk.Frame +import kotlin.test.Test +import kotlin.test.assertEquals + +class FrameAssemblerTest { + private val frames = mutableListOf() + private val assembler = FrameAssembler { frames.add(it) } + + @Test + fun reassembles_a_frame_split_across_chunks() { + val payload = byteArrayOf(1, 2, 3, 4, 5) + val wire = framed(payload).toByteArray() + assembler.feed(wire.copyOfRange(0, 3)) + assembler.feed(wire.copyOfRange(3, 6)) + assembler.feed(wire.copyOfRange(6, wire.size)) + assertEquals(listOf(Frame(framed(payload))), frames) + } + + @Test + fun skips_garbage_and_log_text_between_frames() { + val payload = byteArrayOf(9, 8, 7) + val wire = "INFO | boot\n".encodeToByteArray() + framed(payload).toByteArray() + byteArrayOf(0x94.toByte(), 0x00) + assembler.feed(wire) + assertEquals(listOf(Frame(framed(payload))), frames) + } + + @Test + fun resyncs_after_an_oversized_length() { + val bogus = byteArrayOf(0x94.toByte(), 0xC3.toByte(), 0x7F, 0x00) + val payload = byteArrayOf(42) + assembler.feed(bogus + framed(payload).toByteArray()) + assertEquals(listOf(Frame(framed(payload))), frames) + } + + @Test + fun a_doubled_start_byte_still_frames() { + val payload = byteArrayOf(1) + assembler.feed(byteArrayOf(0x94.toByte()) + framed(payload).toByteArray()) + assertEquals(listOf(Frame(framed(payload))), frames) + } + + @Test + fun payload_round_trips_through_the_header() { + val payload = ByteArray(512) { it.toByte() } + val frame = Frame(framed(payload)) + assertEquals(516, frame.bytes.size) + assertEquals(payload.toList(), payloadOf(frame).toList()) + } +} diff --git a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebBluetoothTransportTest.kt b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebBluetoothTransportTest.kt new file mode 100644 index 000000000..ac8a04e5f --- /dev/null +++ b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebBluetoothTransportTest.kt @@ -0,0 +1,207 @@ +package org.meshtastic.sdk.js + +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.take +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.promise +import kotlinx.coroutines.withTimeout +import org.khronos.webgl.Uint8Array +import org.meshtastic.sdk.Frame +import org.meshtastic.sdk.TransportState +import kotlin.js.Promise +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertTrue + +/** + * Drives the transport with a scripted `navigator.bluetooth`. The fake device + * queues `fromradio` reads and records `toradio` writes; `requestDevice` + * counts prompts, which must stay at zero. + */ +class WebBluetoothTransportTest { + @AfterTest + fun restore() { + js("delete globalThis.navigator") + } + + private fun installBluetooth(devices: Array): dynamic { + val bluetooth = js( + """({ + requested: 0, + requestDevice: function () { this.requested++; return Promise.reject(new Error('prompted')); } + })""", + ) + bluetooth.devices = devices + bluetooth.getDevices = { Promise.resolve(bluetooth.devices) } + val navigator = js("({})") + navigator.bluetooth = bluetooth + js("Object.defineProperty(globalThis, 'navigator', { value: navigator, configurable: true, writable: true })") + return bluetooth + } + + private fun fakeDevice(id: String, hasService: Boolean = true): dynamic { + val device = js( + """({ + listeners: {}, queued: [], written: [], connects: 0, notifying: false, + addEventListener: function (type, cb) { (this.listeners[type] = this.listeners[type] || []).push(cb); }, + removeEventListener: function () {}, + dispatch: function (type) { (this.listeners[type] || []).forEach(function (cb) { cb({}); }); }, + queue: function (bytes) { this.queued.push(bytes); } + })""", + ) + device.id = id + val chars = js("({})") + chars.fromradio = js( + """({ readValue: function () { var next = device.queued.shift(); return Promise.resolve(new DataView(next ? next.buffer : new ArrayBuffer(0))); } })""", + ) + chars.toradio = js( + """({ writeValueWithResponse: function (buffer) { device.written.push(new Uint8Array(buffer)); return Promise.resolve(); } })""", + ) + chars.fromnum = js( + """({ + addEventListener: function (type, cb) { device.listeners[type] = (device.listeners[type] || []).concat([cb]); }, + removeEventListener: function () {}, + startNotifications: function () { device.notifying = true; return Promise.resolve(); }, + stopNotifications: function () { device.notifying = false; } + })""", + ) + val service = js("({})") + service.getCharacteristic = { uuid: String -> + Promise.resolve( + when (uuid) { + "f75c76d2-129e-4dad-a1dd-7866124401e7" -> chars.toradio + "2c55e69e-4993-11ed-b878-0242ac120002" -> chars.fromradio + else -> chars.fromnum + }, + ) + } + val server = js("({ connected: false })") + server.device = device + server.getPrimaryService = { _: String -> + if (hasService) Promise.resolve(service) else Promise.reject(Exception("no service")) + } + server.disconnect = { server.connected = false } + val gatt = js("({})") + gatt.connect = { + device.connects = (device.connects as Int) + 1 + server.connected = true + Promise.resolve(server) + } + device.gatt = gatt + return device + } + + @Test + fun reconnects_a_known_device_through_getDevices_without_prompting() = GlobalScope.promise { + val radio = fakeDevice("radio-1") + val bluetooth = installBluetooth(arrayOf(fakeDevice("other"), radio)) + val transport = WebBluetoothTransport(null, "radio-1") + + transport.connect() + + assertEquals(TransportState.Connected, transport.state.value) + assertEquals(1, radio.connects) + assertTrue(radio.notifying as Boolean) + assertEquals(0, bluetooth.requested) + assertEquals("ble:radio-1", transport.identity.raw) + transport.disconnect() + assertEquals(TransportState.Disconnected, transport.state.value) + } + + @Test + fun uses_the_device_a_gesture_handed_over() = GlobalScope.promise { + val radio = fakeDevice("radio-1") + val bluetooth = installBluetooth(arrayOf()) + val transport = WebBluetoothTransport(radio, null) + + transport.connect() + + assertEquals(1, radio.connects) + assertEquals(0, bluetooth.requested) + transport.disconnect() + } + + @Test + fun fails_without_prompting_when_the_device_is_not_permitted() = GlobalScope.promise { + val bluetooth = installBluetooth(arrayOf(fakeDevice("other"))) + + val failure = assertFailsWith { WebBluetoothTransport(null, "radio-1").connect() } + + assertEquals("bluetooth-unavailable", failure.kind) + assertEquals(0, bluetooth.requested) + } + + @Test + fun reports_a_missing_api_clearly() = GlobalScope.promise { + js("Object.defineProperty(globalThis, 'navigator', { value: {}, configurable: true, writable: true })") + + val failure = assertFailsWith { WebBluetoothTransport(null, "radio-1").connect() } + + assertEquals("bluetooth-unsupported", failure.kind) + } + + @Test + fun reports_a_device_without_the_meshtastic_service() = GlobalScope.promise { + installBluetooth(arrayOf(fakeDevice("radio-1", hasService = false))) + + val failure = assertFailsWith { WebBluetoothTransport(null, "radio-1").connect() } + + assertEquals("bluetooth-missing-service", failure.kind) + } + + @Test + fun drains_fromradio_on_fromnum_and_frames_each_read() = GlobalScope.promise { + val radio = fakeDevice("radio-1") + installBluetooth(arrayOf(radio)) + val transport = WebBluetoothTransport(null, "radio-1") + transport.connect() + + val first = byteArrayOf(0x08, 0x01) + val second = byteArrayOf(0x08, 0x02, 0x03) + radio.queue(first.toUint8Array()) + radio.queue(second.toUint8Array()) + radio.dispatch("characteristicvaluechanged") + + val frames = withTimeout(1_000) { transport.frames().take(2).toList() } + assertEquals(listOf(Frame(framed(first)), Frame(framed(second))), frames) + transport.disconnect() + } + + @Test + fun sends_the_payload_without_the_stream_header() = GlobalScope.promise { + val radio = fakeDevice("radio-1") + installBluetooth(arrayOf(radio)) + val transport = WebBluetoothTransport(null, "radio-1") + transport.connect() + + transport.send(Frame(framed(byteArrayOf(0x10, 0x20)))) + + assertEquals(1, radio.written.length as Int) + assertEquals(listOf(0x10, 0x20), (radio.written[0] as Uint8Array).toByteArray().toList()) + transport.disconnect() + } + + @Test + fun a_gatt_disconnect_is_a_recoverable_error_and_the_same_device_reconnects() = GlobalScope.promise { + val radio = fakeDevice("radio-1") + val bluetooth = installBluetooth(arrayOf(radio)) + val transport = WebBluetoothTransport(null, "radio-1") + transport.connect() + + radio.dispatch("gattserverdisconnected") + val error = withTimeout(1_000) { transport.state.first { it is TransportState.Error } } as TransportState.Error + assertTrue(error.recoverable) + assertEquals("bluetooth-disconnected", (error.cause as ClientException).kind) + + transport.disconnect() + transport.connect() + + assertEquals(TransportState.Connected, transport.state.value) + assertEquals(2, radio.connects) + assertEquals(0, bluetooth.requested) + transport.disconnect() + } +} diff --git a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebSerialTransportTest.kt b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebSerialTransportTest.kt new file mode 100644 index 000000000..72abd8c2f --- /dev/null +++ b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebSerialTransportTest.kt @@ -0,0 +1,189 @@ +package org.meshtastic.sdk.js + +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.promise +import kotlinx.coroutines.withTimeout +import org.meshtastic.sdk.Frame +import org.meshtastic.sdk.TransportState +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertTrue +import kotlin.js.Promise + +/** + * Drives the transport with a scripted `navigator.serial`. Ports are plain JS + * objects shaped like `SerialPort`; the fake serial API records whether + * `requestPort` was ever called. + */ +class WebSerialTransportTest { + @AfterTest + fun restore() { + js("delete globalThis.navigator") + } + + private fun installNavigator(navigator: dynamic) { + js("Object.defineProperty(globalThis, 'navigator', { value: navigator, configurable: true, writable: true })") + } + + private fun installSerial(ports: Array): dynamic { + val serial = js( + """({ + requested: 0, + listeners: {}, + addEventListener: function (type, cb) { (this.listeners[type] = this.listeners[type] || []).push(cb); }, + removeEventListener: function () {}, + dispatch: function (type, port) { (this.listeners[type] || []).forEach(function (cb) { cb({ target: port }); }); }, + requestPort: function () { this.requested++; return Promise.reject(new Error('prompted')); } + })""", + ) + serial.ports = ports + serial.getPorts = { Promise.resolve(serial.ports) } + val navigator = js("({})") + navigator.serial = serial + installNavigator(navigator) + return serial + } + + private fun fakePort(vendor: Int, product: Int): dynamic { + val port = js( + """({ + readable: null, writable: null, written: [], opens: 0, closes: 0, + open: function () { + var self = this; + self.opens++; + self.readable = new ReadableStream({ start: function (c) { self.reader = c; } }); + self.writable = new WritableStream({ write: function (chunk) { self.written.push(chunk); } }); + return Promise.resolve(); + }, + close: function () { this.closes++; this.readable = null; this.writable = null; return Promise.resolve(); }, + setSignals: function () { return Promise.resolve(); }, + push: function (bytes) { this.reader.enqueue(bytes); }, + end: function () { this.reader.close(); } + })""", + ) + val info = js("({})") + info.usbVendorId = vendor + info.usbProductId = product + port.getInfo = { info } + return port + } + + @Test + fun reopens_the_one_permitted_port_matching_the_saved_ids_without_prompting() = GlobalScope.promise { + val other = fakePort(0x10c4, 0xea60) + val radio = fakePort(0x303a, 0x1001) + val serial = installSerial(arrayOf(other, radio)) + val transport = WebSerialTransport(null, 0x303a, 0x1001) + + transport.connect() + + assertEquals(TransportState.Connected, transport.state.value) + assertEquals(1, radio.opens) + assertEquals(0, other.opens) + assertEquals(0, serial.requested) + transport.disconnect() + assertEquals(1, radio.closes) + } + + @Test + fun uses_the_port_a_gesture_handed_over() = GlobalScope.promise { + val radio = fakePort(0x303a, 0x1001) + val serial = installSerial(arrayOf()) + val transport = WebSerialTransport(radio, 0x303a, 0x1001) + + transport.connect() + + assertEquals(1, radio.opens) + assertEquals(0, serial.requested) + transport.disconnect() + } + + @Test + fun fails_without_prompting_when_no_permitted_port_matches() = GlobalScope.promise { + val serial = installSerial(arrayOf(fakePort(0x10c4, 0xea60))) + val transport = WebSerialTransport(null, 0x303a, 0x1001) + + val failure = assertFailsWith { transport.connect() } + + assertEquals("serial-unavailable", failure.kind) + assertEquals(0, serial.requested) + assertEquals(TransportState.Disconnected, transport.state.value) + } + + @Test + fun refuses_to_guess_between_ports_sharing_the_ids() = GlobalScope.promise { + installSerial(arrayOf(fakePort(0x303a, 0x1001), fakePort(0x303a, 0x1001))) + + val failure = assertFailsWith { WebSerialTransport(null, 0x303a, 0x1001).connect() } + + assertEquals("serial-unavailable", failure.kind) + } + + @Test + fun reports_a_missing_api_clearly() = GlobalScope.promise { + installNavigator(js("({})")) + + val failure = assertFailsWith { WebSerialTransport(null, 0x303a, 0x1001).connect() } + + assertEquals("serial-unsupported", failure.kind) + } + + @Test + fun frames_incoming_bytes_and_writes_outgoing_frames_raw() = GlobalScope.promise { + val radio = fakePort(0x303a, 0x1001) + installSerial(arrayOf(radio)) + val transport = WebSerialTransport(null, 0x303a, 0x1001) + transport.connect() + + val payload = byteArrayOf(0x08, 0x01) + radio.push(framed(payload).toByteArray().toUint8Array()) + val frame = withTimeout(1_000) { transport.frames().first() } + assertEquals(Frame(framed(payload)), frame) + + transport.send(Frame(framed(byteArrayOf(0x10)))) + assertEquals(1, radio.written.length as Int) + assertEquals(listOf(0x94.toByte(), 0xC3.toByte(), 0, 1, 0x10), (radio.written[0] as org.khronos.webgl.Uint8Array).toByteArray().toList()) + transport.disconnect() + } + + @Test + fun an_os_disconnect_is_a_recoverable_error_and_a_replug_reconnects() = GlobalScope.promise { + val radio = fakePort(0x303a, 0x1001) + val serial = installSerial(arrayOf(radio)) + val transport = WebSerialTransport(null, 0x303a, 0x1001) + transport.connect() + + serial.dispatch("disconnect", radio) + val error = withTimeout(1_000) { transport.state.first { it is TransportState.Error } } as TransportState.Error + assertTrue(error.recoverable) + assertEquals("serial-disconnected", (error.cause as ClientException).kind) + + transport.disconnect() + val replugged = fakePort(0x303a, 0x1001) + serial.ports = arrayOf(replugged) + serial.dispatch("connect", replugged) + transport.connect() + + assertEquals(TransportState.Connected, transport.state.value) + assertEquals(1, replugged.opens) + assertEquals(0, serial.requested) + transport.disconnect() + } + + @Test + fun a_port_left_open_is_closed_before_reopening() = GlobalScope.promise { + val radio = fakePort(0x303a, 0x1001) + radio.open() + installSerial(arrayOf(radio)) + val transport = WebSerialTransport(null, 0x303a, 0x1001) + + transport.connect() + + assertEquals(1, radio.closes) + assertEquals(2, radio.opens) + transport.disconnect() + } +} From 37796630852fa8328e590e37b9a2734be929d403 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 09:01:39 -0500 Subject: [PATCH 14/49] feat(web): connect Serial and Bluetooth through the Kotlin SDK useConnections now opens all three connection types through the facade (createHttpClient / createSerialClient / createBluetoothClient); the Kotlin SDK owns the transport, handshake and auto-reconnect, and the TS MeshDevice is fed through kmpTransport as HTTP already was. Gesture rules: automatic connects pass only the saved USB ids or Bluetooth device id and the SDK reopens via getPorts()/getDevices(); requestPort/requestDevice run only from clicks (the add-connection form and the Connect button when no permitted device matches) and the picked handle is handed to the facade. Picked ids are saved on the connection. core/connections/browserDevices.ts replaces transports.ts (no casts); AddConnectionForm passes the picked SerialPort along with the BluetoothDevice. apps/web no longer depends on transport-web-serial or transport-web-bluetooth. Tests: browserDevices helpers, useConnections over fake navigator.serial / navigator.bluetooth (no prompt on automatic paths, picker only on clicks, missing API, drop -> reconnecting), and the real Kotlin facade driven end to end over fake ports/devices with a FakeRadio that answers the handshake (connect, handed-over handle, unavailable, unsupported, unplug -> reconnecting -> replug -> connected, GATT drop -> reconnect). Those run under vitest's node environment: kotlinx-coroutines picks the window.postMessage dispatcher under happy-dom, whose MessageEvent.source never matches window, so a burst of more than 16 dispatches wedges it. --- apps/web/package.json | 2 - .../ConnectionsDrawer/AddConnectionForm.tsx | 32 +- .../ConnectionsDrawer/ConnectionsDrawer.tsx | 4 +- .../core/connections/browserDevices.test.ts | 147 ++++++ .../src/core/connections/browserDevices.ts | 155 ++++++ .../src/core/connections/transports.test.ts | 92 ---- apps/web/src/core/connections/transports.ts | 293 ----------- apps/web/src/core/kmp/bluetoothClient.test.ts | 129 +++++ apps/web/src/core/kmp/client.ts | 36 ++ apps/web/src/core/kmp/serialClient.test.ts | 130 +++++ .../useConnections.devices.test.ts | 249 +++++++++ .../pages/Connections/useConnections.test.ts | 15 +- .../src/pages/Connections/useConnections.ts | 188 ++++--- apps/web/src/tests/fakeBrowserDevices.ts | 486 ++++++++++++++++++ pnpm-lock.yaml | 6 - 15 files changed, 1483 insertions(+), 481 deletions(-) create mode 100644 apps/web/src/core/connections/browserDevices.test.ts create mode 100644 apps/web/src/core/connections/browserDevices.ts delete mode 100644 apps/web/src/core/connections/transports.test.ts delete mode 100644 apps/web/src/core/connections/transports.ts create mode 100644 apps/web/src/core/kmp/bluetoothClient.test.ts create mode 100644 apps/web/src/core/kmp/serialClient.test.ts create mode 100644 apps/web/src/pages/Connections/useConnections.devices.test.ts create mode 100644 apps/web/src/tests/fakeBrowserDevices.ts diff --git a/apps/web/package.json b/apps/web/package.json index fbcb2406b..52e059ade 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -42,8 +42,6 @@ "@meshtastic/sdk-react": "workspace:*", "@meshtastic/sdk-storage-sqlocal": "workspace:*", "@meshtastic/transport-http": "workspace:*", - "@meshtastic/transport-web-bluetooth": "workspace:*", - "@meshtastic/transport-web-serial": "workspace:*", "@noble/curves": "^2.4.0", "@preact/signals-core": "^1.14.4", "@radix-ui/react-accordion": "^1.3.1", diff --git a/apps/web/src/components/ConnectionsDrawer/AddConnectionForm.tsx b/apps/web/src/components/ConnectionsDrawer/AddConnectionForm.tsx index 3cc72911f..effc0e640 100644 --- a/apps/web/src/components/ConnectionsDrawer/AddConnectionForm.tsx +++ b/apps/web/src/components/ConnectionsDrawer/AddConnectionForm.tsx @@ -7,6 +7,10 @@ import { isLocalNetworkHost, testHttpReachable, } from "@app/pages/Connections/utils"; +import { + type ConnectionHandle, + MESHTASTIC_BLE_SERVICE, +} from "@core/connections/browserDevices.ts"; import { CertificateGuide } from "@components/CertificateGuide.tsx"; import { cn } from "@core/utils/cn.ts"; import { useLocalNetworkAccess } from "@core/hooks/useLocalNetworkAccess.ts"; @@ -25,7 +29,6 @@ import { useBrowserFeatureDetection, } from "@core/hooks/useBrowserFeatureDetection.ts"; import { useToast } from "@core/hooks/useToast.ts"; -import { TransportWebBluetooth } from "@meshtastic/transport-web-bluetooth"; import { AlertCircle, Bluetooth, @@ -66,7 +69,9 @@ type DialogState = { btSelected: | { id: string; name?: string; device?: BluetoothDevice } | undefined; - serialSelected: { vendorId?: number; productId?: number } | undefined; + serialSelected: + | { vendorId?: number; productId?: number; port?: SerialPort } + | undefined; }; type DialogAction = @@ -96,7 +101,9 @@ type DialogAction = } | { type: "SET_SERIAL_SELECTED"; - payload: { vendorId?: number; productId?: number } | undefined; + payload: + | { vendorId?: number; productId?: number; port?: SerialPort } + | undefined; } | { type: "SET_URL_AND_RESET_TEST"; payload: string }; @@ -356,7 +363,7 @@ export function AddConnectionForm({ onSave, isHTTPS = false, }: { - onSave: (conn: NewConnection, device?: BluetoothDevice) => Promise; + onSave: (conn: NewConnection, handle?: ConnectionHandle) => Promise; isHTTPS?: boolean; }) { const { toast } = useToast(); @@ -423,7 +430,7 @@ export function AddConnectionForm({ } try { const device = await navigator.bluetooth.requestDevice({ - filters: [{ services: [TransportWebBluetooth.ServiceUuid] }], + filters: [{ services: [MESHTASTIC_BLE_SERVICE] }], }); dispatch({ type: "SET_BT_SELECTED", @@ -466,6 +473,7 @@ export function AddConnectionForm({ payload: { vendorId: info.usbVendorId, productId: info.usbProductId, + port, }, }); if (!state.name || state.name === "") { @@ -696,7 +704,7 @@ export function AddConnectionForm({ name: state.name.trim(), deviceId: state.btSelected?.id, deviceName: state.btSelected?.name, - gattServiceUUID: TransportWebBluetooth.ServiceUuid, + gattServiceUUID: MESHTASTIC_BLE_SERVICE, }), }, serial: { @@ -762,7 +770,7 @@ export function AddConnectionForm({ const canCreate = useMemo(() => currentPane.validate(), [currentPane]); const submit = - (fn: (p: NewConnection, device?: BluetoothDevice) => Promise) => + (fn: (p: NewConnection, handle?: ConnectionHandle) => Promise) => async () => { if (!canCreate) { return; @@ -772,9 +780,13 @@ export function AddConnectionForm({ if (!payload) { return; } - const btDevice = - state.tab === "bluetooth" ? state.btSelected?.device : undefined; - await fn(payload, btDevice); + const handle: ConnectionHandle = { + bluetoothDevice: + state.tab === "bluetooth" ? state.btSelected?.device : undefined, + serialPort: + state.tab === "serial" ? state.serialSelected?.port : undefined, + }; + await fn(payload, handle); }; return ( diff --git a/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx b/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx index c2a02f062..06bca6c4c 100644 --- a/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx +++ b/apps/web/src/components/ConnectionsDrawer/ConnectionsDrawer.tsx @@ -166,8 +166,8 @@ function DrawerBody({ forced }: { forced: boolean }) { ) : ( { - const created = await addConnectionAndConnect(partial, btDevice); + onSave={async (partial, handle) => { + const created = await addConnectionAndConnect(partial, handle); if (!created) { toast({ title: t("toasts.failed"), diff --git a/apps/web/src/core/connections/browserDevices.test.ts b/apps/web/src/core/connections/browserDevices.test.ts new file mode 100644 index 000000000..a202c1a37 --- /dev/null +++ b/apps/web/src/core/connections/browserDevices.test.ts @@ -0,0 +1,147 @@ +import type { Connection } from "@core/stores/deviceStore/types"; +import { + FakeBluetoothDevice, + FakeSerialPort, + installBluetooth as installFakeBluetooth, + installSerial as installFakeSerial, + uninstallBrowserDevices, +} from "@app/tests/fakeBrowserDevices.ts"; +import { afterEach, describe, expect, it } from "vitest"; +import { + type BluetoothConnection, + MESHTASTIC_BLE_SERVICE, + matchesSavedPort, + permittedSerialPort, + pickBluetoothDevice, + pickSerialPort, + probeConnection, + type SerialConnection, +} from "./browserDevices.ts"; + +const ids = { usbVendorId: 0x303a, usbProductId: 0x1001 }; + +const savedSerial: SerialConnection = { + id: 1, + name: "Serial: 303a:1001", + type: "serial", + status: "disconnected", + createdAt: 0, + ...ids, +}; + +const savedBluetooth: BluetoothConnection = { + id: 2, + name: "Radio", + type: "bluetooth", + status: "disconnected", + createdAt: 0, + deviceId: "radio-1", +}; + +function fakePort(info: SerialPortInfo): SerialPort { + return new FakeSerialPort(info); +} + +function installSerial(ports: SerialPort[]) { + const serial = installFakeSerial(ports); + const [first] = ports; + if (first) serial.requestPort.mockResolvedValue(first); + return serial; +} + +function installBluetooth(ids: string[]) { + const devices = ids.map((id) => new FakeBluetoothDevice(id)); + const bluetooth = installFakeBluetooth(devices); + const [first] = devices; + if (first) bluetooth.requestDevice.mockResolvedValue(first); + return bluetooth; +} + +afterEach(() => { + uninstallBrowserDevices(); +}); + +describe("permittedSerialPort", () => { + it("picks the only permitted port with the saved USB ids", async () => { + const other = fakePort({ usbVendorId: 0x10c4, usbProductId: 0xea60 }); + const radio = fakePort(ids); + installSerial([other, radio]); + + expect(matchesSavedPort(radio, savedSerial)).toBe(true); + expect(matchesSavedPort(other, savedSerial)).toBe(false); + await expect(permittedSerialPort(savedSerial)).resolves.toBe(radio); + }); + + it("refuses to guess between permitted ports sharing the ids", async () => { + installSerial([fakePort(ids), fakePort(ids)]); + await expect(permittedSerialPort(savedSerial)).resolves.toBeUndefined(); + }); + + it("matches nothing when the connection has no saved ids", async () => { + installSerial([fakePort(ids)]); + const unsaved: SerialConnection = { + ...savedSerial, + usbVendorId: undefined, + }; + await expect(permittedSerialPort(unsaved)).resolves.toBeUndefined(); + }); + + it("is undefined without Web Serial", async () => { + await expect(permittedSerialPort(savedSerial)).resolves.toBeUndefined(); + }); +}); + +describe("pickers", () => { + it("filters the port picker to the saved USB ids", async () => { + const { requestPort } = installSerial([fakePort(ids)]); + await pickSerialPort(savedSerial); + expect(requestPort).toHaveBeenCalledWith({ filters: [ids] }); + }); + + it("filters the device picker to the Meshtastic service", async () => { + const { requestDevice } = installBluetooth(["radio-1"]); + await pickBluetoothDevice(); + expect(requestDevice).toHaveBeenCalledWith({ + filters: [{ services: [MESHTASTIC_BLE_SERVICE] }], + }); + }); + + it("names the missing API", async () => { + await expect(pickSerialPort(savedSerial)).rejects.toMatchObject({ + name: "serial-unsupported", + message: "Web Serial is not supported in this browser", + }); + await expect(pickBluetoothDevice()).rejects.toMatchObject({ + name: "bluetooth-unsupported", + }); + }); +}); + +describe("probeConnection", () => { + it("reports a permitted serial port as online", async () => { + installSerial([fakePort(ids)]); + await expect(probeConnection(savedSerial)).resolves.toEqual({ + status: "online", + }); + }); + + it("reports a known Bluetooth device as online and an unknown one as disconnected", async () => { + installBluetooth(["radio-1"]); + await expect(probeConnection(savedBluetooth)).resolves.toEqual({ + status: "online", + }); + const other: Connection = { ...savedBluetooth, deviceId: "radio-2" }; + await expect(probeConnection(other)).resolves.toEqual({ + status: "disconnected", + }); + }); + + it("is disconnected without the APIs", async () => { + await expect(probeConnection(savedSerial)).resolves.toEqual({ + status: "disconnected", + }); + await expect(probeConnection(savedBluetooth)).resolves.toEqual({ + status: "disconnected", + }); + }); +}); diff --git a/apps/web/src/core/connections/browserDevices.ts b/apps/web/src/core/connections/browserDevices.ts new file mode 100644 index 000000000..614ab871c --- /dev/null +++ b/apps/web/src/core/connections/browserDevices.ts @@ -0,0 +1,155 @@ +import type { Connection } from "@core/stores/deviceStore/types"; +import { httpErrorMessage, testHttpReachable } from "@pages/Connections/utils"; + +/** The Meshtastic GATT service, the only filter the Bluetooth picker uses. */ +export const MESHTASTIC_BLE_SERVICE = "6ba1b218-15a8-461f-9fa8-5dcae273eafd"; + +export type SerialConnection = Connection & { type: "serial" }; +export type BluetoothConnection = Connection & { type: "bluetooth" }; + +/** + * A port or device the user picked inside a click handler. The Kotlin SDK + * never prompts, so these are the only way a new device reaches it. + */ +export interface ConnectionHandle { + serialPort?: SerialPort; + bluetoothDevice?: BluetoothDevice; +} + +export function serialApi(): Serial | undefined { + return "serial" in navigator ? navigator.serial : undefined; +} + +export function bluetoothApi(): Bluetooth | undefined { + return "bluetooth" in navigator ? navigator.bluetooth : undefined; +} + +export function matchesSavedPort( + port: SerialPort, + conn: Pick, +): boolean { + if (conn.usbVendorId === undefined || conn.usbProductId === undefined) { + return false; + } + const info = port.getInfo(); + return ( + info.usbVendorId === conn.usbVendorId && + info.usbProductId === conn.usbProductId + ); +} + +/** + * The one already-permitted port with the saved USB ids, without prompting. + * Several permitted ports sharing the ids are ambiguous, so none is chosen. + */ +export async function permittedSerialPort( + conn: SerialConnection, +): Promise { + const serial = serialApi(); + if (!serial) { + return undefined; + } + const matching = (await serial.getPorts()).filter((port) => + matchesSavedPort(port, conn), + ); + return matching.length === 1 ? matching[0] : undefined; +} + +/** The port picker, filtered to the saved USB ids. Call inside a click handler. */ +export function pickSerialPort( + conn: Pick, +): Promise { + const serial = serialApi(); + if (!serial) { + return Promise.reject(unsupported("serial")); + } + const filters = + conn.usbVendorId !== undefined && conn.usbProductId !== undefined + ? [{ usbVendorId: conn.usbVendorId, usbProductId: conn.usbProductId }] + : []; + return serial.requestPort({ filters }); +} + +/** The already-permitted device with the saved id, without prompting. */ +export async function knownBluetoothDevice( + conn: BluetoothConnection, +): Promise { + const bluetooth = bluetoothApi(); + if ( + !bluetooth || + !conn.deviceId || + typeof bluetooth.getDevices !== "function" + ) { + return undefined; + } + const known = await bluetooth.getDevices(); + return known.find((device) => device.id === conn.deviceId); +} + +/** The device picker, filtered to Meshtastic radios. Call inside a click handler. */ +export function pickBluetoothDevice(): Promise { + const bluetooth = bluetoothApi(); + if (!bluetooth) { + return Promise.reject(unsupported("bluetooth")); + } + return bluetooth.requestDevice({ + filters: [{ services: [MESHTASTIC_BLE_SERVICE] }], + }); +} + +function unsupported(kind: "serial" | "bluetooth"): Error { + const error = new Error( + kind === "serial" + ? "Web Serial is not supported in this browser" + : "Web Bluetooth is not supported in this browser", + ); + error.name = `${kind}-unsupported`; + return error; +} + +export type ProbeResult = { + status: "online" | "configured" | "disconnected" | "error"; + error?: string; + errorKind?: Connection["errorKind"]; +}; + +/** + * Probes a saved connection for reachability or permission without opening + * it, for the saved-connection status badges. + */ +export async function probeConnection(conn: Connection): Promise { + switch (conn.type) { + case "http": { + const { reachable, certError } = await testHttpReachable(conn.url); + if (reachable) { + return { status: "online" }; + } + return { + status: "error", + error: httpErrorMessage(conn.url, certError), + errorKind: certError ? "cert" : "network", + }; + } + case "bluetooth": { + try { + const known = await knownBluetoothDevice(conn); + return { status: known ? "online" : "disconnected" }; + } catch { + return { status: "disconnected" }; + } + } + case "serial": { + const serial = serialApi(); + if (!serial) { + return { status: "disconnected" }; + } + try { + const ports = await serial.getPorts(); + const permitted = ports.some((port) => matchesSavedPort(port, conn)); + return { status: permitted ? "online" : "disconnected" }; + } catch { + return { status: "disconnected" }; + } + } + } +} diff --git a/apps/web/src/core/connections/transports.test.ts b/apps/web/src/core/connections/transports.test.ts deleted file mode 100644 index 3f140ac9a..000000000 --- a/apps/web/src/core/connections/transports.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import type { Connection } from "@core/stores/deviceStore/types"; -import { TransportWebSerial } from "@meshtastic/transport-web-serial"; -import { Result } from "better-result"; -import { beforeEach, describe, expect, it, vi } from "vitest"; -import { openTransport } from "./transports.ts"; - -vi.mock("@meshtastic/transport-web-serial", () => ({ - SerialConnectError: class SerialConnectError extends Error {}, - TransportWebSerial: { createFromPort: vi.fn() }, -})); - -describe("openTransport serial selection", () => { - const info = { usbVendorId: 0x303a, usbProductId: 0x1001 }; - const portA = { getInfo: () => info } as SerialPort; - const portB = { getInfo: () => info } as SerialPort; - const selectedPort = { getInfo: () => info } as SerialPort; - const getPorts = vi.fn(); - const requestPort = vi.fn(); - const savedSerial: Connection = { - id: 1, - name: "Serial: 303a:1001", - type: "serial", - status: "disconnected", - createdAt: 0, - usbVendorId: info.usbVendorId, - usbProductId: info.usbProductId, - }; - const savedFilter = { - filters: [ - { - usbVendorId: info.usbVendorId, - usbProductId: info.usbProductId, - }, - ], - }; - - beforeEach(() => { - vi.clearAllMocks(); - getPorts.mockResolvedValue([portA, portB]); - requestPort.mockResolvedValue(selectedPort); - Object.defineProperty(navigator, "serial", { - configurable: true, - value: { getPorts, requestPort }, - }); - vi.mocked(TransportWebSerial.createFromPort).mockResolvedValue( - Result.ok({} as never), - ); - }); - - it("prompts when multiple permitted ports share the saved VID/PID", async () => { - await openTransport(savedSerial, { allowPrompt: true }); - - expect(requestPort).toHaveBeenCalledOnce(); - expect(requestPort).toHaveBeenCalledWith(savedFilter); - expect(TransportWebSerial.createFromPort).toHaveBeenCalledWith( - selectedPort, - ); - }); - - it("uses the only permitted port matching the saved VID/PID without prompting", async () => { - const otherPort = { - getInfo: () => ({ usbVendorId: 0x10c4, usbProductId: 0xea60 }), - } as SerialPort; - getPorts.mockResolvedValue([otherPort, portA]); - - await openTransport(savedSerial, { allowPrompt: true }); - - expect(requestPort).not.toHaveBeenCalled(); - expect(TransportWebSerial.createFromPort).toHaveBeenCalledWith(portA); - }); - - it("refuses to guess between ports sharing the saved VID/PID when prompting is not allowed", async () => { - await expect( - openTransport(savedSerial, { allowPrompt: false }), - ).rejects.toThrow("Serial port not available"); - - expect(requestPort).not.toHaveBeenCalled(); - expect(TransportWebSerial.createFromPort).not.toHaveBeenCalled(); - }); - - it("filters the picker to the saved VID/PID when no permitted port matches", async () => { - getPorts.mockResolvedValue([]); - - await openTransport(savedSerial, { allowPrompt: true }); - - expect(requestPort).toHaveBeenCalledOnce(); - expect(requestPort).toHaveBeenCalledWith(savedFilter); - expect(TransportWebSerial.createFromPort).toHaveBeenCalledWith( - selectedPort, - ); - }); -}); diff --git a/apps/web/src/core/connections/transports.ts b/apps/web/src/core/connections/transports.ts deleted file mode 100644 index e837180d4..000000000 --- a/apps/web/src/core/connections/transports.ts +++ /dev/null @@ -1,293 +0,0 @@ -import type { Connection } from "@core/stores/deviceStore/types"; -import { httpErrorMessage, testHttpReachable } from "@pages/Connections/utils"; -import { createLogger } from "@core/log.ts"; -import type { Transport } from "@meshtastic/sdk"; -import { - BluetoothConnectError, - TransportWebBluetooth, -} from "@meshtastic/transport-web-bluetooth"; -import { - SerialConnectError, - TransportWebSerial, -} from "@meshtastic/transport-web-serial"; -import { Result } from "better-result"; - -const log = createLogger("transports"); - -/** - * Per-transport-type factories. Each resolves a Transport from a saved - * Connection record + an optional cached BluetoothDevice/SerialPort the - * caller has held onto across reconnects. - */ - -export interface OpenTransportOptions { - /** Whether the user explicitly initiated this connection (allows BT/Serial pickers). */ - allowPrompt?: boolean; - /** Cached BT device from a prior connect, if any. */ - cachedBluetoothDevice?: BluetoothDevice; - /** Cached serial port from a prior connect, if any. */ - cachedSerialPort?: SerialPort; -} - -/** HTTP connections are opened by the Kotlin SDK (see `core/kmp`). */ -export type BrowserConnection = Exclude; - -export interface OpenTransportResult { - transport: Transport; - /** BT device (when type=bluetooth) so caller can cache for cleanup + reconnect. */ - bluetoothDevice?: BluetoothDevice; - /** Serial port (when type=serial) so caller can cache for cleanup + reconnect. */ - serialPort?: SerialPort; -} - -export async function openTransport( - conn: BrowserConnection, - opts: OpenTransportOptions = {}, -): Promise { - switch (conn.type) { - case "bluetooth": - return openBluetooth(conn, opts); - case "serial": - return openSerial(conn, opts); - default: { - const _exhaustive: never = conn; - void _exhaustive; - throw new Error( - `Unknown transport type: ${(conn as { type?: string }).type}`, - ); - } - } -} - -async function openBluetooth( - conn: Connection & { - type: "bluetooth"; - deviceId?: string; - gattServiceUUID?: string; - }, - opts: OpenTransportOptions, -): Promise { - if (!("bluetooth" in navigator)) { - throw new Error("Web Bluetooth not supported"); - } - - let device = opts.cachedBluetoothDevice; - if (!device) { - const bt = navigator.bluetooth as Navigator["bluetooth"] & { - getDevices?: () => Promise; - }; - if (bt.getDevices) { - const known = await bt.getDevices(); - if (known.length > 0 && conn.deviceId) { - device = known.find((d) => d.id === conn.deviceId); - } - } - } - if (!device && opts.allowPrompt) { - device = await navigator.bluetooth.requestDevice({ - acceptAllDevices: !conn.gattServiceUUID, - optionalServices: conn.gattServiceUUID - ? [conn.gattServiceUUID] - : undefined, - filters: conn.gattServiceUUID - ? [{ services: [conn.gattServiceUUID] }] - : undefined, - }); - } - if (!device) { - throw new Error("Bluetooth device not available. Re-select the device."); - } - - // Connect-failure semantics (transient retries, user-friendly messages) - // live inside the transport package — see BluetoothConnectError. This - // layer just surfaces whatever the transport produces. - const transport = await TransportWebBluetooth.createFromDevice(device); - return { transport, bluetoothDevice: device }; -} - -// Re-export so the Connections UI can `instanceof`-check for transient -// vs fatal failures without depending on the transport packages directly. -export { BluetoothConnectError, SerialConnectError }; - -async function openSerial( - conn: Connection & { - type: "serial"; - usbVendorId?: number; - usbProductId?: number; - }, - opts: OpenTransportOptions, -): Promise { - log.debug("openSerial: enter", { - hasCached: !!opts.cachedSerialPort, - allowPrompt: !!opts.allowPrompt, - vid: conn.usbVendorId, - pid: conn.usbProductId, - }); - if (!("serial" in navigator)) { - throw new Error("Web Serial not supported"); - } - - const serial = ( - navigator as Navigator & { - serial: { - getPorts: () => Promise; - requestPort: (options: Record) => Promise; - }; - } - ).serial; - const requestPortOptions = - conn.usbVendorId !== undefined && conn.usbProductId !== undefined - ? { - filters: [ - { - usbVendorId: conn.usbVendorId, - usbProductId: conn.usbProductId, - }, - ], - } - : {}; - - let port = opts.cachedSerialPort; - if (!port) { - const ports = await serial.getPorts(); - log.debug("openSerial: getPorts", { count: ports.length }); - if (ports && conn.usbVendorId && conn.usbProductId) { - const matchingPorts = ports.filter((p: SerialPort) => { - const info = - ( - p as SerialPort & { - getInfo?: () => { usbVendorId?: number; usbProductId?: number }; - } - ).getInfo?.() ?? {}; - return ( - info.usbVendorId === conn.usbVendorId && - info.usbProductId === conn.usbProductId - ); - }); - if (matchingPorts.length === 1) { - port = matchingPorts[0]; - } else if (matchingPorts.length > 1) { - log.info( - "openSerial: multiple permitted ports share VID/PID; user selection required", - { count: matchingPorts.length }, - ); - if (opts.allowPrompt) { - port = await serial.requestPort(requestPortOptions); - } - } - } - } - if (!port && opts.allowPrompt) { - log.debug("openSerial: requesting port via picker"); - port = await serial.requestPort(requestPortOptions); - } - if (!port) { - log.warn("openSerial: no port resolved"); - throw new Error("Serial port not available. Re-select the port."); - } - - log.debug("openSerial: resolved port", { - readable: !!(port as SerialPort).readable, - writable: !!(port as SerialPort).writable, - }); - - // Port-state hygiene (force-close + retry open + busy detection) lives - // inside the transport package — see SerialConnectError. We just unwrap - // the Result and surface the user-facing message on failure. - const result = await TransportWebSerial.createFromPort(port); - if (Result.isError(result)) { - log.error("openSerial: createFromPort returned Err", { - kind: result.error.kind, - userMessage: result.error.userMessage, - }); - throw result.error; - } - log.info("openSerial: transport ready"); - return { transport: result.value, serialPort: port }; -} - -export type ProbeResult = { - status: "online" | "configured" | "disconnected" | "error"; - error?: string; - errorKind?: Connection["errorKind"]; -}; - -/** - * Probes a saved connection for reachability/permission without opening it. - * Used by refreshStatuses to update the saved-connection status badges. - */ -export async function probeConnection(conn: Connection): Promise { - switch (conn.type) { - case "http": { - const { reachable, certError } = await testHttpReachable(conn.url); - if (reachable) return { status: "online" }; - return { - status: "error", - error: httpErrorMessage(conn.url, certError), - errorKind: certError ? "cert" : "network", - }; - } - case "bluetooth": { - if (!("bluetooth" in navigator)) return { status: "disconnected" }; - try { - const known = await ( - navigator.bluetooth as Navigator["bluetooth"] & { - getDevices?: () => Promise; - } - ).getDevices?.(); - const hasPermission = known?.some( - (d: BluetoothDevice) => d.id === conn.deviceId, - ); - return { status: hasPermission ? "online" : "disconnected" }; - } catch { - return { status: "disconnected" }; - } - } - case "serial": { - if (!("serial" in navigator)) return { status: "disconnected" }; - try { - const ports: SerialPort[] = await ( - navigator as Navigator & { - serial: { getPorts: () => Promise }; - } - ).serial.getPorts(); - const hasPermission = ports.some((p: SerialPort) => { - const info = - ( - p as SerialPort & { - getInfo?: () => { usbVendorId?: number; usbProductId?: number }; - } - ).getInfo?.() ?? {}; - return ( - info.usbVendorId === conn.usbVendorId && - info.usbProductId === conn.usbProductId - ); - }); - return { status: hasPermission ? "online" : "disconnected" }; - } catch { - return { status: "disconnected" }; - } - } - } -} - -/** - * Best-effort cleanup for a held-onto BT device or serial port. Safe on either. - */ -export function closeTransport( - handle: BluetoothDevice | SerialPort | undefined, -): void { - if (!handle) return; - const bt = handle as BluetoothDevice; - if (bt.gatt?.connected) { - try { - bt.gatt.disconnect(); - } catch {} - } - const port = handle as SerialPort & { close?: () => Promise }; - if (port.close) { - try { - port.close(); - } catch {} - } -} diff --git a/apps/web/src/core/kmp/bluetoothClient.test.ts b/apps/web/src/core/kmp/bluetoothClient.test.ts new file mode 100644 index 000000000..9b346c128 --- /dev/null +++ b/apps/web/src/core/kmp/bluetoothClient.test.ts @@ -0,0 +1,129 @@ +// @vitest-environment node +import { + FakeBluetoothDevice, + FakeRadio, + installBluetooth, + uninstallBrowserDevices, +} from "@app/tests/fakeBrowserDevices.ts"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { createBluetoothClient, type MeshtasticClient } from "./client.ts"; + +async function connected(client: MeshtasticClient): Promise { + await vi.waitFor( + () => expect(client.connectionState.kind).toBe("connected"), + { timeout: 8_000, interval: 25 }, + ); +} + +describe("createBluetoothClient (Kotlin facade over a fake navigator.bluetooth)", () => { + const clients: MeshtasticClient[] = []; + + afterEach(async () => { + await Promise.all(clients.splice(0).map((client) => client.disconnect())); + uninstallBrowserDevices(); + }); + + it("finds the saved device through getDevices, completes the handshake and never prompts", async () => { + const radio = new FakeRadio(); + const device = new FakeBluetoothDevice("radio-1", "Meshtastic_abcd", radio); + const bluetooth = installBluetooth([ + new FakeBluetoothDevice("other"), + device, + ]); + const client = await createBluetoothClient({ deviceId: "radio-1" }); + clients.push(client); + + await client.connect(); + await connected(client); + + expect(bluetooth.requestDevice).not.toHaveBeenCalled(); + expect(device.connects).toBe(1); + expect(device.notifying).toBe(true); + expect(client.myNodeNum).toBe(radio.myNodeNum); + expect( + device.written.every((bytes) => bytes[0] !== 0x94 || bytes.length !== 4), + ).toBe(true); + }, 10_000); + + it("uses the device a click handed over", async () => { + const device = new FakeBluetoothDevice( + "radio-1", + undefined, + new FakeRadio(), + ); + const bluetooth = installBluetooth([]); + const client = await createBluetoothClient({ device }); + clients.push(client); + + await client.connect(); + await connected(client); + + expect(bluetooth.requestDevice).not.toHaveBeenCalled(); + }, 10_000); + + it("fails with a clear kind when the device is not permitted, without prompting", async () => { + const bluetooth = installBluetooth([new FakeBluetoothDevice("other")]); + const client = await createBluetoothClient({ deviceId: "radio-1" }); + clients.push(client); + + await expect(client.connect()).rejects.toMatchObject({ + name: "bluetooth-unavailable", + }); + expect(bluetooth.requestDevice).not.toHaveBeenCalled(); + }); + + it("fails with a clear kind when Web Bluetooth is missing", async () => { + const client = await createBluetoothClient({ deviceId: "radio-1" }); + clients.push(client); + + await expect(client.connect()).rejects.toMatchObject({ + name: "bluetooth-unsupported", + message: "Web Bluetooth is not supported in this browser", + }); + }); + + it("names a device without the Meshtastic service", async () => { + const device = new FakeBluetoothDevice( + "radio-1", + undefined, + undefined, + false, + ); + installBluetooth([device]); + const client = await createBluetoothClient({ deviceId: "radio-1" }); + clients.push(client); + + await expect(client.connect()).rejects.toMatchObject({ + name: "bluetooth-missing-service", + }); + }); + + it("reconnects through the SDK after the GATT link drops", async () => { + const device = new FakeBluetoothDevice( + "radio-1", + undefined, + new FakeRadio(), + ); + const bluetooth = installBluetooth([device]); + const client = await createBluetoothClient({ deviceId: "radio-1" }); + clients.push(client); + await client.connect(); + await connected(client); + + device.dropLink(); + + await vi.waitFor( + () => expect(client.connectionState.kind).toBe("reconnecting"), + { timeout: 2_000, interval: 10 }, + ); + expect(client.connectionState).toMatchObject({ + attempt: 1, + maxAttempts: 10, + errorKind: "bluetooth-disconnected", + }); + + await connected(client); + expect(device.connects).toBe(2); + expect(bluetooth.requestDevice).not.toHaveBeenCalled(); + }, 15_000); +}); diff --git a/apps/web/src/core/kmp/client.ts b/apps/web/src/core/kmp/client.ts index 9c8eed5f5..5ab86d267 100644 --- a/apps/web/src/core/kmp/client.ts +++ b/apps/web/src/core/kmp/client.ts @@ -25,3 +25,39 @@ export async function createHttpClient( const kmp = await loadKmp(); return kmp.createHttpClient(url, allowPrompt, MAX_RECONNECT_ATTEMPTS); } + +export interface SerialTarget { + /** A port picked inside a click handler; otherwise the SDK reopens by USB ids. */ + port?: SerialPort; + usbVendorId?: number; + usbProductId?: number; +} + +export interface BluetoothTarget { + /** A device picked inside a click handler; otherwise the SDK looks `deviceId` up. */ + device?: BluetoothDevice; + deviceId?: string; +} + +export async function createSerialClient( + target: SerialTarget, +): Promise { + const kmp = await loadKmp(); + return kmp.createSerialClient( + target.port, + target.usbVendorId, + target.usbProductId, + MAX_RECONNECT_ATTEMPTS, + ); +} + +export async function createBluetoothClient( + target: BluetoothTarget, +): Promise { + const kmp = await loadKmp(); + return kmp.createBluetoothClient( + target.device, + target.deviceId, + MAX_RECONNECT_ATTEMPTS, + ); +} diff --git a/apps/web/src/core/kmp/serialClient.test.ts b/apps/web/src/core/kmp/serialClient.test.ts new file mode 100644 index 000000000..4f027670c --- /dev/null +++ b/apps/web/src/core/kmp/serialClient.test.ts @@ -0,0 +1,130 @@ +// @vitest-environment node +import type { ConnectionStateJs } from "@meshtastic/sdk-kmp"; +import { + FakeRadio, + FakeSerialPort, + installSerial, + uninstallBrowserDevices, +} from "@app/tests/fakeBrowserDevices.ts"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { createSerialClient, type MeshtasticClient } from "./client.ts"; + +const ids = { usbVendorId: 0x303a, usbProductId: 0x1001 }; + +async function connected(client: MeshtasticClient): Promise { + await vi.waitFor( + () => expect(client.connectionState.kind).toBe("connected"), + { timeout: 8_000, interval: 25 }, + ); +} + +describe("createSerialClient (Kotlin facade over a fake navigator.serial)", () => { + const clients: MeshtasticClient[] = []; + + afterEach(async () => { + await Promise.all(clients.splice(0).map((client) => client.disconnect())); + uninstallBrowserDevices(); + }); + + it("reopens the permitted port by USB ids, completes the handshake and never prompts", async () => { + const radio = new FakeRadio(); + const port = new FakeSerialPort(ids, radio); + const serial = installSerial([ + new FakeSerialPort({ usbVendorId: 0x10c4, usbProductId: 0xea60 }), + port, + ]); + const client = await createSerialClient(ids); + clients.push(client); + const states: ConnectionStateJs[] = []; + client.onConnectionState((state) => states.push(state)); + const frames: Uint8Array[] = []; + client.onFromRadio((bytes) => frames.push(bytes)); + + await client.connect(); + await connected(client); + + expect(serial.requestPort).not.toHaveBeenCalled(); + expect(port.opens).toBe(1); + expect(client.myNodeNum).toBe(radio.myNodeNum); + expect( + radio.received.filter((m) => m.payloadVariant.case === "wantConfigId"), + ).toHaveLength(2); + expect(frames.length).toBeGreaterThanOrEqual(2); + expect(states.map((s) => s.kind)).toContain("configuring"); + expect(port.written[0]).toEqual(Uint8Array.of(0x94, 0x94, 0x94, 0x94)); + }, 10_000); + + it("uses the port a click handed over", async () => { + const port = new FakeSerialPort(ids, new FakeRadio()); + const serial = installSerial([]); + const client = await createSerialClient({ port, ...ids }); + clients.push(client); + + await client.connect(); + await connected(client); + + expect(serial.requestPort).not.toHaveBeenCalled(); + expect(port.opens).toBe(1); + }, 10_000); + + it("fails with a clear kind when no permitted port matches, without prompting", async () => { + const serial = installSerial([ + new FakeSerialPort({ usbVendorId: 0x10c4, usbProductId: 0xea60 }), + ]); + const client = await createSerialClient(ids); + clients.push(client); + + await expect(client.connect()).rejects.toMatchObject({ + name: "serial-unavailable", + message: "Serial port not available. Re-select the port.", + }); + expect(serial.requestPort).not.toHaveBeenCalled(); + expect(client.connectionState.kind).toBe("disconnected"); + }); + + it("fails with a clear kind when Web Serial is missing", async () => { + const client = await createSerialClient(ids); + clients.push(client); + + await expect(client.connect()).rejects.toMatchObject({ + name: "serial-unsupported", + message: "Web Serial is not supported in this browser", + }); + }); + + it("reconnects through the SDK after an unplug, and reopens the replugged port", async () => { + const radio = new FakeRadio(); + const port = new FakeSerialPort(ids, radio); + const serial = installSerial([port]); + const client = await createSerialClient(ids); + clients.push(client); + const states: ConnectionStateJs[] = []; + client.onConnectionState((state) => states.push(state)); + await client.connect(); + await connected(client); + + port.unplug(); + serial.dispatch("disconnect", port); + + await vi.waitFor( + () => expect(client.connectionState.kind).toBe("reconnecting"), + { timeout: 2_000, interval: 10 }, + ); + expect(client.connectionState).toMatchObject({ + attempt: 1, + maxAttempts: 10, + errorKind: "serial-disconnected", + }); + + const replugged = new FakeSerialPort(ids, radio); + serial.ports = [replugged]; + serial.dispatch("connect", replugged); + + await connected(client); + expect(replugged.opens).toBe(1); + expect(serial.requestPort).not.toHaveBeenCalled(); + expect(states.map((s) => s.kind)).toEqual( + expect.arrayContaining(["connected", "reconnecting", "connected"]), + ); + }, 15_000); +}); diff --git a/apps/web/src/pages/Connections/useConnections.devices.test.ts b/apps/web/src/pages/Connections/useConnections.devices.test.ts new file mode 100644 index 000000000..0ea77cc2a --- /dev/null +++ b/apps/web/src/pages/Connections/useConnections.devices.test.ts @@ -0,0 +1,249 @@ +import { FakeKmpClient, state } from "@core/kmp/fakeClient.ts"; +import type { BluetoothTarget, SerialTarget } from "@core/kmp/client.ts"; +import type { Connection } from "@app/core/stores/deviceStore/types"; +import { useDeviceStore } from "@core/stores"; +import { + FakeBluetoothDevice, + FakeSerialPort, + installBluetooth as installFakeBluetooth, + installSerial as installFakeSerial, + uninstallBrowserDevices, +} from "@app/tests/fakeBrowserDevices.ts"; +import { act, renderHook } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { useConnections } from "./useConnections.ts"; + +const kmp = vi.hoisted( + (): { + client?: FakeKmpClient; + serialTargets: SerialTarget[]; + bluetoothTargets: BluetoothTarget[]; + } => ({ serialTargets: [], bluetoothTargets: [] }), +); + +vi.mock("@core/sdkStorage.ts", () => ({ + getStorageDb: async () => { + throw new Error("no storage in tests"); + }, + coordinator: undefined, +})); + +vi.mock("@core/kmp/client.ts", async () => { + const { FakeKmpClient } = await import("@core/kmp/fakeClient.ts"); + return { + createSerialClient: async (target: SerialTarget) => { + kmp.serialTargets.push(target); + kmp.client = new FakeKmpClient(); + return kmp.client; + }, + createBluetoothClient: async (target: BluetoothTarget) => { + kmp.bluetoothTargets.push(target); + kmp.client = new FakeKmpClient(); + return kmp.client; + }, + }; +}); + +const ids = { usbVendorId: 0x303a, usbProductId: 0x1001 }; + +const saved = (id: number): Connection | undefined => + useDeviceStore.getState().savedConnections.find((c) => c.id === id); + +function fakePort(info: SerialPortInfo): SerialPort { + return new FakeSerialPort(info); +} + +function installSerial(ports: SerialPort[], picked?: SerialPort) { + const serial = installFakeSerial(ports); + if (picked) serial.requestPort.mockResolvedValue(picked); + return serial.requestPort; +} + +function installBluetooth( + devices: FakeBluetoothDevice[], + picked?: FakeBluetoothDevice, +) { + const bluetooth = installFakeBluetooth(devices); + if (picked) bluetooth.requestDevice.mockResolvedValue(picked); + return bluetooth.requestDevice; +} + +describe("useConnections over the Kotlin SDK (Serial and Bluetooth)", () => { + beforeEach(() => { + kmp.client = undefined; + kmp.serialTargets.length = 0; + kmp.bluetoothTargets.length = 0; + }); + + afterEach(() => { + uninstallBrowserDevices(); + }); + + it("reopens a saved serial connection through the SDK without prompting", async () => { + const requestPort = installSerial([fakePort(ids)]); + const { result } = renderHook(() => useConnections()); + const conn = result.current.addConnection({ + type: "serial", + name: "Serial", + ...ids, + }); + + const ok = await act(() => result.current.connect(conn.id)); + + expect(ok).toBe(true); + expect(requestPort).not.toHaveBeenCalled(); + expect(kmp.serialTargets).toEqual([{ port: undefined, ...ids }]); + expect(saved(conn.id)?.status).toBe("configuring"); + await act(() => result.current.disconnect(conn.id)); + }); + + it("hands a click's permitted port to the SDK without prompting", async () => { + const radio = fakePort(ids); + const requestPort = installSerial([radio]); + const { result } = renderHook(() => useConnections()); + const conn = result.current.addConnection({ + type: "serial", + name: "Serial", + ...ids, + }); + + await act(() => result.current.connect(conn.id, { allowPrompt: true })); + + expect(requestPort).not.toHaveBeenCalled(); + expect(kmp.serialTargets).toEqual([{ port: radio, ...ids }]); + await act(() => result.current.disconnect(conn.id)); + }); + + it("shows the port picker on a click only when no permitted port matches, and saves the picked ids", async () => { + const newIds = { usbVendorId: 0x10c4, usbProductId: 0xea60 }; + const picked = fakePort(newIds); + const requestPort = installSerial([], picked); + const { result } = renderHook(() => useConnections()); + const conn = result.current.addConnection({ + type: "serial", + name: "Serial", + ...ids, + }); + + await act(() => result.current.connect(conn.id, { allowPrompt: true })); + + expect(requestPort).toHaveBeenCalledWith({ filters: [ids] }); + expect(kmp.serialTargets).toEqual([{ port: picked, ...newIds }]); + expect(saved(conn.id)).toMatchObject(newIds); + + await act(() => result.current.disconnect(conn.id)); + await act(() => result.current.connect(conn.id)); + expect(requestPort).toHaveBeenCalledTimes(1); + expect(kmp.serialTargets[1]).toEqual({ port: picked, ...newIds }); + }); + + it("reports a missing Web Serial API instead of prompting", async () => { + const { result } = renderHook(() => useConnections()); + const conn = result.current.addConnection({ + type: "serial", + name: "Serial", + ...ids, + }); + + const ok = await act(() => + result.current.connect(conn.id, { allowPrompt: true }), + ); + + expect(ok).toBe(false); + expect(saved(conn.id)).toMatchObject({ + status: "error", + error: "Web Serial is not supported in this browser", + }); + expect(kmp.serialTargets).toEqual([]); + }); + + it("reopens a saved Bluetooth connection by device id without prompting", async () => { + const requestDevice = installBluetooth([ + new FakeBluetoothDevice("radio-1"), + ]); + const { result } = renderHook(() => useConnections()); + const conn = result.current.addConnection({ + type: "bluetooth", + name: "Radio", + deviceId: "radio-1", + }); + + await act(() => result.current.connect(conn.id)); + + expect(requestDevice).not.toHaveBeenCalled(); + expect(kmp.bluetoothTargets).toEqual([ + { device: undefined, deviceId: "radio-1" }, + ]); + await act(() => result.current.disconnect(conn.id)); + }); + + it("shows the device picker on a click only when the device is unknown, and saves the picked device", async () => { + const picked = new FakeBluetoothDevice("radio-2", "Meshtastic_abcd"); + const requestDevice = installBluetooth([], picked); + const { result } = renderHook(() => useConnections()); + const conn = result.current.addConnection({ + type: "bluetooth", + name: "Radio", + deviceId: "radio-1", + }); + + await act(() => result.current.connect(conn.id, { allowPrompt: true })); + + expect(requestDevice).toHaveBeenCalledTimes(1); + expect(kmp.bluetoothTargets).toEqual([ + { device: picked, deviceId: "radio-2" }, + ]); + expect(saved(conn.id)).toMatchObject({ + deviceId: "radio-2", + deviceName: "Meshtastic_abcd", + }); + await act(() => result.current.disconnect(conn.id)); + }); + + it("keeps the device the form picked for later connects", async () => { + const device = new FakeBluetoothDevice("radio-3"); + const requestDevice = installBluetooth([]); + const { result } = renderHook(() => useConnections()); + + const conn = await act(() => + result.current.addConnectionAndConnect( + { type: "bluetooth", name: "Radio", deviceId: device.id }, + { bluetoothDevice: device }, + ), + ); + + expect(requestDevice).not.toHaveBeenCalled(); + expect(kmp.bluetoothTargets).toEqual([{ device, deviceId: "radio-3" }]); + await act(() => result.current.disconnect(conn.id)); + }); + + it("shows the SDK's reconnect attempts after the device drops", async () => { + installSerial([fakePort(ids)]); + const { result } = renderHook(() => useConnections()); + const conn = result.current.addConnection({ + type: "serial", + name: "Serial", + ...ids, + }); + await act(() => result.current.connect(conn.id)); + const client = kmp.client; + if (!client) throw new Error("no client created"); + + act(() => + client.setState( + state("reconnecting", { attempt: 1, errorKind: "serial-disconnected" }), + ), + ); + expect(saved(conn.id)).toMatchObject({ + status: "connecting", + reconnect: { attempt: 1, maxAttempts: 10 }, + }); + + act(() => client.setState(state("connected"))); + expect(saved(conn.id)).toMatchObject({ + status: "configuring", + reconnect: undefined, + }); + await act(() => result.current.disconnect(conn.id)); + }); +}); diff --git a/apps/web/src/pages/Connections/useConnections.test.ts b/apps/web/src/pages/Connections/useConnections.test.ts index 692915815..9458ea032 100644 --- a/apps/web/src/pages/Connections/useConnections.test.ts +++ b/apps/web/src/pages/Connections/useConnections.test.ts @@ -20,17 +20,10 @@ vi.mock("@core/sdkStorage.ts", () => ({ coordinator: undefined, })); -vi.mock("@app/core/connections/transports.ts", () => ({ - openTransport: async () => ({ - transport: { - toDevice: new WritableStream(), - fromDevice: new ReadableStream(), - disconnect: async () => {}, - }, - }), - closeTransport: () => {}, - probeConnection: async () => ({ status: "disconnected" }), -})); +vi.mock("@core/kmp/client.ts", async () => { + const { FakeKmpClient } = await import("@core/kmp/fakeClient.ts"); + return { createSerialClient: async () => new FakeKmpClient() }; +}); // The sqlocal repositories, replaced by the SDK's in-memory ones that record // the scopes they are given. Called with `new`; the returned object is the diff --git a/apps/web/src/pages/Connections/useConnections.ts b/apps/web/src/pages/Connections/useConnections.ts index 433016aff..acd2d6992 100644 --- a/apps/web/src/pages/Connections/useConnections.ts +++ b/apps/web/src/pages/Connections/useConnections.ts @@ -1,10 +1,22 @@ import { buildMeshDevice } from "@app/core/connections/sdkClient.ts"; import { - closeTransport, - openTransport, + type BluetoothConnection, + type ConnectionHandle, + knownBluetoothDevice, + permittedSerialPort, + pickBluetoothDevice, + pickSerialPort, probeConnection, -} from "@app/core/connections/transports.ts"; -import { createHttpClient } from "@core/kmp/client.ts"; + type SerialConnection, +} from "@app/core/connections/browserDevices.ts"; +import { + type BluetoothTarget, + createBluetoothClient, + createHttpClient, + createSerialClient, + type MeshtasticClient, + type SerialTarget, +} from "@core/kmp/client.ts"; import { editorFor } from "@core/kmp/configEditorIo.ts"; import { connectFailure, @@ -37,13 +49,79 @@ import { randId } from "@core/utils/randId.ts"; import { useCallback } from "react"; // Per-connection out-of-band handles tracked outside Zustand: -// - cachedTransports: held BT device / serial port for reconnect + cleanup. +// - heldSerialPorts / heldBluetoothDevices: the port or device the user +// picked, so later connects reuse it without prompting. // - configSubscriptions: handshake status / reboot unsubscribers. -const cachedTransports = new Map(); +const heldSerialPorts = new Map(); +const heldBluetoothDevices = new Map(); const configSubscriptions = new Map void>(); // Kotlin SDK connection-state subscriptions for connections it owns. const kmpSubscriptions = new Map void>(); +/** + * What the SDK opens for a serial connection. Automatic connects pass only + * the saved USB ids and the SDK reopens the permitted port itself; a click + * (`allowPrompt`) may show the port picker when no permitted port matches, + * and hands the chosen port over. + */ +async function serialTarget( + conn: SerialConnection, + allowPrompt: boolean, +): Promise { + const ids = { + usbVendorId: conn.usbVendorId, + usbProductId: conn.usbProductId, + }; + const held = heldSerialPorts.get(conn.id); + if (held) { + return { port: held, ...ids }; + } + if (!allowPrompt) { + return ids; + } + const port = + (await permittedSerialPort(conn)) ?? (await pickSerialPort(conn)); + heldSerialPorts.set(conn.id, port); + const info = port.getInfo(); + if ( + info.usbVendorId !== conn.usbVendorId || + info.usbProductId !== conn.usbProductId + ) { + useDeviceStore.getState().updateSavedConnection(conn.id, { + usbVendorId: info.usbVendorId, + usbProductId: info.usbProductId, + }); + } + return { + port, + usbVendorId: info.usbVendorId, + usbProductId: info.usbProductId, + }; +} + +async function bluetoothTarget( + conn: BluetoothConnection, + allowPrompt: boolean, +): Promise { + const held = heldBluetoothDevices.get(conn.id); + if (held) { + return { device: held, deviceId: conn.deviceId }; + } + if (!allowPrompt) { + return { deviceId: conn.deviceId }; + } + const device = + (await knownBluetoothDevice(conn)) ?? (await pickBluetoothDevice()); + heldBluetoothDevices.set(conn.id, device); + if (device.id !== conn.deviceId) { + useDeviceStore.getState().updateSavedConnection(conn.id, { + deviceId: device.id, + deviceName: device.name, + }); + } + return { device, deviceId: device.id }; +} + export function useConnections() { const connections = useDeviceStore((s) => s.savedConnections); const addSavedConnection = useDeviceStore((s) => s.addSavedConnection); @@ -96,8 +174,6 @@ export function useConnections() { }); } } - closeTransport(cachedTransports.get(id)); - cachedTransports.delete(id); log.debug("teardown: done", { id }); }, []); @@ -105,6 +181,8 @@ export function useConnections() { async (id: ConnectionId) => { const conn = connections.find((c) => c.id === id); await teardown(id, conn); + heldSerialPorts.delete(id); + heldBluetoothDevices.delete(id); if (conn?.meshDeviceId) { try { useDeviceStore.getState().removeDevice(conn.meshDeviceId); @@ -138,8 +216,6 @@ export function useConnections() { id: ConnectionId, transport: Transport, { sdkOwnsConnection = false }: { sdkOwnsConnection?: boolean } = {}, - bluetoothDevice?: BluetoothDevice, - serialPort?: SerialPort, ): Promise => { // Reuse existing meshDeviceId if the device entry still exists; otherwise mint a new one. const conn = connections.find((c) => c.id === id); @@ -192,9 +268,6 @@ export function useConnections() { device.addConnection(meshDevice); subscribeAll(device, meshDevice); - const cached = bluetoothDevice ?? serialPort; - if (cached) cachedTransports.set(id, cached); - setActiveConnectionId(id); device.setConnectionId(id); @@ -312,13 +385,13 @@ export function useConnections() { ); /** - * Connects over the device HTTP API through the Kotlin SDK, which owns - * the handshake and reconnects. The existing MeshDevice is fed from the - * SDK's frames so the rest of the app is unchanged. + * Connects through the Kotlin SDK, which owns the transport, the + * handshake and reconnects. The existing MeshDevice is fed from the SDK's + * frames so the rest of the app is unchanged. */ const connectThroughKmp = useCallback( - async (id: ConnectionId, url: string, allowPrompt: boolean) => { - const client = await createHttpClient(url, allowPrompt); + async (id: ConnectionId, makeClient: () => Promise) => { + const client = await makeClient(); let reconnecting = false; kmpSubscriptions.get(id)?.(); kmpSubscriptions.set( @@ -414,56 +487,37 @@ export function useConnections() { allowPrompt: !!opts?.allowPrompt, }); updateStatus(id, "connecting"); - if (conn.type === "http") { - return connectThroughKmp(conn.id, conn.url, opts?.allowPrompt ?? false); - } + const allowPrompt = opts?.allowPrompt ?? false; try { - const cached = cachedTransports.get(id); - const result = await openTransport(conn, { - allowPrompt: opts?.allowPrompt, - cachedBluetoothDevice: - conn.type === "bluetooth" - ? (cached as BluetoothDevice | undefined) - : undefined, - cachedSerialPort: - conn.type === "serial" - ? (cached as SerialPort | undefined) - : undefined, - }); - log.debug("connect: openTransport ok", { id }); - await setupMeshDevice( - id, - result.transport, - {}, - result.bluetoothDevice, - result.serialPort, - ); - log.info("connect: setupMeshDevice resolved, awaiting handshake", { - id, - }); - - // BT-specific: catch device-side disconnect to flip status. - result.bluetoothDevice?.addEventListener( - "gattserverdisconnected", - () => { - log.warn("BT gattserverdisconnected", { id }); - updateStatus(id, "disconnected"); - }, - ); - return true; - } catch (err) { - const e = err as Error; - log.error("connect: failed", { + switch (conn.type) { + case "http": + return await connectThroughKmp(id, () => + createHttpClient(conn.url, allowPrompt), + ); + case "serial": { + const target = await serialTarget(conn, allowPrompt); + return await connectThroughKmp(id, () => + createSerialClient(target), + ); + } + case "bluetooth": { + const target = await bluetoothTarget(conn, allowPrompt); + return await connectThroughKmp(id, () => + createBluetoothClient(target), + ); + } + } + } catch (error) { + log.error("connect: no device to connect to", { id, - name: e?.name, - message: e?.message, + name: error instanceof Error ? error.name : undefined, + message: error instanceof Error ? error.message : String(error), }); - const message = err instanceof Error ? err.message : String(err); - updateStatus(id, "error", message); + updateSavedConnection(id, connectFailure(error)); return false; } }, - [updateStatus, setupMeshDevice, connectThroughKmp], + [updateStatus, updateSavedConnection, connectThroughKmp], ); const disconnect = useCallback( @@ -495,10 +549,14 @@ export function useConnections() { ); const addConnectionAndConnect = useCallback( - async (input: NewConnection, btDevice?: BluetoothDevice) => { + async (input: NewConnection, handle?: ConnectionHandle) => { const conn = addConnection(input); - if (btDevice && conn.type === "bluetooth") - cachedTransports.set(conn.id, btDevice); + if (handle?.bluetoothDevice && conn.type === "bluetooth") { + heldBluetoothDevices.set(conn.id, handle.bluetoothDevice); + } + if (handle?.serialPort && conn.type === "serial") { + heldSerialPorts.set(conn.id, handle.serialPort); + } await connect(conn.id, { allowPrompt: true }); return conn; }, diff --git a/apps/web/src/tests/fakeBrowserDevices.ts b/apps/web/src/tests/fakeBrowserDevices.ts new file mode 100644 index 000000000..380ea0347 --- /dev/null +++ b/apps/web/src/tests/fakeBrowserDevices.ts @@ -0,0 +1,486 @@ +import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; +import { Protobuf } from "@core/protobuf.ts"; +import { vi } from "vitest"; + +/** + * Scripted stand-ins for Web Serial and Web Bluetooth, shaped like the DOM + * types so they can be handed to code expecting a `SerialPort` or + * `BluetoothDevice`. A `FakeRadio` answers the SDK handshake so the Kotlin + * facade reaches `connected`. + */ + +const START1 = 0x94; +const START2 = 0xc3; + +export function framed(payload: Uint8Array): Uint8Array { + const frame = new Uint8Array(4 + payload.length); + frame[0] = START1; + frame[1] = START2; + frame[2] = payload.length >> 8; + frame[3] = payload.length & 0xff; + frame.set(payload, 4); + return frame; +} + +/** Splits a byte stream into framed payloads, dropping wake bytes and noise. */ +export class FrameSplitter { + private pending: number[] = []; + + feed(chunk: Uint8Array): Uint8Array[] { + this.pending.push(...chunk); + const frames: Uint8Array[] = []; + while (true) { + const start = this.pending.findIndex( + (b, i) => b === START1 && this.pending[i + 1] === START2, + ); + if (start < 0) { + this.pending = this.pending.slice(-1); + return frames; + } + if (this.pending.length < start + 4) { + this.pending = this.pending.slice(start); + return frames; + } + const length = + ((this.pending[start + 2] ?? 0) << 8) | (this.pending[start + 3] ?? 0); + if (this.pending.length < start + 4 + length) { + this.pending = this.pending.slice(start); + return frames; + } + frames.push( + Uint8Array.from(this.pending.slice(start + 4, start + 4 + length)), + ); + this.pending = this.pending.slice(start + 4 + length); + } + } +} + +/** Answers `want_config_id` the way firmware does: my_info, then the matching config_complete_id. */ +export class FakeRadio { + readonly received: Protobuf.Mesh.ToRadio[] = []; + + constructor(readonly myNodeNum = 0x0a0b0c0d) {} + + respond(toRadio: Uint8Array): Uint8Array[] { + const message = fromBinary(Protobuf.Mesh.ToRadioSchema, toRadio); + this.received.push(message); + switch (message.payloadVariant.case) { + case "wantConfigId": { + const nonce = message.payloadVariant.value; + return [ + fromRadio({ + case: "myInfo", + value: create(Protobuf.Mesh.MyNodeInfoSchema, { + myNodeNum: this.myNodeNum, + }), + }), + fromRadio({ + case: "nodeInfo", + value: create(Protobuf.Mesh.NodeInfoSchema, { + num: this.myNodeNum, + user: { longName: "Fake radio", shortName: "FAKE" }, + }), + }), + fromRadio({ case: "configCompleteId", value: nonce }), + ]; + } + case "packet": + return this.answerAdmin(message.payloadVariant.value); + default: + return []; + } + } + + /** Answers the SDK's `get_owner_request`, which seeds the admin session passkey. */ + private answerAdmin(packet: Protobuf.Mesh.MeshPacket): Uint8Array[] { + if ( + packet.payloadVariant.case !== "decoded" || + packet.payloadVariant.value.portnum !== + Protobuf.Portnums.PortNum.ADMIN_APP + ) { + return []; + } + const request = fromBinary( + Protobuf.Admin.AdminMessageSchema, + packet.payloadVariant.value.payload, + ); + if (request.payloadVariant.case !== "getOwnerRequest") { + return []; + } + const response = create(Protobuf.Admin.AdminMessageSchema, { + sessionPasskey: Uint8Array.of(1, 2, 3, 4, 5, 6, 7, 8), + payloadVariant: { + case: "getOwnerResponse", + value: create(Protobuf.Mesh.UserSchema, { longName: "Fake radio" }), + }, + }); + return [ + fromRadio({ + case: "packet", + value: create(Protobuf.Mesh.MeshPacketSchema, { + from: this.myNodeNum, + to: this.myNodeNum, + id: packet.id + 1, + payloadVariant: { + case: "decoded", + value: create(Protobuf.Mesh.DataSchema, { + portnum: Protobuf.Portnums.PortNum.ADMIN_APP, + payload: toBinary(Protobuf.Admin.AdminMessageSchema, response), + requestId: packet.id, + }), + }, + }), + }), + ]; + } +} + +function fromRadio( + payloadVariant: Protobuf.Mesh.FromRadio["payloadVariant"], +): Uint8Array { + return toBinary( + Protobuf.Mesh.FromRadioSchema, + create(Protobuf.Mesh.FromRadioSchema, { payloadVariant }), + ); +} + +const noSignals = { + dataCarrierDetect: false, + clearToSend: false, + ringIndicator: false, + dataSetReady: false, +}; + +/** + * A `SerialPort` whose streams exist while open. Bytes written to it go + * through `radio`, whose replies are pushed back framed. + */ +export class FakeSerialPort extends EventTarget implements SerialPort { + onconnect = null; + ondisconnect = null; + connected = true; + readable: ReadableStream | null = null; + writable: WritableStream | null = null; + opens = 0; + closes = 0; + readonly written: Uint8Array[] = []; + private reader?: ReadableStreamDefaultController; + private readonly splitter = new FrameSplitter(); + + constructor( + private readonly info: SerialPortInfo, + readonly radio?: FakeRadio, + ) { + super(); + } + + getInfo(): SerialPortInfo { + return this.info; + } + + async open(): Promise { + this.opens += 1; + this.readable = new ReadableStream({ + start: (controller) => { + this.reader = controller; + }, + }); + this.writable = new WritableStream({ + write: (chunk) => { + this.written.push(chunk); + for (const payload of this.splitter.feed(chunk)) { + for (const reply of this.radio?.respond(payload) ?? []) { + this.push(framed(reply)); + } + } + }, + }); + } + + async close(): Promise { + this.closes += 1; + try { + this.reader?.close(); + } catch {} + this.readable = null; + this.writable = null; + } + + async forget(): Promise {} + + async setSignals(): Promise {} + + async getSignals(): Promise { + return noSignals; + } + + push(bytes: Uint8Array): void { + this.reader?.enqueue(bytes); + } + + /** The OS lost the device: the read stream errors, as Chrome's does. */ + unplug(): void { + try { + this.reader?.error(new Error("The device has been lost.")); + } catch {} + this.readable = null; + this.writable = null; + } +} + +export class FakeSerial extends EventTarget { + ports: SerialPort[] = []; + readonly requestPort = vi.fn((): Promise => { + return Promise.reject(new Error("prompted")); + }); + + getPorts(): Promise { + return Promise.resolve(this.ports); + } + + dispatch(type: "connect" | "disconnect", port: SerialPort): void { + const event = new Event(type); + Object.defineProperty(event, "target", { value: port }); + this.dispatchEvent(event); + } +} + +export function installSerial(ports: SerialPort[] = []): FakeSerial { + const serial = new FakeSerial(); + serial.ports = ports; + Object.defineProperty(navigator, "serial", { + configurable: true, + value: serial, + }); + return serial; +} + +export function uninstallBrowserDevices(): void { + Reflect.deleteProperty(navigator, "serial"); + Reflect.deleteProperty(navigator, "bluetooth"); +} + +const MESH_SERVICE = "6ba1b218-15a8-461f-9fa8-5dcae273eafd"; +const TORADIO = "f75c76d2-129e-4dad-a1dd-7866124401e7"; +const FROMRADIO = "2c55e69e-4993-11ed-b878-0242ac120002"; +const FROMNUM = "ed9da18c-a800-4f66-a670-aa7547e34453"; + +const noProperties: BluetoothCharacteristicProperties = { + authenticatedSignedWrites: false, + broadcast: false, + indicate: false, + notify: true, + read: true, + reliableWrite: false, + writableAuxiliaries: false, + write: true, + writeWithoutResponse: false, +}; + +class FakeCharacteristic + extends EventTarget + implements BluetoothRemoteGATTCharacteristic +{ + oncharacteristicvaluechanged = () => {}; + readonly properties = noProperties; + value?: DataView; + + constructor( + readonly uuid: string, + readonly service: BluetoothRemoteGATTService, + private readonly device: FakeBluetoothDevice, + ) { + super(); + } + + getDescriptor(): Promise { + return Promise.reject(new Error("no descriptors")); + } + + async getDescriptors(): Promise { + return []; + } + + async readValue(): Promise { + const next = this.device.queued.shift(); + return new DataView(next ? next.slice().buffer : new ArrayBuffer(0)); + } + + async writeValue(value: BufferSource): Promise { + await this.writeValueWithResponse(value); + } + + async writeValueWithResponse(value: BufferSource): Promise { + const payload = + value instanceof ArrayBuffer + ? new Uint8Array(value) + : new Uint8Array(value.buffer, value.byteOffset, value.byteLength); + this.device.written.push(payload); + for (const reply of this.device.radio?.respond(payload) ?? []) { + this.device.queued.push(reply); + } + this.device.notifyFromNum(); + } + + async writeValueWithoutResponse(value: BufferSource): Promise { + await this.writeValueWithResponse(value); + } + + async startNotifications(): Promise { + this.device.notifying = true; + return this; + } + + async stopNotifications(): Promise { + this.device.notifying = false; + return this; + } +} + +class FakeService extends EventTarget implements BluetoothRemoteGATTService { + oncharacteristicvaluechanged = () => {}; + onserviceadded = () => {}; + onservicechanged = () => {}; + onserviceremoved = () => {}; + readonly isPrimary = true; + readonly characteristics = new Map(); + + constructor( + readonly uuid: string, + readonly device: FakeBluetoothDevice, + ) { + super(); + } + + async getCharacteristic( + characteristic: BluetoothCharacteristicUUID, + ): Promise { + const found = this.characteristics.get(String(characteristic)); + if (!found) throw new Error("no such characteristic"); + return found; + } + + async getCharacteristics(): Promise { + return [...this.characteristics.values()]; + } + + getIncludedService(): Promise { + return Promise.reject(new Error("no included services")); + } + + async getIncludedServices(): Promise { + return []; + } +} + +class FakeGattServer implements BluetoothRemoteGATTServer { + connected = false; + + constructor( + readonly device: FakeBluetoothDevice, + private readonly service: FakeService | undefined, + ) {} + + async connect(): Promise { + this.device.connects += 1; + this.connected = true; + return this; + } + + disconnect(): void { + this.connected = false; + } + + async getPrimaryService( + uuid: BluetoothServiceUUID, + ): Promise { + if (!this.service || String(uuid) !== this.service.uuid) { + throw new Error("no such service"); + } + return this.service; + } + + async getPrimaryServices(): Promise { + return this.service ? [this.service] : []; + } +} + +/** + * A `BluetoothDevice` with the Meshtastic GATT service. Writes to `toradio` + * go through `radio`; replies queue on `fromradio` and a `fromnum` + * notification announces them. + */ +export class FakeBluetoothDevice + extends EventTarget + implements BluetoothDevice +{ + onadvertisementreceived = () => {}; + ongattserverdisconnected = () => {}; + oncharacteristicvaluechanged = () => {}; + onserviceadded = () => {}; + onservicechanged = () => {}; + onserviceremoved = () => {}; + watchingAdvertisements = false; + connects = 0; + notifying = false; + readonly queued: Uint8Array[] = []; + readonly written: Uint8Array[] = []; + readonly gatt: FakeGattServer; + private readonly fromNum: FakeCharacteristic; + + constructor( + readonly id: string, + readonly name?: string, + readonly radio?: FakeRadio, + hasService = true, + ) { + super(); + const service = new FakeService(MESH_SERVICE, this); + this.fromNum = new FakeCharacteristic(FROMNUM, service, this); + for (const uuid of [TORADIO, FROMRADIO]) { + service.characteristics.set( + uuid, + new FakeCharacteristic(uuid, service, this), + ); + } + service.characteristics.set(FROMNUM, this.fromNum); + this.gatt = new FakeGattServer(this, hasService ? service : undefined); + } + + async forget(): Promise {} + + async watchAdvertisements(): Promise {} + + notifyFromNum(): void { + this.fromNum.dispatchEvent(new Event("characteristicvaluechanged")); + } + + /** The link dropped: Chrome fires `gattserverdisconnected` on the device. */ + dropLink(): void { + this.gatt.connected = false; + this.dispatchEvent(new Event("gattserverdisconnected")); + } +} + +export class FakeBluetooth { + devices: FakeBluetoothDevice[] = []; + readonly requestDevice = vi.fn((): Promise => { + return Promise.reject(new Error("prompted")); + }); + + getDevices(): Promise { + return Promise.resolve(this.devices); + } +} + +export function installBluetooth( + devices: FakeBluetoothDevice[] = [], +): FakeBluetooth { + const bluetooth = new FakeBluetooth(); + bluetooth.devices = devices; + Object.defineProperty(navigator, "bluetooth", { + configurable: true, + value: bluetooth, + }); + return bluetooth; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 15d0fe2e7..470e3d70c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -84,12 +84,6 @@ importers: '@meshtastic/transport-http': specifier: workspace:* version: link:../../packages/transport-http - '@meshtastic/transport-web-bluetooth': - specifier: workspace:* - version: link:../../packages/transport-web-bluetooth - '@meshtastic/transport-web-serial': - specifier: workspace:* - version: link:../../packages/transport-web-serial '@noble/curves': specifier: ^2.4.0 version: 2.4.0 From 189074b87e68c03670f04a2c3bf9415615163721 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 09:12:43 -0500 Subject: [PATCH 15/49] feat(sdk-kmp): send handles, lockdown admin and a host storage provider sendText, sendPacket, requestNodeInfo and requestPosition now return the packet id straight away with the outcome as a promise, so the web client can file an optimistic message under the id the routing ack will name. Admin dispatch forwards lockdown_auth. The factories take an optional StorageJs, a host-implemented StorageProvider/DeviceStorage over encoded protobufs; ConfigBundleJs carries deviceUiConfig for the round trip. --- apps/web/src/core/kmp/fakeClient.ts | 61 ++++++--- .../kotlin/org/meshtastic/sdk/js/Admin.kt | 1 + .../kotlin/org/meshtastic/sdk/js/Client.kt | 48 +++++-- .../kotlin/org/meshtastic/sdk/js/Data.kt | 19 +++ .../kotlin/org/meshtastic/sdk/js/Storage.kt | 120 ++++++++++++++++++ 5 files changed, 220 insertions(+), 29 deletions(-) create mode 100644 packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Storage.kt diff --git a/apps/web/src/core/kmp/fakeClient.ts b/apps/web/src/core/kmp/fakeClient.ts index 39ac4bf08..c99de1ba8 100644 --- a/apps/web/src/core/kmp/fakeClient.ts +++ b/apps/web/src/core/kmp/fakeClient.ts @@ -5,6 +5,7 @@ import type { ConnectionStateJs, MeshtasticClient, NodeChangeJs, + SendHandleJs, SendOutcomeJs, } from "@meshtastic/sdk-kmp"; @@ -68,12 +69,22 @@ export class FakeKmpClient implements MeshtasticClient { channels: Uint8Array[] | null = null; nodeList: Uint8Array[] = []; readonly sent: Uint8Array[] = []; - readonly texts: Array<{ text: string; to: number; channel: number }> = []; + readonly texts: Array<{ + text: string; + to: number; + channel: number; + id: number; + }> = []; readonly packets: Uint8Array[] = []; readonly requests: Array<{ kind: string; nodeNum: number }> = []; readonly disconnects: number[] = []; readonly admins = new Map(); - sendOutcome: SendOutcomeJs = { id: 1, ok: true, reason: null }; + /** Outcome every send resolves with; `settleSends` resolves the pending ones. */ + sendOutcome: Omit = { ok: true, reason: null }; + /** When set, sends stay pending until `settleSends` is called. */ + holdSends = false; + private nextSendId = 1; + private readonly pendingSends: Array<(outcome: SendOutcomeJs) => void> = []; adminResult: AdminResultJs = adminOk(); private frameListeners: Listeners = new Set(); private stateListeners: Listeners = new Set(); @@ -144,28 +155,48 @@ export class FakeKmpClient implements MeshtasticClient { return created; } - async sendText( - text: string, - to: number, - channel: number, - ): Promise { - this.texts.push({ text, to, channel }); - return this.sendOutcome; + sendText(text: string, to: number, channel: number): SendHandleJs { + const handle = this.handle(); + this.texts.push({ text, to, channel, id: handle.id }); + return handle; } - async sendPacket(meshPacket: Uint8Array): Promise { + sendPacket(meshPacket: Uint8Array): SendHandleJs { this.packets.push(meshPacket); - return this.sendOutcome; + return this.handle(); } - async requestNodeInfo(nodeNum: number): Promise { + requestNodeInfo(nodeNum: number): SendHandleJs { this.requests.push({ kind: "nodeInfo", nodeNum }); - return this.sendOutcome; + return this.handle(); } - async requestPosition(nodeNum: number): Promise { + requestPosition(nodeNum: number): SendHandleJs { this.requests.push({ kind: "position", nodeNum }); - return this.sendOutcome; + return this.handle(); + } + + /** Resolves every held send with `outcome`, or with `sendOutcome`. */ + settleSends(outcome?: Omit): void { + const settled = this.pendingSends.splice(0); + const result = outcome ?? this.sendOutcome; + for (const resolve of settled) { + resolve({ id: 0, ...result }); + } + } + + private handle(): SendHandleJs { + const id = this.nextSendId++; + const outcome = new Promise((resolve) => { + const settle = (result: SendOutcomeJs): void => + resolve({ ...result, id }); + if (this.holdSends) { + this.pendingSends.push(settle); + } else { + settle({ id, ...this.sendOutcome }); + } + }); + return { id, outcome }; } async traceRoute(dest: number): Promise { diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Admin.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Admin.kt index 97b2e30fc..8d5b907b6 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Admin.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Admin.kt @@ -110,6 +110,7 @@ private suspend fun AdminApi.dispatch(message: AdminMessage): AdminResultJs { if (message.nodedb_reset == true) return nodeDbReset().toJs() if (message.enter_dfu_mode_request == true) return enterDfuMode().toJs() message.set_time_only?.let { return setTimeOnly(it).toJs() } + message.lockdown_auth?.let { return lockdown(it).toJs() } return failure("unsupported") } diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt index d4ba1e9ce..91888363c 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt @@ -38,12 +38,16 @@ import kotlin.js.JsExport import kotlin.js.Promise @JsExport -class MeshtasticClient internal constructor(transport: RadioTransport, private val maxAttempts: Int) { +class MeshtasticClient internal constructor( + transport: RadioTransport, + private val maxAttempts: Int, + storage: StorageJs? = null, +) { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) private val frameListeners = mutableSetOf<(Uint8Array) -> Unit>() private val client: RadioClient = RadioClient { transport(TappingTransport(transport) { bytes -> frameListeners.toList().forEach { it(bytes.toUint8Array()) } }) - storage(InMemoryStorageProvider()) + storage(if (storage == null) InMemoryStorageProvider() else JsStorageProvider(storage)) autoReconnect(AutoReconnectConfig(maxAttempts = maxAttempts)) } @@ -100,16 +104,16 @@ class MeshtasticClient internal constructor(transport: RadioTransport, private v fun admin(dest: Int = 0): AdminJs = AdminJs(if (dest == 0) client.admin else client.admin.forNode(NodeId(dest)), scope) - fun sendText(text: String, to: Int, channel: Int, replyId: Int = 0): Promise = + fun sendText(text: String, to: Int, channel: Int, replyId: Int = 0): SendHandleJs = sending { client.sendText(text, NodeId(to), ChannelIndex(channel), replyId) } /** Sends an encoded `MeshPacket`; the SDK assigns the id and reports the outcome. */ - fun sendPacket(meshPacket: Uint8Array): Promise = + fun sendPacket(meshPacket: Uint8Array): SendHandleJs = sending { client.send(MeshPacket.ADAPTER.decode(meshPacket.toByteArray())) } - fun requestNodeInfo(nodeNum: Int): Promise = sending { client.requestNodeInfo(NodeId(nodeNum)) } + fun requestNodeInfo(nodeNum: Int): SendHandleJs = sending { client.requestNodeInfo(NodeId(nodeNum)) } - fun requestPosition(nodeNum: Int): Promise = sending { + fun requestPosition(nodeNum: Int): SendHandleJs = sending { client.send( MeshPacket.Builder().also { packet -> packet.to = nodeNum @@ -158,13 +162,16 @@ class MeshtasticClient internal constructor(transport: RadioTransport, private v } } - private fun sending(send: suspend () -> MessageHandle): Promise = scope.promise { + private fun sending(send: () -> MessageHandle): SendHandleJs { val handle = try { send() } catch (e: Throwable) { throw e.toJsError().unsafeCast() } - handle.await().toJs(handle.id.raw) + val js = jso() + js.id = handle.id.raw + js.outcome = scope.promise { handle.await().toJs(handle.id.raw) } + return js.unsafeCast() } private fun Flow.subscribe(): () -> Unit { @@ -174,8 +181,12 @@ class MeshtasticClient internal constructor(transport: RadioTransport, private v } @JsExport -fun createHttpClient(url: String, allowPrompt: Boolean = false, maxAttempts: Int = 10): MeshtasticClient = - MeshtasticClient(HttpTransport(url.trimEnd('/'), allowPrompt), maxAttempts) +fun createHttpClient( + url: String, + allowPrompt: Boolean = false, + maxAttempts: Int = 10, + storage: StorageJs? = null, +): MeshtasticClient = MeshtasticClient(HttpTransport(url.trimEnd('/'), allowPrompt), maxAttempts, storage) /** * A client over Web Serial. `port` is a `SerialPort` picked inside a user @@ -183,8 +194,13 @@ fun createHttpClient(url: String, allowPrompt: Boolean = false, maxAttempts: Int * without prompting. */ @JsExport -fun createSerialClient(port: dynamic, usbVendorId: Int?, usbProductId: Int?, maxAttempts: Int = 10): MeshtasticClient = - MeshtasticClient(WebSerialTransport(port, usbVendorId, usbProductId), maxAttempts) +fun createSerialClient( + port: dynamic, + usbVendorId: Int?, + usbProductId: Int?, + maxAttempts: Int = 10, + storage: StorageJs? = null, +): MeshtasticClient = MeshtasticClient(WebSerialTransport(port, usbVendorId, usbProductId), maxAttempts, storage) /** * A client over Web Bluetooth. `device` is a `BluetoothDevice` picked inside @@ -192,5 +208,9 @@ fun createSerialClient(port: dynamic, usbVendorId: Int?, usbProductId: Int?, max * without prompting. */ @JsExport -fun createBluetoothClient(device: dynamic, deviceId: String?, maxAttempts: Int = 10): MeshtasticClient = - MeshtasticClient(WebBluetoothTransport(device, deviceId), maxAttempts) +fun createBluetoothClient( + device: dynamic, + deviceId: String?, + maxAttempts: Int = 10, + storage: StorageJs? = null, +): MeshtasticClient = MeshtasticClient(WebBluetoothTransport(device, deviceId), maxAttempts, storage) diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Data.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Data.kt index d0aef815c..d643f7f33 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Data.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Data.kt @@ -6,6 +6,7 @@ import org.khronos.webgl.Uint8Array import org.meshtastic.proto.Channel import org.meshtastic.proto.Config import org.meshtastic.proto.DeviceMetadata +import org.meshtastic.proto.DeviceUIConfig import org.meshtastic.proto.ModuleConfig import org.meshtastic.proto.MyNodeInfo import org.meshtastic.proto.NodeInfo @@ -15,6 +16,7 @@ import org.meshtastic.sdk.SendFailure import org.meshtastic.sdk.SendOutcome import kotlin.js.ExperimentalJsExport import kotlin.js.JsExport +import kotlin.js.Promise /** The device's config as the handshake delivered it; every field is an encoded protobuf. */ @JsExport @@ -23,6 +25,7 @@ external interface ConfigBundleJs { val metadata: Uint8Array val configs: Array val moduleConfigs: Array + val deviceUiConfig: Uint8Array? } /** @@ -46,15 +49,31 @@ external interface SendOutcomeJs { val reason: String? } +/** A packet handed to the SDK: its id straight away, its outcome once the mesh answers. */ +@JsExport +external interface SendHandleJs { + val id: Int + val outcome: Promise +} + internal fun ConfigBundle.toJs(): ConfigBundleJs { val bundle = jso() bundle.myInfo = MyNodeInfo.ADAPTER.encode(myInfo).toUint8Array() bundle.metadata = DeviceMetadata.ADAPTER.encode(metadata).toUint8Array() bundle.configs = configs.map { Config.ADAPTER.encode(it).toUint8Array() }.toTypedArray() bundle.moduleConfigs = moduleConfigs.map { ModuleConfig.ADAPTER.encode(it).toUint8Array() }.toTypedArray() + bundle.deviceUiConfig = deviceUIConfig?.let { DeviceUIConfig.ADAPTER.encode(it).toUint8Array() } return bundle.unsafeCast() } +internal fun ConfigBundleJs.toKotlin(): ConfigBundle = ConfigBundle( + myInfo = MyNodeInfo.ADAPTER.decode(myInfo.toByteArray()), + metadata = DeviceMetadata.ADAPTER.decode(metadata.toByteArray()), + configs = configs.map { Config.ADAPTER.decode(it.toByteArray()) }, + moduleConfigs = moduleConfigs.map { ModuleConfig.ADAPTER.decode(it.toByteArray()) }, + deviceUIConfig = deviceUiConfig?.let { DeviceUIConfig.ADAPTER.decode(it.toByteArray()) }, +) + internal fun List.toJs(): Array = map { Channel.ADAPTER.encode(it).toUint8Array() }.toTypedArray() internal fun NodeInfo.encodeJs(): Uint8Array = NodeInfo.ADAPTER.encode(this).toUint8Array() diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Storage.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Storage.kt new file mode 100644 index 000000000..33b3da113 --- /dev/null +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Storage.kt @@ -0,0 +1,120 @@ +@file:OptIn(ExperimentalJsExport::class) + +package org.meshtastic.sdk.js + +import kotlinx.coroutines.await +import okio.ByteString.Companion.toByteString +import org.khronos.webgl.Uint8Array +import org.meshtastic.proto.Channel +import org.meshtastic.proto.NodeInfo +import org.meshtastic.sdk.ConfigBundle +import org.meshtastic.sdk.DeviceStorage +import org.meshtastic.sdk.NodeId +import org.meshtastic.sdk.SessionPasskey +import org.meshtastic.sdk.StorageProvider +import org.meshtastic.sdk.TransportIdentity +import kotlin.js.ExperimentalJsExport +import kotlin.js.JsExport +import kotlin.js.Promise + +/** A host-implemented store the SDK opens before connecting; see the SDK's `StorageProvider`. */ +@JsExport +external interface StorageJs { + fun activate(identity: String): Promise +} + +@JsExport +external interface HeartbeatJs { + val nodeNum: Int + val epochMillis: Double +} + +@JsExport +external interface PasskeyJs { + val bytes: Uint8Array + val expiresAtEpochMs: Double +} + +/** + * One device's persisted state, as the SDK's `DeviceStorage`. Protobufs + * cross as encoded bytes; `loadConfig` and `loadSessionPasskey` resolve to + * null when nothing is stored. + */ +@JsExport +external interface DeviceStorageJs { + fun loadNodes(): Promise> + fun saveNode(nodeInfo: Uint8Array): Promise + fun removeNode(nodeNum: Int): Promise + fun loadConfig(): Promise + fun saveConfig(bundle: ConfigBundleJs): Promise + fun loadChannels(): Promise> + fun saveChannels(channels: Array): Promise + fun recordOwnNode(nodeNum: Int, firmwareVersion: String): Promise + fun clear(): Promise + fun close() + fun saveSessionPasskey(passkey: PasskeyJs): Promise + fun loadSessionPasskey(): Promise + fun saveHeartbeat(nodeNum: Int, epochMillis: Double): Promise + fun loadHeartbeats(): Promise> +} + +internal class JsStorageProvider(private val js: StorageJs) : StorageProvider { + override suspend fun activate(identity: TransportIdentity): DeviceStorage = + JsDeviceStorage(js.activate(identity.raw).await()) +} + +internal class JsDeviceStorage(private val js: DeviceStorageJs) : DeviceStorage { + override suspend fun loadNodes(): Map = + js.loadNodes().await().map { NodeInfo.ADAPTER.decode(it.toByteArray()) }.associateBy { NodeId(it.num) } + + override suspend fun saveNode(node: NodeInfo) { + js.saveNode(node.encodeJs()).await() + } + + override suspend fun removeNode(nodeId: NodeId) { + js.removeNode(nodeId.raw).await() + } + + override suspend fun loadConfig(): ConfigBundle? = js.loadConfig().await()?.toKotlin() + + override suspend fun saveConfig(config: ConfigBundle) { + js.saveConfig(config.toJs()).await() + } + + override suspend fun loadChannels(): List = + js.loadChannels().await().map { Channel.ADAPTER.decode(it.toByteArray()) } + + override suspend fun saveChannels(channels: List) { + js.saveChannels(channels.toJs()).await() + } + + override suspend fun recordOwnNode(nodeNum: NodeId, firmwareVersion: String) { + js.recordOwnNode(nodeNum.raw, firmwareVersion).await() + } + + override suspend fun clear() { + js.clear().await() + } + + override fun close() { + js.close() + } + + override suspend fun saveSessionPasskey(passkey: SessionPasskey) { + val value = jso() + value.bytes = passkey.bytes.toUint8Array() + value.expiresAtEpochMs = passkey.expiresAtEpochMs.toDouble() + js.saveSessionPasskey(value.unsafeCast()).await() + } + + override suspend fun loadSessionPasskey(): SessionPasskey? = js.loadSessionPasskey().await()?.let { + SessionPasskey(it.bytes.toByteArray().toByteString(), it.expiresAtEpochMs.toLong()) + } + + override suspend fun saveHeartbeat(nodeId: NodeId, epochMillis: Long) { + js.saveHeartbeat(nodeId.raw, epochMillis.toDouble()).await() + } + + override suspend fun loadHeartbeats(): Map = + js.loadHeartbeats().await().associate { NodeId(it.nodeNum) to it.epochMillis.toLong() } +} From 12a9370d57cac559f032ae2fba154bec80f1c0dd Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 09:18:10 -0500 Subject: [PATCH 16/49] refactor(web): own the sqlocal repositories and the Types namespace Moves the message, draft, node and telemetry repositories, the DB opener, migrations and the multi-tab coordinator from sdk-storage-sqlocal into apps/web/src/core/storage with local Message, Node and TelemetryReading types, cast-free, and drops the sdk-storage-sqlocal dependency. The Types namespace (ChannelNumber, Destination, PacketMetadata, DeviceStatusEnum) is now local in core/types.ts. --- apps/web/package.json | 5 +- apps/web/src/core/connections/sdkClient.ts | 10 +- apps/web/src/core/protobuf.ts | 2 +- apps/web/src/core/sdkStorage.ts | 7 +- apps/web/src/core/storage/coordinator.test.ts | 13 + apps/web/src/core/storage/coordinator.ts | 64 +++++ apps/web/src/core/storage/db.ts | 99 +++++++ apps/web/src/core/storage/drafts.test.ts | 111 ++++++++ apps/web/src/core/storage/drafts.ts | 92 +++++++ apps/web/src/core/storage/memoryDb.ts | 26 ++ apps/web/src/core/storage/messages.test.ts | 216 +++++++++++++++ apps/web/src/core/storage/messages.ts | 245 ++++++++++++++++++ apps/web/src/core/storage/migrations.test.ts | 111 ++++++++ apps/web/src/core/storage/nodes.test.ts | 96 +++++++ apps/web/src/core/storage/nodes.ts | 147 +++++++++++ apps/web/src/core/storage/schema.ts | 216 +++++++++++++++ apps/web/src/core/storage/telemetry.test.ts | 123 +++++++++ apps/web/src/core/storage/telemetry.ts | 242 +++++++++++++++++ apps/web/src/core/storage/types.ts | 197 ++++++++++++++ apps/web/src/core/types.ts | 53 ++++ .../pages/Connections/useConnections.test.ts | 11 +- 21 files changed, 2070 insertions(+), 16 deletions(-) create mode 100644 apps/web/src/core/storage/coordinator.test.ts create mode 100644 apps/web/src/core/storage/coordinator.ts create mode 100644 apps/web/src/core/storage/db.ts create mode 100644 apps/web/src/core/storage/drafts.test.ts create mode 100644 apps/web/src/core/storage/drafts.ts create mode 100644 apps/web/src/core/storage/memoryDb.ts create mode 100644 apps/web/src/core/storage/messages.test.ts create mode 100644 apps/web/src/core/storage/messages.ts create mode 100644 apps/web/src/core/storage/migrations.test.ts create mode 100644 apps/web/src/core/storage/nodes.test.ts create mode 100644 apps/web/src/core/storage/nodes.ts create mode 100644 apps/web/src/core/storage/schema.ts create mode 100644 apps/web/src/core/storage/telemetry.test.ts create mode 100644 apps/web/src/core/storage/telemetry.ts create mode 100644 apps/web/src/core/storage/types.ts create mode 100644 apps/web/src/core/types.ts diff --git a/apps/web/package.json b/apps/web/package.json index 52e059ade..1bed98d3e 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -40,7 +40,6 @@ "@meshtastic/sdk": "workspace:*", "@meshtastic/sdk-kmp": "workspace:*", "@meshtastic/sdk-react": "workspace:*", - "@meshtastic/sdk-storage-sqlocal": "workspace:*", "@meshtastic/transport-http": "workspace:*", "@noble/curves": "^2.4.0", "@preact/signals-core": "^1.14.4", @@ -75,6 +74,7 @@ "clsx": "^2.1.1", "cmdk": "^1.1.1", "crypto-random-string": "^6.0.0", + "drizzle-orm": "^0.45.4", "i18next": "^26.4.5", "i18next-browser-languagedetector": "^8.2.1", "i18next-http-backend": "^4.0.3", @@ -91,6 +91,7 @@ "react-map-gl": "8.1.3", "react-qrcode-logo": "^4.1.0", "rfc4648": "^1.5.4", + "sqlocal": "^0.18.0", "tslog": "^5.2.0", "vaul": "^1.1.2", "vite": "^8.3.4", @@ -110,6 +111,7 @@ "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "@types/serviceworker": "^0.0.203", + "@types/sql.js": "^1.4.11", "@types/w3c-web-serial": "^1.0.8", "@vitejs/plugin-basic-ssl": "^2.3.0", "@vitejs/plugin-react": "^6.1.2", @@ -118,6 +120,7 @@ "happy-dom": "^21.0.1", "oxfmt": "^0.73.0", "oxlint": "^1.88.0", + "sql.js": "^1.15.0", "tailwind-merge": "^3.7.0", "tailwindcss": "^4.3.3", "tailwindcss-animate": "^1.0.7", diff --git a/apps/web/src/core/connections/sdkClient.ts b/apps/web/src/core/connections/sdkClient.ts index ea4508085..d97c5a664 100644 --- a/apps/web/src/core/connections/sdkClient.ts +++ b/apps/web/src/core/connections/sdkClient.ts @@ -2,12 +2,10 @@ import { coordinator, getStorageDb } from "@core/sdkStorage.ts"; import type { ConnectionId } from "@core/stores/deviceStore/types"; import { createLogger } from "@core/log.ts"; import { MeshDevice, type Transport } from "@meshtastic/sdk"; -import { - SqlocalDraftRepository, - SqlocalMessageRepository, -} from "@meshtastic/sdk-storage-sqlocal/chat"; -import { SqlocalNodesRepository } from "@meshtastic/sdk-storage-sqlocal/nodes"; -import { SqlocalTelemetryRepository } from "@meshtastic/sdk-storage-sqlocal/telemetry"; +import { SqlocalDraftRepository } from "@core/storage/drafts.ts"; +import { SqlocalMessageRepository } from "@core/storage/messages.ts"; +import { SqlocalNodesRepository } from "@core/storage/nodes.ts"; +import { SqlocalTelemetryRepository } from "@core/storage/telemetry.ts"; const log = createLogger("sdkClient"); diff --git a/apps/web/src/core/protobuf.ts b/apps/web/src/core/protobuf.ts index 70ce332b4..d940a57c8 100644 --- a/apps/web/src/core/protobuf.ts +++ b/apps/web/src/core/protobuf.ts @@ -1,2 +1,2 @@ export * as Protobuf from "@meshtastic/protobufs"; -export { Types } from "@meshtastic/sdk"; +export * as Types from "./types.ts"; diff --git a/apps/web/src/core/sdkStorage.ts b/apps/web/src/core/sdkStorage.ts index 8b5222f1c..ca6d069a6 100644 --- a/apps/web/src/core/sdkStorage.ts +++ b/apps/web/src/core/sdkStorage.ts @@ -1,9 +1,6 @@ import { createLogger } from "@core/log.ts"; -import { - MultiTabCoordinator, - type OpenedSqlocalDb, - openSqlocalDb, -} from "@meshtastic/sdk-storage-sqlocal"; +import { MultiTabCoordinator } from "@core/storage/coordinator.ts"; +import { type OpenedSqlocalDb, openSqlocalDb } from "@core/storage/db.ts"; const log = createLogger("sdkStorage"); diff --git a/apps/web/src/core/storage/coordinator.test.ts b/apps/web/src/core/storage/coordinator.test.ts new file mode 100644 index 000000000..c2ff3b4d9 --- /dev/null +++ b/apps/web/src/core/storage/coordinator.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from "vitest"; +import { MultiTabCoordinator } from "./coordinator.ts"; + +describe("MultiTabCoordinator", () => { + it("subscribe/unsubscribe gates listeners", () => { + const coordinator = new MultiTabCoordinator(); + const seen: number[] = []; + const off = coordinator.subscribe(() => seen.push(1)); + off(); + // No real BroadcastChannel here; ensure subscribe returns a callable no-op + expect(seen).toEqual([]); + }); +}); diff --git a/apps/web/src/core/storage/coordinator.ts b/apps/web/src/core/storage/coordinator.ts new file mode 100644 index 000000000..2bffe1061 --- /dev/null +++ b/apps/web/src/core/storage/coordinator.ts @@ -0,0 +1,64 @@ +/** + * Coordination across browser tabs of the same origin. + * + * - **Web Locks API** (`navigator.locks`): a single tab holds the writer lock + * for a given resource; others queue. Used to serialize destructive + * operations (full DB rebuilds, bulk imports) when needed. + * - **BroadcastChannel**: lock-free pub/sub for "data changed" notifications, + * so reader tabs can refresh their views without polling. + * + * sqlocal handles low-level DB write serialization via OPFS file locks; this + * layer is for app-level changes ("messages-changed for device 5, channel 0") + * so the chat slice in another tab can re-query after a write. + */ + +export type ChangeKind = + | "messages-changed" + | "nodes-changed" + | "telemetry-changed"; + +export interface ChangeEvent { + kind: ChangeKind; + deviceId: number; + /** Free-form key (e.g. conversationKey for chat). */ + key?: string; +} + +const CHANNEL_NAME = "meshtastic-storage"; + +export class MultiTabCoordinator { + private readonly channel: BroadcastChannel | undefined; + private readonly listeners = new Set<(event: ChangeEvent) => void>(); + + constructor() { + if (typeof BroadcastChannel === "undefined") { + this.channel = undefined; + return; + } + this.channel = new BroadcastChannel(CHANNEL_NAME); + this.channel.onmessage = (msg: MessageEvent) => { + for (const listener of this.listeners) listener(msg.data); + }; + } + + broadcast(event: ChangeEvent): void { + this.channel?.postMessage(event); + } + + subscribe(listener: (event: ChangeEvent) => void): () => void { + this.listeners.add(listener); + return () => { + this.listeners.delete(listener); + }; + } + + /** + * Acquires an app-level Web Lock for the given resource. Resolves with a + * release function once the lock is granted. Falls through (no lock held) + * when the Web Locks API is not available. + */ + close(): void { + this.channel?.close(); + this.listeners.clear(); + } +} diff --git a/apps/web/src/core/storage/db.ts b/apps/web/src/core/storage/db.ts new file mode 100644 index 000000000..cbf15b26a --- /dev/null +++ b/apps/web/src/core/storage/db.ts @@ -0,0 +1,99 @@ +import { drizzle } from "drizzle-orm/sqlite-proxy"; +import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; +import { SQLocalDrizzle } from "sqlocal/drizzle"; +import * as schema from "./schema.ts"; +import { MIGRATIONS } from "./schema.ts"; + +export interface CreateSqlocalDbOptions { + /** OPFS path. Defaults to "meshtastic.db". */ + databasePath?: string; +} + +export type SqlocalDb = BaseSQLiteDatabase< + "async" | "sync", + unknown, + typeof schema +>; + +export interface OpenedSqlocalDb { + db: SqlocalDb; + /** + * Where the database actually lives. sqlocal falls back to "memory" without + * throwing when OPFS can't be used (no cross-origin isolation, a private + * window), and nothing written then survives a reload. + */ + storageType: string; + /** True when the database is saved to OPFS. */ + persistent: boolean; +} + +/** + * Opens (or creates) the OPFS-backed SQLite database, applies migrations, and + * returns a Drizzle client typed against the schema, along with where sqlocal + * ended up storing it. One instance per origin — sqlocal serializes writes + * via Web Locks under the hood. + */ +export async function openSqlocalDb( + options: CreateSqlocalDbOptions = {}, +): Promise { + const databasePath = options.databasePath ?? "meshtastic.db"; + const client = new SQLocalDrizzle({ databasePath }); + const { driver, batchDriver, sql } = client; + const db: SqlocalDb = drizzle(driver, batchDriver, { + schema, + casing: "snake_case", + }); + + await applyMigrations(sql); + + const { storageType = "memory" } = await client.getDatabaseInfo(); + return { db, storageType, persistent: storageType === "opfs" }; +} + +/** {@link openSqlocalDb} for callers that only need the Drizzle client. */ +export async function createSqlocalDb( + options: CreateSqlocalDbOptions = {}, +): Promise { + return (await openSqlocalDb(options)).db; +} + +type RawSql = ( + query: TemplateStringsArray, + ...values: ReadonlyArray +) => Promise; + +export const isDuplicateColumn = (e: unknown): boolean => + /duplicate column name/i.test(e instanceof Error ? e.message : String(e)); + +async function applyMigrations(sql: RawSql): Promise { + await sql`CREATE TABLE IF NOT EXISTS _schema (version INTEGER PRIMARY KEY)`; + const current = latestVersion( + await sql`SELECT version FROM _schema ORDER BY version DESC LIMIT 1`, + ); + for (const migration of MIGRATIONS) { + if (migration.version <= current) continue; + for (const statement of migration.sql) { + try { + await sql(literal(statement)); + } catch (e) { + // Another tab opening the same database can apply an ALTER TABLE + // first; the column it adds is the one we wanted. + if (!isDuplicateColumn(e)) throw e; + } + } + await sql`INSERT OR IGNORE INTO _schema (version) VALUES (${migration.version})`; + } +} + +function literal(statement: string): TemplateStringsArray { + return Object.assign([statement], { raw: [statement] }); +} + +function latestVersion(rows: unknown): number { + if (!Array.isArray(rows)) return 0; + const first: unknown = rows[0]; + if (typeof first !== "object" || first === null || !("version" in first)) { + return 0; + } + return typeof first.version === "number" ? first.version : 0; +} diff --git a/apps/web/src/core/storage/drafts.test.ts b/apps/web/src/core/storage/drafts.test.ts new file mode 100644 index 000000000..2690ee8b8 --- /dev/null +++ b/apps/web/src/core/storage/drafts.test.ts @@ -0,0 +1,111 @@ +import { Types } from "@core/protobuf.ts"; +import { beforeEach, describe, expect, it } from "vitest"; +import type { SqlocalDb } from "./db.ts"; +import { SqlocalDraftRepository } from "./drafts.ts"; +import { createMemoryDb } from "./memoryDb.ts"; +import type { ConversationKey } from "./types.ts"; + +describe("SqlocalDraftRepository", () => { + let db: SqlocalDb; + let repo: SqlocalDraftRepository; + + beforeEach(async () => { + db = await createMemoryDb(); + repo = new SqlocalDraftRepository(db, { deviceId: 1 }); + }); + + it("save then load returns the same text", async () => { + await repo.save( + { kind: "channel", channel: Types.ChannelNumber.Primary }, + "hello", + ); + expect( + await repo.load({ + kind: "channel", + channel: Types.ChannelNumber.Primary, + }), + ).toBe("hello"); + }); + + it("save with empty text deletes the row", async () => { + await repo.save({ kind: "direct", peer: 7 }, "wip"); + await repo.save({ kind: "direct", peer: 7 }, ""); + expect(await repo.load({ kind: "direct", peer: 7 })).toBe(""); + }); + + it("clear removes the row", async () => { + await repo.save( + { kind: "channel", channel: Types.ChannelNumber.Channel1 }, + "draft", + ); + await repo.clear({ + kind: "channel", + channel: Types.ChannelNumber.Channel1, + }); + expect( + await repo.load({ + kind: "channel", + channel: Types.ChannelNumber.Channel1, + }), + ).toBe(""); + }); + + it("upsert overwrites prior text without throwing", async () => { + await repo.save({ kind: "direct", peer: 12 }, "first"); + await repo.save({ kind: "direct", peer: 12 }, "second"); + expect(await repo.load({ kind: "direct", peer: 12 })).toBe("second"); + }); + + it("scoped per device_id", async () => { + const repoB = new SqlocalDraftRepository(db, { deviceId: 2 }); + await repo.save( + { kind: "channel", channel: Types.ChannelNumber.Primary }, + "from-1", + ); + await repoB.save( + { kind: "channel", channel: Types.ChannelNumber.Primary }, + "from-2", + ); + expect( + await repo.load({ + kind: "channel", + channel: Types.ChannelNumber.Primary, + }), + ).toBe("from-1"); + expect( + await repoB.load({ + kind: "channel", + channel: Types.ChannelNumber.Primary, + }), + ).toBe("from-2"); + }); + + it("loadAll returns all drafts for the device", async () => { + await repo.save( + { kind: "channel", channel: Types.ChannelNumber.Primary }, + "a", + ); + await repo.save({ kind: "direct", peer: 99 }, "b"); + const all = await repo.loadAll(); + expect(all.length).toBe(2); + }); + + it("setScope moves reads and writes to the new scope", async () => { + const channel: ConversationKey = { + kind: "channel", + channel: Types.ChannelNumber.Primary, + }; + await repo.save(channel, "old"); + + repo.setScope(0xabcd); + expect(await repo.load(channel)).toBe(""); + expect(await repo.loadAll()).toEqual([]); + await repo.save(channel, "new"); + await repo.save({ kind: "direct", peer: 7 }, "dm"); + await repo.clear({ kind: "direct", peer: 7 }); + expect(await repo.loadAll()).toEqual([{ key: channel, text: "new" }]); + + const old = new SqlocalDraftRepository(db, { deviceId: 1 }); + expect(await old.load(channel)).toBe("old"); + }); +}); diff --git a/apps/web/src/core/storage/drafts.ts b/apps/web/src/core/storage/drafts.ts new file mode 100644 index 000000000..b71d9b597 --- /dev/null +++ b/apps/web/src/core/storage/drafts.ts @@ -0,0 +1,92 @@ +import { and, eq, sql } from "drizzle-orm"; +import type { SqlocalDb } from "./db.ts"; +import { drafts } from "./schema.ts"; +import { + type ConversationKey, + conversationKeyString, + type DraftRepository, + parseConversationKey, +} from "./types.ts"; + +export interface SqlocalDraftRepositoryOptions { + deviceId: number; +} + +/** + * Per-conversation draft persistence. Single row per (device_id, + * conversation_key); upsert on save, delete on clear or empty save. + */ +export class SqlocalDraftRepository implements DraftRepository { + private readonly db: SqlocalDb; + private deviceId: number; + + constructor(db: SqlocalDb, options: SqlocalDraftRepositoryOptions) { + this.db = db; + this.deviceId = options.deviceId; + } + + /** + * Points every later read and write at another `device_id`. Rows under the + * old one are left as they are. + */ + setScope(deviceId: number): void { + this.deviceId = deviceId; + } + + async load(key: ConversationKey): Promise { + const rows = await this.db + .select({ text: drafts.text }) + .from(drafts) + .where( + and( + eq(drafts.deviceId, this.deviceId), + eq(drafts.conversationKey, conversationKeyString(key)), + ), + ) + .limit(1); + return rows[0]?.text ?? ""; + } + + async save(key: ConversationKey, text: string): Promise { + if (text.length === 0) { + await this.clear(key); + return; + } + await this.db + .insert(drafts) + .values({ + deviceId: this.deviceId, + conversationKey: conversationKeyString(key), + text, + updatedAt: Date.now(), + }) + .onConflictDoUpdate({ + target: [drafts.deviceId, drafts.conversationKey], + set: { text: sql`excluded.text`, updatedAt: sql`excluded.updated_at` }, + }); + } + + async clear(key: ConversationKey): Promise { + await this.db + .delete(drafts) + .where( + and( + eq(drafts.deviceId, this.deviceId), + eq(drafts.conversationKey, conversationKeyString(key)), + ), + ); + } + + async loadAll(): Promise< + ReadonlyArray<{ key: ConversationKey; text: string }> + > { + const rows = await this.db + .select({ conversationKey: drafts.conversationKey, text: drafts.text }) + .from(drafts) + .where(eq(drafts.deviceId, this.deviceId)); + return rows.map((r) => ({ + key: parseConversationKey(r.conversationKey), + text: r.text, + })); + } +} diff --git a/apps/web/src/core/storage/memoryDb.ts b/apps/web/src/core/storage/memoryDb.ts new file mode 100644 index 000000000..0ba8ca141 --- /dev/null +++ b/apps/web/src/core/storage/memoryDb.ts @@ -0,0 +1,26 @@ +import { drizzle } from "drizzle-orm/sql-js"; +import initSqlJs from "sql.js"; +import type { SqlocalDb } from "./db.ts"; +import * as schema from "./schema.ts"; +import { MIGRATIONS } from "./schema.ts"; + +/** + * In-memory database backed by sql.js, for tests and other Node contexts. + * Same Drizzle interface as the production sqlocal connection so repository + * code is portable between browser and test runs. + */ +export async function createMemoryDb(): Promise { + const SQL = await initSqlJs({}); + const sqlite = new SQL.Database(); + + for (const migration of MIGRATIONS) { + for (const statement of migration.sql) { + sqlite.run(statement); + } + sqlite.run("INSERT OR IGNORE INTO _schema (version) VALUES (?)", [ + migration.version, + ]); + } + + return drizzle(sqlite, { schema, casing: "snake_case" }); +} diff --git a/apps/web/src/core/storage/messages.test.ts b/apps/web/src/core/storage/messages.test.ts new file mode 100644 index 000000000..5510c14d8 --- /dev/null +++ b/apps/web/src/core/storage/messages.test.ts @@ -0,0 +1,216 @@ +import { Types } from "@core/protobuf.ts"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { MultiTabCoordinator } from "./coordinator.ts"; +import type { SqlocalDb } from "./db.ts"; +import { createMemoryDb } from "./memoryDb.ts"; +import { SqlocalMessageRepository } from "./messages.ts"; +import { type ConversationKey, type Message, MessageState } from "./types.ts"; + +function msg(id: number, ms: number, text = "t"): Message { + return { + id, + from: 1, + to: 0xffffffff, + channel: Types.ChannelNumber.Primary, + rxTime: new Date(ms), + type: "broadcast", + text, + state: MessageState.Ack, + }; +} + +describe("SqlocalMessageRepository (sql.js test driver)", () => { + let db: SqlocalDb; + let repo: SqlocalMessageRepository; + + beforeEach(async () => { + db = await createMemoryDb(); + repo = new SqlocalMessageRepository(db, { deviceId: 1 }); + }); + + it("loadRecent returns the tail in chronological order", async () => { + await repo.appendBatch([msg(1, 1000), msg(2, 2000), msg(3, 3000)]); + const out = await repo.loadRecent( + { kind: "channel", channel: Types.ChannelNumber.Primary }, + 2, + ); + expect(out.map((m) => m.id)).toEqual([2, 3]); + }); + + it("loadBefore paginates older messages", async () => { + await repo.appendBatch([ + msg(1, 1000), + msg(2, 2000), + msg(3, 3000), + msg(4, 4000), + ]); + const out = await repo.loadBefore( + { kind: "channel", channel: Types.ChannelNumber.Primary }, + new Date(3000), + 10, + ); + expect(out.map((m) => m.id)).toEqual([1, 2]); + }); + + it("round-trips how a message was received, keeping 0 readings", async () => { + await repo.append({ + ...msg(7, 1000), + snr: 0, + rssi: -97, + hopsAway: 0, + viaMqtt: true, + transport: 0, + }); + await repo.append(msg(8, 2000)); + const [withRadio, without] = await repo.loadRecent( + { kind: "channel", channel: Types.ChannelNumber.Primary }, + 2, + ); + expect(withRadio).toMatchObject({ + snr: 0, + rssi: -97, + hopsAway: 0, + viaMqtt: true, + transport: 0, + }); + expect(without?.snr).toBeUndefined(); + expect(without?.rssi).toBeUndefined(); + expect(without?.hopsAway).toBeUndefined(); + expect(without?.viaMqtt).toBeUndefined(); + expect(without?.transport).toBeUndefined(); + }); + + it("files a message under the conversation it is given", async () => { + const sent: Message = { + ...msg(5, 1000, "hi"), + from: 1, + to: 2, + type: "direct", + }; + await repo.append(sent, { kind: "direct", peer: 2 }); + expect( + (await repo.loadRecent({ kind: "direct", peer: 2 }, 10)).map((m) => m.id), + ).toEqual([5]); + expect(await repo.loadRecent({ kind: "direct", peer: 1 }, 10)).toEqual([]); + }); + + it("refiles sent direct messages filed under our own node", async () => { + const direct = (id: number, from: number, to: number): Message => ({ + ...msg(id, id * 1000), + from, + to, + type: "direct", + }); + // What older versions wrote: everything under direct:. + await repo.appendBatch([ + direct(1, 1, 2), // sent by us (node 1) to 2: misfiled + direct(2, 2, 1), // received from 2: already right + direct(3, 1, 1), // a note to ourselves: stays put + ]); + + expect(await repo.refileSentDirect(1)).toBe(1); + expect( + (await repo.loadRecent({ kind: "direct", peer: 2 }, 10)).map((m) => m.id), + ).toEqual([1, 2]); + expect( + (await repo.loadRecent({ kind: "direct", peer: 1 }, 10)).map((m) => m.id), + ).toEqual([3]); + expect(await repo.refileSentDirect(1)).toBe(0); + }); + + it("updateState mutates the matching row", async () => { + await repo.append(msg(42, 1000)); + await repo.updateState(42, MessageState.Failed); + const [found] = await repo.loadRecent( + { kind: "channel", channel: Types.ChannelNumber.Primary }, + 1, + ); + expect(found?.state).toBe(MessageState.Failed); + }); + + it("prune enforces maxPerBucket", async () => { + await repo.appendBatch([ + msg(1, 1000), + msg(2, 2000), + msg(3, 3000), + msg(4, 4000), + ]); + await repo.prune({ maxPerBucket: 2 }); + const out = await repo.loadRecent( + { kind: "channel", channel: Types.ChannelNumber.Primary }, + 10, + ); + expect(out.map((m) => m.id)).toEqual([3, 4]); + }); + + it("prune enforces olderThanMs", async () => { + const now = Date.now(); + await repo.appendBatch([ + msg(1, now - 1000 * 60 * 60 * 24 * 10), + msg(2, now), + ]); + await repo.prune({ olderThanMs: 1000 * 60 * 60 * 24 }); + const out = await repo.loadRecent( + { kind: "channel", channel: Types.ChannelNumber.Primary }, + 10, + ); + expect(out.map((m) => m.id)).toEqual([2]); + }); + + it("isolates devices via device_id scoping", async () => { + const repoB = new SqlocalMessageRepository(db, { deviceId: 2 }); + await repo.append(msg(1, 1000, "from-1")); + await repoB.append(msg(2, 2000, "from-2")); + const a = await repo.loadRecent( + { kind: "channel", channel: Types.ChannelNumber.Primary }, + 10, + ); + const b = await repoB.loadRecent( + { kind: "channel", channel: Types.ChannelNumber.Primary }, + 10, + ); + expect(a.map((m) => m.text)).toEqual(["from-1"]); + expect(b.map((m) => m.text)).toEqual(["from-2"]); + }); + + it("setScope moves reads, writes and pruning to the new scope", async () => { + const channel: ConversationKey = { + kind: "channel", + channel: Types.ChannelNumber.Primary, + }; + await repo.appendBatch([msg(1, 1000, "old"), msg(2, 2000, "old")]); + + repo.setScope(0xabcd); + expect(await repo.loadRecent(channel, 10)).toEqual([]); + await repo.append(msg(3, 3000, "new"), channel); + await repo.append(msg(4, 4000, "new"), channel); + await repo.prune({ maxPerBucket: 1 }); + await repo.updateState(1, MessageState.Failed); + expect( + (await repo.loadRecent(channel, 10)).map((m) => [m.id, m.text]), + ).toEqual([[4, "new"]]); + + const old = new SqlocalMessageRepository(db, { deviceId: 1 }); + const untouched = await old.loadRecent(channel, 10); + expect(untouched.map((m) => m.id)).toEqual([1, 2]); + expect(untouched.map((m) => m.state)).toEqual([ + MessageState.Ack, + MessageState.Ack, + ]); + }); + + it("broadcasts changes under the current scope", async () => { + const coordinator = new MultiTabCoordinator(); + const broadcast = vi.spyOn(coordinator, "broadcast"); + const scoped = new SqlocalMessageRepository(db, { + deviceId: 1, + coordinator, + }); + scoped.setScope(0xabcd); + await scoped.append(msg(5, 5000)); + expect(broadcast.mock.calls).toEqual([ + [{ kind: "messages-changed", deviceId: 0xabcd, key: "channel:0" }], + ]); + coordinator.close(); + }); +}); diff --git a/apps/web/src/core/storage/messages.ts b/apps/web/src/core/storage/messages.ts new file mode 100644 index 000000000..4b56d226b --- /dev/null +++ b/apps/web/src/core/storage/messages.ts @@ -0,0 +1,245 @@ +import { and, desc, eq, lt, ne, sql } from "drizzle-orm"; +import type { MultiTabCoordinator } from "./coordinator.ts"; +import type { SqlocalDb } from "./db.ts"; +import { messages } from "./schema.ts"; +import { + type ConversationKey, + conversationKeyString, + inferConversation, + type Message, + type MessageDeliveryPatch, + type MessageRepository, + MessageState, + type RetentionPolicy, +} from "./types.ts"; + +export interface SqlocalMessageRepositoryOptions { + /** + * The `device_id` rows are stored and read under: the storage scope, e.g. + * the radio's node number. Change it later with `setScope`. + */ + deviceId: number; + /** Optional cross-tab coordinator. If omitted, mutations are silent. */ + coordinator?: MultiTabCoordinator; +} + +export class SqlocalMessageRepository implements MessageRepository { + private readonly db: SqlocalDb; + private deviceId: number; + private readonly coordinator: MultiTabCoordinator | undefined; + + constructor(db: SqlocalDb, options: SqlocalMessageRepositoryOptions) { + this.db = db; + this.deviceId = options.deviceId; + this.coordinator = options.coordinator; + } + + /** + * Points every later read and write at another `device_id`. Rows under the + * old one are left as they are. + */ + setScope(deviceId: number): void { + this.deviceId = deviceId; + } + + async loadRecent(key: ConversationKey, limit: number): Promise { + const rows = await this.db + .select() + .from(messages) + .where(this.scoped(key)) + .orderBy(desc(messages.rxTime)) + .limit(limit); + return rows.reverse().map(rowToMessage); + } + + async loadBefore( + key: ConversationKey, + cursor: Date, + limit: number, + ): Promise { + const rows = await this.db + .select() + .from(messages) + .where(and(this.scoped(key), lt(messages.rxTime, cursor.getTime()))) + .orderBy(desc(messages.rxTime)) + .limit(limit); + return rows.reverse().map(rowToMessage); + } + + async append(message: Message, key?: ConversationKey): Promise { + await this.insert([ + messageToRow(this.deviceId, message, key ?? inferConversation(message)), + ]); + } + + async appendBatch(input: ReadonlyArray): Promise { + await this.insert( + input.map((m) => messageToRow(this.deviceId, m, inferConversation(m))), + ); + } + + async refileSentDirect(localNodeNum: number): Promise { + const moved = await this.db + .update(messages) + .set({ conversationKey: sql`'direct:' || ${messages.toNode}` }) + .where( + and( + eq(messages.deviceId, this.deviceId), + eq(messages.type, "direct"), + eq(messages.fromNode, localNodeNum), + ne(messages.toNode, localNodeNum), + eq( + messages.conversationKey, + conversationKeyString({ kind: "direct", peer: localNodeNum }), + ), + ), + ) + .returning({ conversationKey: messages.conversationKey }); + this.notify(moved.map((r) => r.conversationKey)); + return moved.length; + } + + private async insert(rows: MessageRow[]): Promise { + if (rows.length === 0) return; + await this.db.insert(messages).values(rows).onConflictDoNothing(); + this.notify(rows.map((r) => r.conversationKey)); + } + + async updateDelivery(id: number, patch: MessageDeliveryPatch): Promise { + const set: Partial = {}; + if ("state" in patch) set.state = patch.state; + if ("ackProof" in patch) set.ackProof = patch.ackProof ?? null; + if ("routingError" in patch) set.routingError = patch.routingError ?? null; + if ("relays" in patch) set.relays = patch.relays ?? null; + if (Object.keys(set).length === 0) return; + await this.db + .update(messages) + .set(set) + .where(and(eq(messages.deviceId, this.deviceId), eq(messages.id, id))); + } + + async remove(id: number): Promise { + await this.db + .delete(messages) + .where(and(eq(messages.deviceId, this.deviceId), eq(messages.id, id))); + } + + async updateState(id: number, state: MessageState): Promise { + await this.db + .update(messages) + .set({ state }) + .where(and(eq(messages.deviceId, this.deviceId), eq(messages.id, id))); + } + + async prune(policy: RetentionPolicy): Promise { + if (policy.olderThanMs !== undefined) { + const cutoff = Date.now() - policy.olderThanMs; + await this.db + .delete(messages) + .where( + and( + eq(messages.deviceId, this.deviceId), + lt(messages.rxTime, cutoff), + ), + ); + } + if (policy.maxPerBucket !== undefined) { + // Keep the newest N per (device, conversation_key). SQLite has no + // straightforward per-group LIMIT, so use a windowed delete. + await this.db.run(sql` + DELETE FROM messages + WHERE device_id = ${this.deviceId} + AND rowid IN ( + SELECT rowid FROM ( + SELECT rowid, + row_number() OVER ( + PARTITION BY conversation_key + ORDER BY rx_time DESC, id DESC + ) AS rn + FROM messages + WHERE device_id = ${this.deviceId} + ) + WHERE rn > ${policy.maxPerBucket} + ) + `); + } + } + + async clearConversation(key: ConversationKey): Promise { + await this.db.delete(messages).where(this.scoped(key)); + } + + async clear(): Promise { + await this.db.delete(messages).where(eq(messages.deviceId, this.deviceId)); + } + + private scoped(key: ConversationKey) { + return and( + eq(messages.deviceId, this.deviceId), + eq(messages.conversationKey, conversationKeyString(key)), + ); + } + + private notify(keys: ReadonlyArray): void { + if (!this.coordinator) return; + for (const key of new Set(keys)) { + this.coordinator.broadcast({ + kind: "messages-changed", + deviceId: this.deviceId, + key, + }); + } + } +} + +type MessageRow = typeof messages.$inferInsert; + +function rowToMessage(row: MessageRow): Message { + return { + id: row.id, + from: row.fromNode, + to: row.toNode, + channel: row.channel, + rxTime: new Date(row.rxTime), + type: row.type, + text: row.text, + state: row.state, + signed: row.signed ?? undefined, + ackProof: row.ackProof ?? undefined, + routingError: row.routingError ?? undefined, + relays: row.relays ?? undefined, + snr: row.snr ?? undefined, + rssi: row.rssi ?? undefined, + hopsAway: row.hopsAway ?? undefined, + viaMqtt: row.viaMqtt ?? undefined, + transport: row.transport ?? undefined, + }; +} + +function messageToRow( + deviceId: number, + message: Message, + conv: ConversationKey, +): MessageRow { + return { + id: message.id, + deviceId, + conversationKey: conversationKeyString(conv), + fromNode: message.from, + toNode: message.to, + channel: message.channel, + rxTime: message.rxTime.getTime(), + type: message.type, + text: message.text, + state: message.state, + signed: message.signed ?? null, + ackProof: message.ackProof ?? null, + routingError: message.routingError ?? null, + relays: message.relays ?? null, + snr: message.snr ?? null, + rssi: message.rssi ?? null, + hopsAway: message.hopsAway ?? null, + viaMqtt: message.viaMqtt ?? null, + transport: message.transport ?? null, + }; +} diff --git a/apps/web/src/core/storage/migrations.test.ts b/apps/web/src/core/storage/migrations.test.ts new file mode 100644 index 000000000..dd5a813a3 --- /dev/null +++ b/apps/web/src/core/storage/migrations.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it } from "vitest"; +import initSqlJs, { type Database } from "sql.js"; +import { isDuplicateColumn } from "./db.ts"; +import { MIGRATIONS } from "./schema.ts"; + +async function freshSqlite() { + const SQL = await initSqlJs({}); + return new SQL.Database(); +} + +const first = MIGRATIONS[0] ?? { version: 0, sql: [] }; +const last = MIGRATIONS.at(-1)?.sql[0] ?? ""; + +function column(rows: T[][] | undefined, index: number): T[] { + return (rows ?? []) + .map((row) => row[index]) + .flatMap((v) => (v === undefined ? [] : [v])); +} + +function names(db: Database, query: string): unknown[] { + return column(db.exec(query)[0]?.values, 0); +} + +describe("MIGRATIONS", () => { + it("first migration creates messages, nodes, telemetry, _schema", async () => { + const db = await freshSqlite(); + for (const stmt of first.sql) db.run(stmt); + db.run("INSERT INTO _schema (version) VALUES (?)", [first.version]); + + const tables = names( + db, + "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name", + ); + expect(tables).toEqual( + expect.arrayContaining(["_schema", "messages", "nodes", "telemetry"]), + ); + + const version = db.exec("SELECT MAX(version) FROM _schema")[0] + ?.values[0]?.[0]; + expect(version).toBe(first.version); + }); + + it("messages indexes are present after v1", async () => { + const db = await freshSqlite(); + for (const stmt of first.sql) db.run(stmt); + const indexes = names( + db, + "SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='messages' ORDER BY name", + ); + expect(indexes).toEqual( + expect.arrayContaining([ + "idx_messages_conv_rxtime", + "idx_messages_pending", + "messages_pk", + ]), + ); + }); + + it("re-applying v1 statements is idempotent (CREATE IF NOT EXISTS)", async () => { + const db = await freshSqlite(); + for (const stmt of first.sql) db.run(stmt); + expect(() => { + for (const stmt of first.sql) db.run(stmt); + }).not.toThrow(); + }); + + it("v3 adds the signed and ack_proof message columns", async () => { + const db = await freshSqlite(); + for (const migration of MIGRATIONS) { + for (const stmt of migration.sql) db.run(stmt); + } + const columns = column( + db.exec("PRAGMA table_info(messages)")[0]?.values, + 1, + ); + expect(columns).toEqual(expect.arrayContaining(["signed", "ack_proof"])); + }); + + it("v4 adds the received-signal message columns", async () => { + const db = await freshSqlite(); + for (const migration of MIGRATIONS) { + for (const stmt of migration.sql) db.run(stmt); + } + const columns = ( + db.exec("PRAGMA table_info(messages)")[0]?.values ?? [] + ).map((row) => [row[1], row[2]]); + expect(columns).toEqual( + expect.arrayContaining([ + ["snr", "REAL"], + ["rssi", "INTEGER"], + ["hops_away", "INTEGER"], + ["via_mqtt", "INTEGER"], + ["transport", "INTEGER"], + ]), + ); + }); + + it("a second ALTER TABLE fails with an error isDuplicateColumn recognises", async () => { + const db = await freshSqlite(); + for (const migration of MIGRATIONS) { + for (const stmt of migration.sql) db.run(stmt); + } + let error: unknown; + try { + db.run(last); + } catch (e) { + error = e; + } + expect(isDuplicateColumn(error)).toBe(true); + }); +}); diff --git a/apps/web/src/core/storage/nodes.test.ts b/apps/web/src/core/storage/nodes.test.ts new file mode 100644 index 000000000..62abff359 --- /dev/null +++ b/apps/web/src/core/storage/nodes.test.ts @@ -0,0 +1,96 @@ +import { create } from "@bufbuild/protobuf"; +import { Protobuf } from "@core/protobuf.ts"; +import { beforeEach, describe, expect, it } from "vitest"; +import type { SqlocalDb } from "./db.ts"; +import { createMemoryDb } from "./memoryDb.ts"; +import { SqlocalNodesRepository } from "./nodes.ts"; +import type { Node } from "./types.ts"; + +function node(num: number, partial: Partial = {}): Node { + return { + num, + isFavorite: false, + isIgnored: false, + user: undefined, + position: undefined, + deviceMetrics: undefined, + lastHeard: undefined, + snr: undefined, + ...partial, + }; +} + +describe("SqlocalNodesRepository", () => { + let db: SqlocalDb; + let repo: SqlocalNodesRepository; + + beforeEach(async () => { + db = await createMemoryDb(); + repo = new SqlocalNodesRepository(db, { deviceId: 1 }); + }); + + it("upsert + loadAll round-trip", async () => { + await repo.upsert(node(1, { isFavorite: true, lastHeard: 1000 })); + await repo.upsert(node(2, { snr: 5 })); + const all = await repo.loadAll(); + expect(all.map((n) => n.num).sort()).toEqual([1, 2]); + expect((await repo.get(1))?.isFavorite).toBe(true); + }); + + it("upsert overwrites prior row", async () => { + await repo.upsert(node(7, { isFavorite: false })); + await repo.upsert(node(7, { isFavorite: true })); + expect((await repo.get(7))?.isFavorite).toBe(true); + }); + + it("preserves user proto across save + load", async () => { + const user = create(Protobuf.Mesh.UserSchema, { + id: "!abcdef00", + longName: "Test Node", + shortName: "TST", + }); + await repo.upsert(node(42, { user })); + const loaded = await repo.get(42); + expect(loaded?.user?.id).toBe("!abcdef00"); + expect(loaded?.user?.longName).toBe("Test Node"); + }); + + it("remove deletes the row", async () => { + await repo.upsert(node(9)); + await repo.remove(9); + expect(await repo.get(9)).toBeUndefined(); + }); + + it("clear wipes all rows for the scoped device", async () => { + await repo.upsertBatch([node(1), node(2), node(3)]); + await repo.clear(); + expect((await repo.loadAll()).length).toBe(0); + }); + + it("scoped per device_id", async () => { + const repoB = new SqlocalNodesRepository(db, { deviceId: 2 }); + await repo.upsert(node(1, { isFavorite: true })); + await repoB.upsert(node(1, { isFavorite: false })); + expect((await repo.get(1))?.isFavorite).toBe(true); + expect((await repoB.get(1))?.isFavorite).toBe(false); + }); + + it("setScope moves reads and writes to the new scope", async () => { + await repo.upsert(node(1, { snr: 1 })); + await repo.upsert(node(2)); + + repo.setScope(0xabcd); + expect(await repo.loadAll()).toEqual([]); + expect(await repo.get(1)).toBeUndefined(); + await repo.upsert(node(1, { snr: 9 })); + await repo.remove(2); + expect((await repo.loadAll()).map((n) => [n.num, n.snr])).toEqual([[1, 9]]); + await repo.clear(); + + const old = new SqlocalNodesRepository(db, { deviceId: 1 }); + expect((await old.loadAll()).map((n) => [n.num, n.snr]).sort()).toEqual([ + [1, 1], + [2, undefined], + ]); + }); +}); diff --git a/apps/web/src/core/storage/nodes.ts b/apps/web/src/core/storage/nodes.ts new file mode 100644 index 000000000..f7c6d67a4 --- /dev/null +++ b/apps/web/src/core/storage/nodes.ts @@ -0,0 +1,147 @@ +import { fromBinary, toBinary } from "@bufbuild/protobuf"; +import { Protobuf } from "@core/protobuf.ts"; +import { and, eq } from "drizzle-orm"; +import type { SqlocalDb } from "./db.ts"; +import { nodes } from "./schema.ts"; +import { + base64Decode, + base64Encode, + type Node, + type NodesRepository, +} from "./types.ts"; + +export interface SqlocalNodesRepositoryOptions { + deviceId: number; +} + +/** + * Persists the snapshot of the device's NodeDB. user/position/metrics are + * stored as base64-encoded protobuf bytes — round-trip safe across schema + * additions because the wire shape is the source of truth. + */ +export class SqlocalNodesRepository implements NodesRepository { + private readonly db: SqlocalDb; + private deviceId: number; + + constructor(db: SqlocalDb, options: SqlocalNodesRepositoryOptions) { + this.db = db; + this.deviceId = options.deviceId; + } + + /** + * Points every later read and write at another `device_id`. Rows under the + * old one are left as they are. + */ + setScope(deviceId: number): void { + this.deviceId = deviceId; + } + + async loadAll(): Promise { + const rows = await this.db + .select() + .from(nodes) + .where(eq(nodes.deviceId, this.deviceId)); + return rows.map(rowToNode); + } + + async get(nodeNum: number): Promise { + const rows = await this.db + .select() + .from(nodes) + .where(and(eq(nodes.deviceId, this.deviceId), eq(nodes.num, nodeNum))) + .limit(1); + return rows[0] ? rowToNode(rows[0]) : undefined; + } + + async upsert(node: Node): Promise { + await this.upsertBatch([node]); + } + + async upsertBatch(input: ReadonlyArray): Promise { + if (input.length === 0) return; + for (const node of input) { + const row = nodeToRow(this.deviceId, node); + await this.db + .insert(nodes) + .values(row) + .onConflictDoUpdate({ + target: [nodes.deviceId, nodes.num], + set: { + lastHeard: row.lastHeard, + snr: row.snr, + isFavorite: row.isFavorite, + isIgnored: row.isIgnored, + userJson: row.userJson, + positionJson: row.positionJson, + metricsJson: row.metricsJson, + }, + }); + } + } + + async remove(nodeNum: number): Promise { + await this.db + .delete(nodes) + .where(and(eq(nodes.deviceId, this.deviceId), eq(nodes.num, nodeNum))); + } + + async clear(): Promise { + await this.db.delete(nodes).where(eq(nodes.deviceId, this.deviceId)); + } +} + +interface NodeRow { + deviceId: number; + num: number; + lastHeard: number | null; + snr: number | null; + isFavorite: boolean; + isIgnored: boolean; + userJson: string | null; + positionJson: string | null; + metricsJson: string | null; +} + +function rowToNode(row: NodeRow): Node { + return { + num: row.num, + user: row.userJson + ? fromBinary(Protobuf.Mesh.UserSchema, base64Decode(row.userJson)) + : undefined, + position: row.positionJson + ? fromBinary(Protobuf.Mesh.PositionSchema, base64Decode(row.positionJson)) + : undefined, + deviceMetrics: row.metricsJson + ? fromBinary( + Protobuf.Telemetry.DeviceMetricsSchema, + base64Decode(row.metricsJson), + ) + : undefined, + lastHeard: row.lastHeard ?? undefined, + snr: row.snr ?? undefined, + isFavorite: row.isFavorite, + isIgnored: row.isIgnored, + }; +} + +function nodeToRow(deviceId: number, node: Node): NodeRow { + return { + deviceId, + num: node.num, + lastHeard: node.lastHeard ?? null, + snr: node.snr ?? null, + isFavorite: node.isFavorite, + isIgnored: node.isIgnored, + userJson: node.user + ? base64Encode(toBinary(Protobuf.Mesh.UserSchema, node.user)) + : null, + positionJson: node.position + ? base64Encode(toBinary(Protobuf.Mesh.PositionSchema, node.position)) + : null, + metricsJson: node.deviceMetrics + ? base64Encode( + toBinary(Protobuf.Telemetry.DeviceMetricsSchema, node.deviceMetrics), + ) + : null, + }; +} diff --git a/apps/web/src/core/storage/schema.ts b/apps/web/src/core/storage/schema.ts new file mode 100644 index 000000000..4d1713aa6 --- /dev/null +++ b/apps/web/src/core/storage/schema.ts @@ -0,0 +1,216 @@ +import type { Protobuf } from "@core/protobuf.ts"; +import { + index, + integer, + primaryKey, + real, + sqliteTable, + text, +} from "drizzle-orm/sqlite-core"; +import { MessageState } from "./types.ts"; + +export const messages = sqliteTable( + "messages", + { + /** + * Composite primary key would be ideal, but Meshtastic packet IDs are + * already 32-bit random values; collisions across devices are rare. We + * scope reads by (device_id, conversation_key) so collisions only + * matter within a single device's history. + */ + id: integer("id").notNull(), + deviceId: integer("device_id").notNull(), + conversationKey: text("conversation_key").notNull(), + fromNode: integer("from_node").notNull(), + toNode: integer("to_node").notNull(), + channel: integer("channel").notNull(), + rxTime: integer("rx_time").notNull(), + type: text("type", { enum: ["broadcast", "direct"] }).notNull(), + text: text("text").notNull(), + state: text("state", { + enum: [ + MessageState.Pending, + MessageState.Delivered, + MessageState.Ack, + MessageState.Failed, + ], + }).notNull(), + signed: integer("signed", { mode: "boolean" }), + ackProof: + integer("ack_proof").$type(), + routingError: integer("routing_error").$type(), + relays: integer("relays"), + snr: real("snr"), + rssi: integer("rssi"), + hopsAway: integer("hops_away"), + viaMqtt: integer("via_mqtt", { mode: "boolean" }), + transport: + integer("transport").$type(), + }, + (t) => ({ + pk: index("messages_pk").on(t.deviceId, t.id), + convRxTime: index("idx_messages_conv_rxtime").on( + t.deviceId, + t.conversationKey, + t.rxTime, + ), + pending: index("idx_messages_pending").on(t.deviceId, t.state), + }), +); + +export type MessageRow = typeof messages.$inferSelect; +export type MessageInsert = typeof messages.$inferInsert; + +export const drafts = sqliteTable( + "drafts", + { + deviceId: integer("device_id").notNull(), + conversationKey: text("conversation_key").notNull(), + text: text("text").notNull(), + updatedAt: integer("updated_at").notNull(), + }, + (t) => ({ + pk: primaryKey({ columns: [t.deviceId, t.conversationKey] }), + }), +); + +export type DraftRow = typeof drafts.$inferSelect; +export type DraftInsert = typeof drafts.$inferInsert; + +/** + * Snapshot of the device's NodeDB. Position / metrics / user are stored as + * JSON blobs (proto-shape) — slice infrastructure mappers are responsible + * for serialization. Last-heard duplicates the column for sortable indexes. + */ +export const nodes = sqliteTable( + "nodes", + { + deviceId: integer("device_id").notNull(), + num: integer("num").notNull(), + lastHeard: integer("last_heard"), + snr: integer("snr"), + isFavorite: integer("is_favorite", { mode: "boolean" }) + .notNull() + .default(false), + isIgnored: integer("is_ignored", { mode: "boolean" }) + .notNull() + .default(false), + userJson: text("user_json"), + positionJson: text("position_json"), + metricsJson: text("metrics_json"), + }, + (t) => ({ + pk: primaryKey({ columns: [t.deviceId, t.num] }), + lastHeardIdx: index("idx_nodes_last_heard").on(t.deviceId, t.lastHeard), + }), +); + +export type NodeRow = typeof nodes.$inferSelect; +export type NodeInsert = typeof nodes.$inferInsert; + +export const telemetry = sqliteTable( + "telemetry", + { + id: integer("id").primaryKey({ autoIncrement: true }), + deviceId: integer("device_id").notNull(), + nodeNum: integer("node_num").notNull(), + kind: text("kind").notNull(), + ts: integer("ts").notNull(), + payloadJson: text("payload_json").notNull(), + }, + (t) => ({ + nodeTs: index("idx_telemetry_node_ts").on(t.deviceId, t.nodeNum, t.ts), + }), +); + +export type TelemetryRow = typeof telemetry.$inferSelect; +export type TelemetryInsert = typeof telemetry.$inferInsert; + +export const schemaVersion = sqliteTable("_schema", { + version: integer("version").primaryKey(), +}); + +/** + * Hand-written DDL applied at boot if `_schema` is empty or behind. Drizzle's + * own migration tooling is great but adds a build-time step; we keep migrations + * inline so the package self-bootstraps on first DB open. + */ +export const MIGRATIONS: ReadonlyArray<{ version: number; sql: string[] }> = [ + { + version: 1, + sql: [ + `CREATE TABLE IF NOT EXISTS messages ( + id INTEGER NOT NULL, + device_id INTEGER NOT NULL, + conversation_key TEXT NOT NULL, + from_node INTEGER NOT NULL, + to_node INTEGER NOT NULL, + channel INTEGER NOT NULL, + rx_time INTEGER NOT NULL, + type TEXT NOT NULL, + text TEXT NOT NULL, + state TEXT NOT NULL + )`, + `CREATE INDEX IF NOT EXISTS messages_pk ON messages(device_id, id)`, + `CREATE INDEX IF NOT EXISTS idx_messages_conv_rxtime ON messages(device_id, conversation_key, rx_time)`, + `CREATE INDEX IF NOT EXISTS idx_messages_pending ON messages(device_id, state)`, + `CREATE TABLE IF NOT EXISTS nodes ( + device_id INTEGER NOT NULL, + num INTEGER NOT NULL, + last_heard INTEGER, + snr INTEGER, + is_favorite INTEGER NOT NULL DEFAULT 0, + is_ignored INTEGER NOT NULL DEFAULT 0, + user_json TEXT, + position_json TEXT, + metrics_json TEXT, + PRIMARY KEY (device_id, num) + )`, + `CREATE INDEX IF NOT EXISTS idx_nodes_last_heard ON nodes(device_id, last_heard)`, + `CREATE TABLE IF NOT EXISTS telemetry ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + device_id INTEGER NOT NULL, + node_num INTEGER NOT NULL, + kind TEXT NOT NULL, + ts INTEGER NOT NULL, + payload_json TEXT NOT NULL + )`, + `CREATE INDEX IF NOT EXISTS idx_telemetry_node_ts ON telemetry(device_id, node_num, ts)`, + `CREATE TABLE IF NOT EXISTS _schema (version INTEGER PRIMARY KEY)`, + ], + }, + { + version: 2, + sql: [ + `CREATE TABLE IF NOT EXISTS drafts ( + device_id INTEGER NOT NULL, + conversation_key TEXT NOT NULL, + text TEXT NOT NULL, + updated_at INTEGER NOT NULL, + PRIMARY KEY (device_id, conversation_key) + )`, + ], + }, + { + // Firmware 2.8: XEdDSA-signed messages, ack proof of delivery, and why + // a message failed and how many acks it got. + version: 3, + sql: [ + `ALTER TABLE messages ADD COLUMN signed INTEGER`, + `ALTER TABLE messages ADD COLUMN ack_proof INTEGER`, + `ALTER TABLE messages ADD COLUMN routing_error INTEGER`, + `ALTER TABLE messages ADD COLUMN relays INTEGER`, + ], + }, + { + // How a received message reached us: signal, hops and transport. + version: 4, + sql: [ + `ALTER TABLE messages ADD COLUMN snr REAL`, + `ALTER TABLE messages ADD COLUMN rssi INTEGER`, + `ALTER TABLE messages ADD COLUMN hops_away INTEGER`, + `ALTER TABLE messages ADD COLUMN via_mqtt INTEGER`, + `ALTER TABLE messages ADD COLUMN transport INTEGER`, + ], + }, +]; diff --git a/apps/web/src/core/storage/telemetry.test.ts b/apps/web/src/core/storage/telemetry.test.ts new file mode 100644 index 000000000..3ce91ff66 --- /dev/null +++ b/apps/web/src/core/storage/telemetry.test.ts @@ -0,0 +1,123 @@ +import { create } from "@bufbuild/protobuf"; +import { Protobuf } from "@core/protobuf.ts"; +import { beforeEach, describe, expect, it } from "vitest"; +import type { SqlocalDb } from "./db.ts"; +import { createMemoryDb } from "./memoryDb.ts"; +import { SqlocalTelemetryRepository } from "./telemetry.ts"; +import type { TelemetryReading } from "./types.ts"; + +function reading(nodeNum: number, ms: number, battery = 80): TelemetryReading { + return { + nodeNum, + time: new Date(ms), + kind: "deviceMetrics", + value: create(Protobuf.Telemetry.DeviceMetricsSchema, { + batteryLevel: battery, + }), + }; +} + +function deviceMetrics( + reading: TelemetryReading | undefined, +): Protobuf.Telemetry.DeviceMetrics | undefined { + const value = reading?.value; + return value?.$typeName === "meshtastic.DeviceMetrics" ? value : undefined; +} + +describe("SqlocalTelemetryRepository", () => { + let db: SqlocalDb; + let repo: SqlocalTelemetryRepository; + + beforeEach(async () => { + db = await createMemoryDb(); + repo = new SqlocalTelemetryRepository(db, { deviceId: 1 }); + }); + + it("appends and loads recent readings ordered ascending", async () => { + await repo.append(reading(100, 1000, 90)); + await repo.append(reading(100, 2000, 80)); + await repo.append(reading(100, 3000, 70)); + + const out = await repo.loadRecent(100, 10); + expect(out.map((r) => r.time.getTime())).toEqual([1000, 2000, 3000]); + expect(deviceMetrics(out[2])?.batteryLevel).toBe(70); + }); + + it("loadBefore returns rows older than the cursor in ascending order", async () => { + await repo.appendBatch([ + reading(100, 1000), + reading(100, 2000), + reading(100, 3000), + reading(100, 4000), + ]); + + const out = await repo.loadBefore(100, new Date(3000), 10); + expect(out.map((r) => r.time.getTime())).toEqual([1000, 2000]); + }); + + it("scopes by deviceId — different repos see only their own rows", async () => { + const repo2 = new SqlocalTelemetryRepository(db, { deviceId: 2 }); + await repo.append(reading(50, 1000)); + await repo2.append(reading(50, 1000)); + + expect(await repo.loadRecent(50, 10)).toHaveLength(1); + expect(await repo2.loadRecent(50, 10)).toHaveLength(1); + + await repo.clearNode(50); + expect(await repo.loadRecent(50, 10)).toHaveLength(0); + expect(await repo2.loadRecent(50, 10)).toHaveLength(1); + }); + + it("prune trims per-node history to maxPerNode", async () => { + for (let i = 0; i < 20; i++) { + await repo.append(reading(7, (i + 1) * 1000)); + } + await repo.prune({ maxPerNode: 5 }); + const remaining = await repo.loadRecent(7, 100); + expect(remaining).toHaveLength(5); + // The 5 newest entries kept (16k..20k) + expect(remaining[0]?.time.getTime()).toBe(16_000); + expect(remaining[4]?.time.getTime()).toBe(20_000); + }); + + it("prune drops readings older than olderThanMs", async () => { + await repo.append(reading(7, Date.now() - 10_000_000)); + await repo.append(reading(7, Date.now() - 1000)); + await repo.prune({ olderThanMs: 5_000_000 }); + expect(await repo.loadRecent(7, 100)).toHaveLength(1); + }); + + it("preserves the proto payload across save + load", async () => { + const value = create(Protobuf.Telemetry.DeviceMetricsSchema, { + batteryLevel: 73, + voltage: 4.1, + }); + await repo.append({ + nodeNum: 9, + time: new Date(123_456), + kind: "deviceMetrics", + value, + }); + const out = await repo.loadRecent(9, 1); + const v = deviceMetrics(out[0]); + expect(v?.batteryLevel).toBe(73); + expect(v?.voltage).toBeCloseTo(4.1); + }); + + it("setScope moves reads, writes and pruning to the new scope", async () => { + await repo.appendBatch([reading(100, 1000), reading(100, 2000)]); + + repo.setScope(0xabcd); + expect(await repo.loadRecent(100, 10)).toEqual([]); + await repo.appendBatch([reading(100, 3000), reading(100, 4000)]); + await repo.prune({ maxPerNode: 1 }); + expect( + (await repo.loadRecent(100, 10)).map((r) => r.time.getTime()), + ).toEqual([4000]); + + const old = new SqlocalTelemetryRepository(db, { deviceId: 1 }); + expect( + (await old.loadRecent(100, 10)).map((r) => r.time.getTime()), + ).toEqual([1000, 2000]); + }); +}); diff --git a/apps/web/src/core/storage/telemetry.ts b/apps/web/src/core/storage/telemetry.ts new file mode 100644 index 000000000..3ea092c7f --- /dev/null +++ b/apps/web/src/core/storage/telemetry.ts @@ -0,0 +1,242 @@ +import { fromBinary, toBinary } from "@bufbuild/protobuf"; +import { Protobuf } from "@core/protobuf.ts"; +import { and, count, desc, eq, lt, sql } from "drizzle-orm"; +import type { SqlocalDb } from "./db.ts"; +import { telemetry } from "./schema.ts"; +import { + base64Decode, + base64Encode, + type TelemetryReading, + type TelemetryRepository, + type TelemetryRetentionPolicy, +} from "./types.ts"; + +export interface SqlocalTelemetryRepositoryOptions { + deviceId: number; +} + +export class SqlocalTelemetryRepository implements TelemetryRepository { + private readonly db: SqlocalDb; + private deviceId: number; + + constructor(db: SqlocalDb, options: SqlocalTelemetryRepositoryOptions) { + this.db = db; + this.deviceId = options.deviceId; + } + + /** + * Points every later read and write at another `device_id`. Rows under the + * old one are left as they are. + */ + setScope(deviceId: number): void { + this.deviceId = deviceId; + } + + async loadRecent( + nodeNum: number, + limit: number, + ): Promise { + const rows = await this.db + .select() + .from(telemetry) + .where( + and( + eq(telemetry.deviceId, this.deviceId), + eq(telemetry.nodeNum, nodeNum), + ), + ) + .orderBy(desc(telemetry.ts)) + .limit(limit); + return rows.flatMap((row) => rowToReading(row) ?? []).reverse(); + } + + async loadBefore( + nodeNum: number, + cursor: Date, + limit: number, + ): Promise { + const rows = await this.db + .select() + .from(telemetry) + .where( + and( + eq(telemetry.deviceId, this.deviceId), + eq(telemetry.nodeNum, nodeNum), + lt(telemetry.ts, cursor.getTime()), + ), + ) + .orderBy(desc(telemetry.ts)) + .limit(limit); + return rows.flatMap((row) => rowToReading(row) ?? []).reverse(); + } + + async append(reading: TelemetryReading): Promise { + await this.appendBatch([reading]); + } + + async appendBatch(readings: ReadonlyArray): Promise { + if (readings.length === 0) return; + const rows = readings.flatMap((r) => readingToRow(this.deviceId, r) ?? []); + if (rows.length === 0) return; + await this.db.insert(telemetry).values(rows); + } + + async prune(policy: TelemetryRetentionPolicy): Promise { + if (policy.olderThanMs !== undefined) { + const cutoff = Date.now() - policy.olderThanMs; + await this.db + .delete(telemetry) + .where( + and(eq(telemetry.deviceId, this.deviceId), lt(telemetry.ts, cutoff)), + ); + } + if (policy.maxPerNode !== undefined) { + const max = policy.maxPerNode; + // Get distinct nodes that exceed the cap, then trim each. + const overCap = await this.db + .select({ nodeNum: telemetry.nodeNum, c: count() }) + .from(telemetry) + .where(eq(telemetry.deviceId, this.deviceId)) + .groupBy(telemetry.nodeNum) + .having(sql`count(*) > ${max}`); + for (const row of overCap) { + // Keep the newest `max` rows; delete everything older than the + // ts-of-the-(max+1)th-newest. ts ASC; offset by max-th gives cutoff. + const cutoffRows = await this.db + .select({ ts: telemetry.ts }) + .from(telemetry) + .where( + and( + eq(telemetry.deviceId, this.deviceId), + eq(telemetry.nodeNum, row.nodeNum), + ), + ) + .orderBy(desc(telemetry.ts)) + .limit(1) + .offset(max - 1); + const cutoff = cutoffRows[0]?.ts; + if (cutoff === undefined) continue; + await this.db + .delete(telemetry) + .where( + and( + eq(telemetry.deviceId, this.deviceId), + eq(telemetry.nodeNum, row.nodeNum), + lt(telemetry.ts, cutoff), + ), + ); + } + } + } + + async clearNode(nodeNum: number): Promise { + await this.db + .delete(telemetry) + .where( + and( + eq(telemetry.deviceId, this.deviceId), + eq(telemetry.nodeNum, nodeNum), + ), + ); + } + + async clear(): Promise { + await this.db + .delete(telemetry) + .where(eq(telemetry.deviceId, this.deviceId)); + } +} + +type TelemetryRow = typeof telemetry.$inferInsert; + +function readingToRow( + deviceId: number, + reading: TelemetryReading, +): TelemetryRow | undefined { + const payload = encodeValue(reading.value); + if (!reading.kind || !payload) return undefined; + return { + deviceId, + nodeNum: reading.nodeNum, + kind: reading.kind, + ts: reading.time.getTime(), + payloadJson: base64Encode(payload), + }; +} + +function encodeValue(value: TelemetryReading["value"]): Uint8Array | undefined { + switch (value?.$typeName) { + case "meshtastic.DeviceMetrics": + return toBinary(Protobuf.Telemetry.DeviceMetricsSchema, value); + case "meshtastic.EnvironmentMetrics": + return toBinary(Protobuf.Telemetry.EnvironmentMetricsSchema, value); + case "meshtastic.AirQualityMetrics": + return toBinary(Protobuf.Telemetry.AirQualityMetricsSchema, value); + case "meshtastic.PowerMetrics": + return toBinary(Protobuf.Telemetry.PowerMetricsSchema, value); + case "meshtastic.LocalStats": + return toBinary(Protobuf.Telemetry.LocalStatsSchema, value); + case "meshtastic.HealthMetrics": + return toBinary(Protobuf.Telemetry.HealthMetricsSchema, value); + case "meshtastic.HostMetrics": + return toBinary(Protobuf.Telemetry.HostMetricsSchema, value); + default: + return undefined; + } +} + +function rowToReading(row: { + nodeNum: number; + kind: string; + ts: number; + payloadJson: string; +}): TelemetryReading | undefined { + const base = { nodeNum: row.nodeNum, time: new Date(row.ts) }; + const bytes = base64Decode(row.payloadJson); + switch (row.kind) { + case "deviceMetrics": + return { + ...base, + kind: row.kind, + value: fromBinary(Protobuf.Telemetry.DeviceMetricsSchema, bytes), + }; + case "environmentMetrics": + return { + ...base, + kind: row.kind, + value: fromBinary(Protobuf.Telemetry.EnvironmentMetricsSchema, bytes), + }; + case "airQualityMetrics": + return { + ...base, + kind: row.kind, + value: fromBinary(Protobuf.Telemetry.AirQualityMetricsSchema, bytes), + }; + case "powerMetrics": + return { + ...base, + kind: row.kind, + value: fromBinary(Protobuf.Telemetry.PowerMetricsSchema, bytes), + }; + case "localStats": + return { + ...base, + kind: row.kind, + value: fromBinary(Protobuf.Telemetry.LocalStatsSchema, bytes), + }; + case "healthMetrics": + return { + ...base, + kind: row.kind, + value: fromBinary(Protobuf.Telemetry.HealthMetricsSchema, bytes), + }; + case "hostMetrics": + return { + ...base, + kind: row.kind, + value: fromBinary(Protobuf.Telemetry.HostMetricsSchema, bytes), + }; + default: + return undefined; + } +} diff --git a/apps/web/src/core/storage/types.ts b/apps/web/src/core/storage/types.ts new file mode 100644 index 000000000..8af767bb9 --- /dev/null +++ b/apps/web/src/core/storage/types.ts @@ -0,0 +1,197 @@ +import type { Protobuf, Types } from "@core/protobuf.ts"; + +/** + * Delivery state of a message, after the Android app's MessageStatus. + * + * - Pending: handed to the radio, no ack yet. + * - Delivered: acked by a relay, or the radio heard it rebroadcast. + * - Ack: the addressed node acked it (and every inbound message). + * - Failed: a NAK or a local error; see Message.routingError. + */ +export enum MessageState { + Pending = "pending", + Delivered = "delivered", + Ack = "ack", + Failed = "failed", +} + +export interface Message { + readonly id: number; + readonly from: number; + readonly to: number; + readonly channel: Types.ChannelNumber; + readonly rxTime: Date; + readonly type: Types.PacketDestination; + readonly text: string; + readonly state: MessageState; + /** Received with an XEdDSA signature the device verified. */ + readonly signed?: boolean; + /** Proof-of-delivery verdict from the ack (firmware 2.8.1+). */ + readonly ackProof?: Protobuf.Mesh.MeshPacket_AckProofStatus; + /** Why a Failed message failed, from the NAK or the local queue. */ + readonly routingError?: Protobuf.Mesh.Routing_Error; + /** How many acks (relays and the recipient) came back for it. */ + readonly relays?: number; + readonly snr?: number; + readonly rssi?: number; + readonly hopsAway?: number; + readonly viaMqtt?: boolean; + readonly transport?: Protobuf.Mesh.MeshPacket_TransportMechanism; +} + +/** Fields an ack or NAK can change on a stored message. */ +export type MessageDeliveryPatch = { + -readonly [ + K in "state" | "ackProof" | "routingError" | "relays" + ]?: Message[K]; +}; + +/** Broadcast messages are keyed by channel; direct ones by the peer. */ +export type ConversationKey = + | { kind: "channel"; channel: Types.ChannelNumber } + | { kind: "direct"; peer: number }; + +export interface RetentionPolicy { + olderThanMs?: number; + maxPerBucket?: number; +} + +export interface MessageRepository { + loadRecent(key: ConversationKey, limit: number): Promise; + loadBefore( + key: ConversationKey, + cursor: Date, + limit: number, + ): Promise; + /** + * Stores a message under `key` when known: a direct message we sent + * belongs to its recipient, which `message` alone can't tell apart from + * one we received. Without it the key is inferred from the sender. + */ + append(message: Message, key?: ConversationKey): Promise; + appendBatch(messages: ReadonlyArray): Promise; + updateState(id: number, state: MessageState): Promise; + updateDelivery(id: number, patch: MessageDeliveryPatch): Promise; + remove(id: number): Promise; + prune(policy: RetentionPolicy): Promise; + clearConversation(key: ConversationKey): Promise; + clear(): Promise; + /** + * Moves direct messages we sent that were filed under our own node, as + * older versions did, to the conversation with their recipient. + */ + refileSentDirect?(localNodeNum: number): Promise; + /** Points every later read and write at another node's history. */ + setScope?(scope: number): void; +} + +export interface DraftRepository { + load(key: ConversationKey): Promise; + save(key: ConversationKey, text: string): Promise; + clear(key: ConversationKey): Promise; + loadAll(): Promise>; + setScope?(scope: number): void; +} + +export interface Node { + readonly num: number; + readonly user?: Protobuf.Mesh.User; + readonly position?: Protobuf.Mesh.Position; + readonly deviceMetrics?: Protobuf.Telemetry.DeviceMetrics; + readonly lastHeard?: number; + readonly snr?: number; + readonly channel?: number; + readonly viaMqtt?: boolean; + readonly hopsAway?: number; + readonly isFavorite: boolean; + readonly isIgnored: boolean; + readonly isKeyManuallyVerified?: boolean; + readonly isMuted?: boolean; + /** The node signs its packets with XEdDSA (firmware 2.8+). */ + readonly hasXeddsaSigned?: boolean; + /** + * Heard over LoRa since the radio's current LoRa settings took effect. + * Firmware older than 2.8.1 doesn't report it, so every node counts as + * heard there. + */ + readonly heardOnCurrentLora?: boolean; + /** Latest status message the node broadcast (NODE_STATUS_APP). */ + readonly status?: string; +} + +export interface NodesRepository { + loadAll(): Promise; + get(nodeNum: number): Promise; + upsert(node: Node): Promise; + upsertBatch(nodes: ReadonlyArray): Promise; + remove(nodeNum: number): Promise; + clear(): Promise; + setScope?(scope: number): void; +} + +export type TelemetryKind = Protobuf.Telemetry.Telemetry["variant"]["case"]; + +export interface TelemetryReading { + readonly nodeNum: number; + readonly time: Date; + readonly kind: TelemetryKind; + readonly value: Protobuf.Telemetry.Telemetry["variant"]["value"]; +} + +export interface TelemetryRetentionPolicy { + maxPerNode?: number; + olderThanMs?: number; +} + +export interface TelemetryRepository { + loadRecent(nodeNum: number, limit: number): Promise; + loadBefore( + nodeNum: number, + cursor: Date, + limit: number, + ): Promise; + append(reading: TelemetryReading): Promise; + appendBatch(readings: ReadonlyArray): Promise; + prune(policy: TelemetryRetentionPolicy): Promise; + clearNode(nodeNum: number): Promise; + clear(): Promise; + setScope?(scope: number): void; +} + +/** + * The conversation a received message belongs to. Wrong for a direct + * message we sent, which belongs to its recipient; callers that know the + * local node pass the key instead. + */ +export function inferConversation(message: Message): ConversationKey { + return message.type === "direct" + ? { kind: "direct", peer: message.from } + : { kind: "channel", channel: message.channel }; +} + +export function conversationKeyString(key: ConversationKey): string { + return key.kind === "channel" + ? `channel:${key.channel}` + : `direct:${key.peer}`; +} + +export function parseConversationKey(s: string): ConversationKey { + if (s.startsWith("channel:")) + return { kind: "channel", channel: Number(s.slice(8)) }; + if (s.startsWith("direct:")) + return { kind: "direct", peer: Number(s.slice(7)) }; + throw new Error(`Unknown conversation key format: ${s}`); +} + +export function base64Encode(bytes: Uint8Array): string { + let s = ""; + for (const byte of bytes) s += String.fromCharCode(byte); + return btoa(s); +} + +export function base64Decode(s: string): Uint8Array { + const bin = atob(s); + const out = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); + return out; +} diff --git a/apps/web/src/core/types.ts b/apps/web/src/core/types.ts new file mode 100644 index 000000000..a606ac9ed --- /dev/null +++ b/apps/web/src/core/types.ts @@ -0,0 +1,53 @@ +import type { Protobuf } from "@core/protobuf.ts"; + +export enum DeviceStatusEnum { + DeviceRestarting = 1, + DeviceDisconnected = 2, + DeviceConnecting = 3, + DeviceReconnecting = 4, + DeviceConnected = 5, + DeviceConfiguring = 6, + DeviceConfigured = 7, + DeviceError = 8, +} + +export enum ChannelNumber { + Primary = 0, + Channel1 = 1, + Channel2 = 2, + Channel3 = 3, + Channel4 = 4, + Channel5 = 5, + Channel6 = 6, + Admin = 7, +} + +export type Destination = number | "self" | "broadcast"; + +export type PacketDestination = "broadcast" | "direct"; + +export interface PacketMetadata { + id: number; + rxTime: Date; + type: PacketDestination; + from: number; + to: number; + channel: ChannelNumber; + data: T; + /** Data.request_id: the packet this one answers or acks. */ + requestId?: number; + /** The sender signed the packet with XEdDSA and the device verified it. */ + xeddsaSigned?: boolean; + /** Firmware's verdict on an ack's proof of delivery (2.8.1+). */ + ackProofStatus?: Protobuf.Mesh.MeshPacket_AckProofStatus; + /** SNR in dB as our radio heard the packet; undefined when unmeasured. */ + rxSnr?: number; + /** RSSI in dBm as our radio heard the packet; undefined when unmeasured. */ + rxRssi?: number; + /** Hops the packet took to reach us; undefined when it can't be told. */ + hopsAway?: number; + /** The packet reached the mesh through an MQTT gateway. */ + viaMqtt?: boolean; + /** How the packet reached our radio (LoRa, MQTT, UDP, API...). */ + transportMechanism?: Protobuf.Mesh.MeshPacket_TransportMechanism; +} diff --git a/apps/web/src/pages/Connections/useConnections.test.ts b/apps/web/src/pages/Connections/useConnections.test.ts index 9458ea032..8a72493a9 100644 --- a/apps/web/src/pages/Connections/useConnections.test.ts +++ b/apps/web/src/pages/Connections/useConnections.test.ts @@ -39,20 +39,25 @@ function recording(kind: string, make: () => T) { }; } -vi.mock("@meshtastic/sdk-storage-sqlocal/chat", async () => { +vi.mock("@core/storage/messages.ts", async () => { const sdk = await import("@meshtastic/sdk"); return { SqlocalMessageRepository: recording( "messages", () => new sdk.InMemoryMessageRepository(), ), + }; +}); +vi.mock("@core/storage/drafts.ts", async () => { + const sdk = await import("@meshtastic/sdk"); + return { SqlocalDraftRepository: recording( "drafts", () => new sdk.InMemoryDraftRepository(), ), }; }); -vi.mock("@meshtastic/sdk-storage-sqlocal/nodes", async () => { +vi.mock("@core/storage/nodes.ts", async () => { const sdk = await import("@meshtastic/sdk"); return { SqlocalNodesRepository: recording( @@ -61,7 +66,7 @@ vi.mock("@meshtastic/sdk-storage-sqlocal/nodes", async () => { ), }; }); -vi.mock("@meshtastic/sdk-storage-sqlocal/telemetry", async () => { +vi.mock("@core/storage/telemetry.ts", async () => { const sdk = await import("@meshtastic/sdk"); return { SqlocalTelemetryRepository: recording( From dc1bd8a0f216280f9b9d45266a83d401c4c21e73 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 09:35:30 -0500 Subject: [PATCH 17/49] refactor(web): run the app on the Kotlin SDK session, ending the TS runtime A MeshSession over the facade decodes the SDK's FromRadio and MeshPacket streams into typed events and owns the web's views: device (status, identity, metadata, lockdown, region presets), nodes (the SDK node DB plus PKI and routing errors, favourite/ignore/remove/reset), channels and beacon offers, chat (messages, drafts, unread, send/resend with the SDK's packet id and delivery state) and telemetry history, all over the web's sqlocal repositories keyed by node number. The sdk-react hooks are replaced by same-named hooks in core/kmp/hooks over a web MeshRegistry; subscriptions.ts feeds the device store from session events; useConnections creates the session before the SDK connects, so there is one handshake. kmpTransport, the TS MeshDevice/MeshClient, the TS MeshRegistry and the sdk, sdk-react and transport-http dependencies are gone from apps/web; Types, withLocalNetworkTarget and the Mesh Beacon join helpers are local. --- apps/web/package.json | 3 - apps/web/src/App.tsx | 2 +- .../src/components/BeaconOfferNotifier.tsx | 2 +- .../src/components/CommandPalette/index.tsx | 6 +- .../src/components/ConnectingOverlay.test.tsx | 3 +- apps/web/src/components/ConnectingOverlay.tsx | 2 +- .../ClientNotificationDialog.tsx | 5 +- .../DeleteMessagesDialog.test.tsx | 5 +- .../DeleteMessagesDialog.tsx | 2 +- .../FactoryResetConfigDialog.test.tsx | 10 +- .../FactoryResetConfigDialog.tsx | 4 +- .../FactoryResetDeviceDialog.test.tsx | 9 +- .../FactoryResetDeviceDialog.tsx | 4 +- .../LockdownDialog/LockdownDialog.test.tsx | 5 +- .../NodeDetailsDialog/NodeDetailsDialog.tsx | 4 +- .../NodeDetailsDialog/NodeTelemetry.test.tsx | 2 +- .../NodeDetailsDialog/NodeTelemetry.tsx | 2 +- apps/web/src/components/Dialog/QRDialog.tsx | 2 +- .../components/Dialog/RebootDialog.test.tsx | 6 +- .../src/components/Dialog/RebootDialog.tsx | 4 +- .../RefreshKeysDialog.test.tsx | 4 +- .../RefreshKeysDialog/RefreshKeysDialog.tsx | 2 +- .../RefreshKeysDialog/useRefreshKeysDialog.ts | 2 +- .../components/Dialog/RemoveNodeDialog.tsx | 2 +- .../ResetNodeDbDialog.test.tsx | 3 +- .../ResetNodeDbDialog/ResetNodeDbDialog.tsx | 2 +- .../src/components/Dialog/ShutdownDialog.tsx | 4 +- .../PageComponents/Channels/BeaconOffers.tsx | 4 +- .../PageComponents/Channels/Channels.tsx | 2 +- .../PageComponents/Map/Layers/NodesLayer.tsx | 2 +- .../Messages/MessageInput.test.tsx | 5 +- .../PageComponents/Messages/MessageInput.tsx | 4 +- .../Messages/MessageItem.test.tsx | 3 +- .../PageComponents/Messages/MessageStatus.tsx | 2 +- .../PageComponents/ModuleConfig/MQTT.test.tsx | 4 +- .../ModuleConfig/MeshBeacon.tsx | 2 +- .../PageComponents/ModuleConfig/RangeTest.tsx | 2 +- .../Settings/DeviceConfig.test.tsx | 6 +- .../SettingsPages/useDeviceConnected.ts | 7 +- .../src/components/RegionSetupReminder.tsx | 2 +- apps/web/src/components/Sidebar.tsx | 2 +- apps/web/src/core/connections/lna.ts | 35 ++ apps/web/src/core/connections/repositories.ts | 81 +++ apps/web/src/core/connections/sdkClient.ts | 131 ---- apps/web/src/core/hooks/useBeaconOffers.ts | 5 +- .../hooks/useChatAsLegacyMessages.test.ts | 2 +- .../src/core/hooks/useChatAsLegacyMessages.ts | 21 +- apps/web/src/core/hooks/useChatLegacy.ts | 52 -- .../src/core/hooks/useDeviceCapabilities.ts | 3 +- .../src/core/hooks/useFavoriteNode.test.ts | 3 +- apps/web/src/core/hooks/useFavoriteNode.ts | 2 +- apps/web/src/core/hooks/useIgnoreNode.test.ts | 3 +- apps/web/src/core/hooks/useIgnoreNode.ts | 2 +- apps/web/src/core/hooks/useLockdown.ts | 7 +- .../src/core/hooks/useNodeTelemetryHistory.ts | 6 +- .../src/core/hooks/useNodesAsProto.test.ts | 2 +- apps/web/src/core/hooks/useNodesAsProto.ts | 5 +- apps/web/src/core/hooks/useNodesLegacy.ts | 43 -- apps/web/src/core/kmp/channels.ts | 73 +++ apps/web/src/core/kmp/chat.ts | 562 +++++++++++++++++ apps/web/src/core/kmp/configEditorIo.test.ts | 112 +--- apps/web/src/core/kmp/configEditorIo.ts | 175 +----- apps/web/src/core/kmp/connectionState.test.ts | 2 +- apps/web/src/core/kmp/connectionState.ts | 8 +- apps/web/src/core/kmp/device.ts | 219 +++++++ apps/web/src/core/kmp/emitter.ts | 17 + apps/web/src/core/kmp/hooks/index.ts | 26 + apps/web/src/core/kmp/hooks/registry.tsx | 35 ++ .../web/src/core/kmp/hooks/useConfigEditor.ts | 2 +- .../src/core/kmp/hooks/useModuleMessages.ts | 2 +- apps/web/src/core/kmp/hooks/useSession.ts | 163 +++++ apps/web/src/core/kmp/moduleMessages.ts | 43 +- apps/web/src/core/kmp/nodes.ts | 334 ++++++++++ apps/web/src/core/kmp/packets.ts | 97 +++ apps/web/src/core/kmp/registry.ts | 40 ++ apps/web/src/core/kmp/session.test.ts | 419 +++++++++++++ apps/web/src/core/kmp/session.ts | 577 ++++++++++++++++++ apps/web/src/core/kmp/signals.ts | 28 + apps/web/src/core/kmp/telemetry.ts | 150 +++++ apps/web/src/core/kmp/transport.test.ts | 107 ---- apps/web/src/core/kmp/transport.ts | 82 --- apps/web/src/core/meshRegistry.ts | 14 - .../stores/deviceStore/deviceStore.mock.ts | 2 - .../stores/deviceStore/deviceStore.test.ts | 38 +- apps/web/src/core/stores/deviceStore/index.ts | 28 +- apps/web/src/core/subscriptions.ts | 159 ++--- apps/web/src/core/utils/beaconJoin.test.ts | 2 +- apps/web/src/core/utils/beaconJoin.ts | 5 +- apps/web/src/core/utils/cleanNodes.test.ts | 2 +- apps/web/src/core/utils/cleanNodes.ts | 2 +- apps/web/src/core/utils/meshBeacon.test.ts | 118 ++++ apps/web/src/core/utils/meshBeacon.ts | 138 +++++ apps/web/src/core/utils/telemetry.test.ts | 2 +- apps/web/src/core/utils/telemetry.ts | 2 +- apps/web/src/index.tsx | 4 +- .../useConnections.devices.test.ts | 4 +- .../Connections/useConnections.kmp.test.ts | 31 +- .../pages/Connections/useConnections.test.ts | 111 ++-- .../src/pages/Connections/useConnections.ts | 365 ++++------- apps/web/src/pages/Connections/utils.ts | 2 +- apps/web/src/pages/Messages.tsx | 7 +- apps/web/src/pages/Nodes/index.tsx | 15 +- .../web/src/pages/Settings/Administration.tsx | 4 +- apps/web/src/pages/Settings/BackupRestore.tsx | 2 +- apps/web/src/pages/Settings/CleanNodeDb.tsx | 5 +- apps/web/src/pages/Settings/DebugPanel.tsx | 2 +- apps/web/src/tests/adminInterceptor.ts | 137 +++++ apps/web/src/tests/renderSettingsForm.tsx | 20 +- 108 files changed, 3734 insertions(+), 1311 deletions(-) create mode 100644 apps/web/src/core/connections/lna.ts create mode 100644 apps/web/src/core/connections/repositories.ts delete mode 100644 apps/web/src/core/connections/sdkClient.ts delete mode 100644 apps/web/src/core/hooks/useChatLegacy.ts delete mode 100644 apps/web/src/core/hooks/useNodesLegacy.ts create mode 100644 apps/web/src/core/kmp/channels.ts create mode 100644 apps/web/src/core/kmp/chat.ts create mode 100644 apps/web/src/core/kmp/device.ts create mode 100644 apps/web/src/core/kmp/emitter.ts create mode 100644 apps/web/src/core/kmp/hooks/registry.tsx create mode 100644 apps/web/src/core/kmp/hooks/useSession.ts create mode 100644 apps/web/src/core/kmp/nodes.ts create mode 100644 apps/web/src/core/kmp/packets.ts create mode 100644 apps/web/src/core/kmp/registry.ts create mode 100644 apps/web/src/core/kmp/session.test.ts create mode 100644 apps/web/src/core/kmp/session.ts create mode 100644 apps/web/src/core/kmp/telemetry.ts delete mode 100644 apps/web/src/core/kmp/transport.test.ts delete mode 100644 apps/web/src/core/kmp/transport.ts delete mode 100644 apps/web/src/core/meshRegistry.ts create mode 100644 apps/web/src/core/utils/meshBeacon.test.ts create mode 100644 apps/web/src/core/utils/meshBeacon.ts create mode 100644 apps/web/src/tests/adminInterceptor.ts diff --git a/apps/web/package.json b/apps/web/package.json index 1bed98d3e..2c3c33639 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -37,10 +37,7 @@ "@bufbuild/protobuf": "^2.16.0", "@hookform/resolvers": "^5.9.1", "@meshtastic/protobufs": "workspace:*", - "@meshtastic/sdk": "workspace:*", "@meshtastic/sdk-kmp": "workspace:*", - "@meshtastic/sdk-react": "workspace:*", - "@meshtastic/transport-http": "workspace:*", "@noble/curves": "^2.4.0", "@preact/signals-core": "^1.14.4", "@radix-ui/react-accordion": "^1.3.1", diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 46525f6de..26ad51477 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -12,7 +12,7 @@ import Footer from "@components/UI/Footer.tsx"; import { useTheme } from "@core/hooks/useTheme.ts"; import { cn } from "@core/utils/cn.ts"; import { SidebarProvider, useAppStore, useDeviceStore } from "@core/stores"; -import { useTotalUnread } from "@meshtastic/sdk-react"; +import { useTotalUnread } from "@core/kmp/hooks"; import { Outlet } from "@tanstack/react-router"; import { TanStackRouterDevtools } from "@tanstack/react-router-devtools"; import { useEffect, useRef } from "react"; diff --git a/apps/web/src/components/BeaconOfferNotifier.tsx b/apps/web/src/components/BeaconOfferNotifier.tsx index ed391d83d..79fd7a693 100644 --- a/apps/web/src/components/BeaconOfferNotifier.tsx +++ b/apps/web/src/components/BeaconOfferNotifier.tsx @@ -6,7 +6,7 @@ import { Button } from "@components/UI/Button.tsx"; import { useBeaconOffers } from "@core/hooks/useBeaconOffers.ts"; import { useToast } from "@core/hooks/useToast.ts"; import { useBeaconJoinStore } from "@core/stores/beaconJoinStore.ts"; -import { useNodes } from "@meshtastic/sdk-react"; +import { useNodes } from "@core/kmp/hooks"; import { useEffect, useRef } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/CommandPalette/index.tsx b/apps/web/src/components/CommandPalette/index.tsx index bc02e52f0..48dcb0f1b 100644 --- a/apps/web/src/components/CommandPalette/index.tsx +++ b/apps/web/src/components/CommandPalette/index.tsx @@ -51,6 +51,7 @@ import { } from "lucide-react"; import { useEffect } from "react"; import { useTranslation } from "react-i18next"; +import { useActiveClient } from "@core/kmp/hooks"; export interface Group { id: string; @@ -79,7 +80,8 @@ export const CommandPalette = () => { setSelectedDevice, } = useAppStore(); const { getDevices } = useDeviceStore(); - const { setDialogOpen, connection } = useDevice(); + const { setDialogOpen } = useDevice(); + const connection = useActiveClient(); const allNodes = useNodesAsProto(); const getNode = (n: number) => allNodes.find((node) => node.num === n); const { pinnedItems, togglePinnedItem } = usePinnedItems({ @@ -297,7 +299,7 @@ export const CommandPalette = () => { label: t("debug.command.reconfigure"), icon: RefreshCwIcon, action() { - void connection?.configure(); + void connection?.rehandshake(); }, }, { diff --git a/apps/web/src/components/ConnectingOverlay.test.tsx b/apps/web/src/components/ConnectingOverlay.test.tsx index 8b47f0708..884c6ede1 100644 --- a/apps/web/src/components/ConnectingOverlay.test.tsx +++ b/apps/web/src/components/ConnectingOverlay.test.tsx @@ -14,7 +14,8 @@ vi.mock("@app/pages/Connections/useConnections", () => ({ vi.mock("@core/hooks/useLockdown.ts", () => ({ useLockdown: () => ({ isLocked: false }), })); -vi.mock("@meshtastic/sdk-react", () => ({ +vi.mock("@core/kmp/hooks", async (importOriginal) => ({ + ...(await importOriginal()), useConnectionProgress: () => ({ phase: "connecting" }), })); diff --git a/apps/web/src/components/ConnectingOverlay.tsx b/apps/web/src/components/ConnectingOverlay.tsx index 2580c8eb0..ef9639b97 100644 --- a/apps/web/src/components/ConnectingOverlay.tsx +++ b/apps/web/src/components/ConnectingOverlay.tsx @@ -4,7 +4,7 @@ import { useDeviceStore } from "@core/stores"; import { cn } from "@core/utils/cn.ts"; import { useConnections } from "@app/pages/Connections/useConnections"; import { useLockdown } from "@core/hooks/useLockdown.ts"; -import { useConnectionProgress } from "@meshtastic/sdk-react"; +import { useConnectionProgress } from "@core/kmp/hooks"; import { Bluetooth, Cable, CheckCircle2, Globe, Loader2 } from "lucide-react"; import type { ComponentType, ReactElement } from "react"; import { useEffect, useState } from "react"; diff --git a/apps/web/src/components/Dialog/ClientNotificationDialog/ClientNotificationDialog.tsx b/apps/web/src/components/Dialog/ClientNotificationDialog/ClientNotificationDialog.tsx index bf026e756..1463ae04b 100644 --- a/apps/web/src/components/Dialog/ClientNotificationDialog/ClientNotificationDialog.tsx +++ b/apps/web/src/components/Dialog/ClientNotificationDialog/ClientNotificationDialog.tsx @@ -13,6 +13,7 @@ import { useDevice } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; import { useState } from "react"; import { useTranslation } from "react-i18next"; +import { useActiveClient } from "@core/kmp/hooks"; const MessageType = Protobuf.Admin.KeyVerificationAdmin_MessageType; @@ -26,8 +27,8 @@ export const ClientNotificationDialog = ({ onOpenChange, }: ClientNotificationDialogProps) => { const { t } = useTranslation("dialog"); - const { connection, getClientNotification, removeClientNotification } = - useDevice(); + const { getClientNotification, removeClientNotification } = useDevice(); + const connection = useActiveClient(); const [securityNumber, setSecurityNumber] = useState(""); const notification = getClientNotification(0); diff --git a/apps/web/src/components/Dialog/DeleteMessagesDialog/DeleteMessagesDialog.test.tsx b/apps/web/src/components/Dialog/DeleteMessagesDialog/DeleteMessagesDialog.test.tsx index e323cfea3..571a297f9 100644 --- a/apps/web/src/components/Dialog/DeleteMessagesDialog/DeleteMessagesDialog.test.tsx +++ b/apps/web/src/components/Dialog/DeleteMessagesDialog/DeleteMessagesDialog.test.tsx @@ -1,11 +1,12 @@ import { DeleteMessagesDialog } from "@components/Dialog/DeleteMessagesDialog/DeleteMessagesDialog.tsx"; -import { useActiveClient } from "@meshtastic/sdk-react"; +import { useActiveClient } from "@core/kmp/hooks"; import { fireEvent, render, screen } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; const mockClearAll = vi.fn(); -vi.mock("@meshtastic/sdk-react", () => ({ +vi.mock("@core/kmp/hooks", async (importOriginal) => ({ + ...(await importOriginal()), useActiveClient: vi.fn(() => ({ chat: { clearAll: mockClearAll }, })), diff --git a/apps/web/src/components/Dialog/DeleteMessagesDialog/DeleteMessagesDialog.tsx b/apps/web/src/components/Dialog/DeleteMessagesDialog/DeleteMessagesDialog.tsx index 081d2244b..f090f15a8 100644 --- a/apps/web/src/components/Dialog/DeleteMessagesDialog/DeleteMessagesDialog.tsx +++ b/apps/web/src/components/Dialog/DeleteMessagesDialog/DeleteMessagesDialog.tsx @@ -1,4 +1,4 @@ -import { useActiveClient } from "@meshtastic/sdk-react"; +import { useActiveClient } from "@core/kmp/hooks"; import { AlertTriangleIcon } from "lucide-react"; import { useTranslation } from "react-i18next"; import { DialogWrapper } from "../DialogWrapper.tsx"; diff --git a/apps/web/src/components/Dialog/FactoryResetConfigDialog/FactoryResetConfigDialog.test.tsx b/apps/web/src/components/Dialog/FactoryResetConfigDialog/FactoryResetConfigDialog.test.tsx index ec205e93c..8cf591fca 100644 --- a/apps/web/src/components/Dialog/FactoryResetConfigDialog/FactoryResetConfigDialog.test.tsx +++ b/apps/web/src/components/Dialog/FactoryResetConfigDialog/FactoryResetConfigDialog.test.tsx @@ -9,11 +9,11 @@ vi.mock("@core/stores", () => ({ CurrentDeviceContext: { _currentValue: { deviceId: 1234 }, }, - useDevice: () => ({ - connection: { - factoryResetConfig: mockFactoryReset, - }, - }), + useDevice: () => ({}), +})); + +vi.mock("@core/kmp/hooks", () => ({ + useActiveClient: () => ({ factoryResetConfig: mockFactoryReset }), })); vi.mock("@core/hooks/useToast.ts", () => ({ diff --git a/apps/web/src/components/Dialog/FactoryResetConfigDialog/FactoryResetConfigDialog.tsx b/apps/web/src/components/Dialog/FactoryResetConfigDialog/FactoryResetConfigDialog.tsx index b350447d2..42a81ff96 100644 --- a/apps/web/src/components/Dialog/FactoryResetConfigDialog/FactoryResetConfigDialog.tsx +++ b/apps/web/src/components/Dialog/FactoryResetConfigDialog/FactoryResetConfigDialog.tsx @@ -1,7 +1,7 @@ import { toast } from "@core/hooks/useToast.ts"; -import { useDevice } from "@core/stores"; import { useTranslation } from "react-i18next"; import { DialogWrapper } from "../DialogWrapper.tsx"; +import { useActiveClient } from "@core/kmp/hooks"; export interface FactoryResetConfigDialogProps { open: boolean; @@ -13,7 +13,7 @@ export const FactoryResetConfigDialog = ({ onOpenChange, }: FactoryResetConfigDialogProps) => { const { t } = useTranslation("dialog"); - const { connection } = useDevice(); + const connection = useActiveClient(); const handleFactoryResetConfig = () => { connection?.factoryResetConfig().catch((error) => { diff --git a/apps/web/src/components/Dialog/FactoryResetDeviceDialog/FactoryResetDeviceDialog.test.tsx b/apps/web/src/components/Dialog/FactoryResetDeviceDialog/FactoryResetDeviceDialog.test.tsx index 7337c9b92..edecbd310 100644 --- a/apps/web/src/components/Dialog/FactoryResetDeviceDialog/FactoryResetDeviceDialog.test.tsx +++ b/apps/web/src/components/Dialog/FactoryResetDeviceDialog/FactoryResetDeviceDialog.test.tsx @@ -15,14 +15,15 @@ vi.mock("@core/stores", () => { CurrentDeviceContext: { _currentValue: { deviceId: 1234 }, }, - useDevice: () => ({ - id: 42, - connection: { factoryResetDevice: mockFactoryResetDevice }, - }), + useDevice: () => ({ id: 42 }), useDeviceStore, }; }); +vi.mock("@core/kmp/hooks", () => ({ + useActiveClient: () => ({ factoryResetDevice: mockFactoryResetDevice }), +})); + vi.mock("@core/hooks/useToast.ts", () => ({ toast: (...args: unknown[]) => mockToast(...args), })); diff --git a/apps/web/src/components/Dialog/FactoryResetDeviceDialog/FactoryResetDeviceDialog.tsx b/apps/web/src/components/Dialog/FactoryResetDeviceDialog/FactoryResetDeviceDialog.tsx index e89850d50..167bad918 100644 --- a/apps/web/src/components/Dialog/FactoryResetDeviceDialog/FactoryResetDeviceDialog.tsx +++ b/apps/web/src/components/Dialog/FactoryResetDeviceDialog/FactoryResetDeviceDialog.tsx @@ -2,6 +2,7 @@ import { toast } from "@core/hooks/useToast.ts"; import { useDevice, useDeviceStore } from "@core/stores"; import { useTranslation } from "react-i18next"; import { DialogWrapper } from "../DialogWrapper.tsx"; +import { useActiveClient } from "@core/kmp/hooks"; export interface FactoryResetDeviceDialogProps { open: boolean; @@ -13,7 +14,8 @@ export const FactoryResetDeviceDialog = ({ onOpenChange, }: FactoryResetDeviceDialogProps) => { const { t } = useTranslation("dialog"); - const { connection, id } = useDevice(); + const { id } = useDevice(); + const connection = useActiveClient(); const handleFactoryResetDevice = () => { connection?.factoryResetDevice().catch((error) => { diff --git a/apps/web/src/components/Dialog/LockdownDialog/LockdownDialog.test.tsx b/apps/web/src/components/Dialog/LockdownDialog/LockdownDialog.test.tsx index dfcd893ec..3ec1c6a0f 100644 --- a/apps/web/src/components/Dialog/LockdownDialog/LockdownDialog.test.tsx +++ b/apps/web/src/components/Dialog/LockdownDialog/LockdownDialog.test.tsx @@ -33,11 +33,8 @@ const fakeClient = () => ({ disconnect: vi.fn(), }); -vi.mock("@meshtastic/sdk-react", () => ({ - useActiveClient: () => fakeClient(), -})); - vi.mock("@core/kmp/hooks", () => ({ + useActiveClient: () => fakeClient(), useSignal: (sig: { value: unknown }) => sig.value, })); diff --git a/apps/web/src/components/Dialog/NodeDetailsDialog/NodeDetailsDialog.tsx b/apps/web/src/components/Dialog/NodeDetailsDialog/NodeDetailsDialog.tsx index 6735e2493..d30a3366b 100644 --- a/apps/web/src/components/Dialog/NodeDetailsDialog/NodeDetailsDialog.tsx +++ b/apps/web/src/components/Dialog/NodeDetailsDialog/NodeDetailsDialog.tsx @@ -30,6 +30,7 @@ import { useFavoriteNode } from "@core/hooks/useFavoriteNode.ts"; import { useIgnoreNode } from "@core/hooks/useIgnoreNode.ts"; import { toast } from "@core/hooks/useToast.ts"; import { useNodeAsProto } from "@core/hooks/useNodesAsProto.ts"; +import { useActiveClient } from "@core/kmp/hooks"; import { useAppStore, useDevice } from "@core/stores"; import { cn } from "@core/utils/cn.ts"; import { Protobuf } from "@core/protobuf.ts"; @@ -59,7 +60,8 @@ export const NodeDetailsDialog = ({ onOpenChange, }: NodeDetailsDialogProps) => { const { t } = useTranslation("dialog"); - const { setDialogOpen, connection } = useDevice(); + const { setDialogOpen } = useDevice(); + const connection = useActiveClient(); const navigate = useNavigate(); const { setNodeNumToBeRemoved, nodeNumDetails } = useAppStore(); const { updateFavorite } = useFavoriteNode(); diff --git a/apps/web/src/components/Dialog/NodeDetailsDialog/NodeTelemetry.test.tsx b/apps/web/src/components/Dialog/NodeDetailsDialog/NodeTelemetry.test.tsx index 74a93e73b..6a215d704 100644 --- a/apps/web/src/components/Dialog/NodeDetailsDialog/NodeTelemetry.test.tsx +++ b/apps/web/src/components/Dialog/NodeDetailsDialog/NodeTelemetry.test.tsx @@ -1,6 +1,6 @@ import { create } from "@bufbuild/protobuf"; import { TelemetrySections } from "@components/Dialog/NodeDetailsDialog/NodeTelemetry.tsx"; -import type { TelemetryReading } from "@meshtastic/sdk"; +import type { TelemetryReading } from "@core/storage/types.ts"; import { Protobuf } from "@core/protobuf.ts"; import { render, screen, within } from "@testing-library/react"; import { describe, expect, it } from "vitest"; diff --git a/apps/web/src/components/Dialog/NodeDetailsDialog/NodeTelemetry.tsx b/apps/web/src/components/Dialog/NodeDetailsDialog/NodeTelemetry.tsx index da03e9e81..1bd83cc24 100644 --- a/apps/web/src/components/Dialog/NodeDetailsDialog/NodeTelemetry.tsx +++ b/apps/web/src/components/Dialog/NodeDetailsDialog/NodeTelemetry.tsx @@ -1,7 +1,7 @@ import { TimeAgo } from "@components/generic/TimeAgo.tsx"; import { useNodeTelemetryHistory } from "@core/hooks/useNodeTelemetryHistory.ts"; import { telemetrySections } from "@core/utils/telemetry.ts"; -import type { TelemetryReading } from "@meshtastic/sdk"; +import type { TelemetryReading } from "@core/storage/types.ts"; import { useMemo } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/Dialog/QRDialog.tsx b/apps/web/src/components/Dialog/QRDialog.tsx index 748df0e0e..6fb1e0018 100644 --- a/apps/web/src/components/Dialog/QRDialog.tsx +++ b/apps/web/src/components/Dialog/QRDialog.tsx @@ -12,7 +12,7 @@ import { Input } from "@components/UI/Input.tsx"; import { Label } from "@components/UI/Label.tsx"; import { channelSetToUrl } from "@core/utils/channelUrl.ts"; import { Protobuf } from "@core/protobuf.ts"; -import { useChannels } from "@meshtastic/sdk-react"; +import { useChannels } from "@core/kmp/hooks"; import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import { QRCode } from "react-qrcode-logo"; diff --git a/apps/web/src/components/Dialog/RebootDialog.test.tsx b/apps/web/src/components/Dialog/RebootDialog.test.tsx index edf4afcea..aee5cb243 100644 --- a/apps/web/src/components/Dialog/RebootDialog.test.tsx +++ b/apps/web/src/components/Dialog/RebootDialog.test.tsx @@ -21,10 +21,8 @@ let mockConnection: rebootOta: rebootOtaMock, }; -vi.mock("@core/stores", () => ({ - useDevice: () => ({ - connection: mockConnection, - }), +vi.mock("@core/kmp/hooks", () => ({ + useActiveClient: () => mockConnection, })); vi.mock("@components/UI/Button.tsx", async () => { diff --git a/apps/web/src/components/Dialog/RebootDialog.tsx b/apps/web/src/components/Dialog/RebootDialog.tsx index b6e4ed6f4..5988405d8 100644 --- a/apps/web/src/components/Dialog/RebootDialog.tsx +++ b/apps/web/src/components/Dialog/RebootDialog.tsx @@ -11,10 +11,10 @@ import { import { Input } from "@components/UI/Input.tsx"; import { Label } from "@components/UI/Label.tsx"; import { Separator } from "@components/UI/Separator.tsx"; -import { useDevice } from "@core/stores"; import { ClockIcon, OctagonXIcon, RefreshCwIcon } from "lucide-react"; import { useState } from "react"; import { useTranslation } from "react-i18next"; +import { useActiveClient } from "@core/kmp/hooks"; export interface RebootDialogProps { open: boolean; @@ -25,7 +25,7 @@ const DEFAULT_REBOOT_DELAY = 5; // seconds export const RebootDialog = ({ open, onOpenChange }: RebootDialogProps) => { const { t } = useTranslation("dialog"); - const { connection } = useDevice(); + const connection = useActiveClient(); const [time, setTime] = useState(DEFAULT_REBOOT_DELAY); const [isScheduled, setIsScheduled] = useState(false); const [isOTA, setIsOTA] = useState(false); diff --git a/apps/web/src/components/Dialog/RefreshKeysDialog/RefreshKeysDialog.test.tsx b/apps/web/src/components/Dialog/RefreshKeysDialog/RefreshKeysDialog.test.tsx index 2098e04d0..ef11fc0ab 100644 --- a/apps/web/src/components/Dialog/RefreshKeysDialog/RefreshKeysDialog.test.tsx +++ b/apps/web/src/components/Dialog/RefreshKeysDialog/RefreshKeysDialog.test.tsx @@ -1,6 +1,6 @@ import { CurrentDeviceContext, useDeviceStore } from "@core/stores"; -import { MeshRegistry } from "@meshtastic/sdk"; -import { MeshRegistryProvider } from "@meshtastic/sdk-react"; +import { MeshRegistryProvider } from "@core/kmp/hooks"; +import { MeshRegistry } from "@core/kmp/registry.ts"; import { render } from "@testing-library/react"; import { afterEach, beforeEach, expect, test, vi } from "vitest"; import { RefreshKeysDialog } from "./RefreshKeysDialog.tsx"; diff --git a/apps/web/src/components/Dialog/RefreshKeysDialog/RefreshKeysDialog.tsx b/apps/web/src/components/Dialog/RefreshKeysDialog/RefreshKeysDialog.tsx index f865eb2e9..f5f8235f0 100644 --- a/apps/web/src/components/Dialog/RefreshKeysDialog/RefreshKeysDialog.tsx +++ b/apps/web/src/components/Dialog/RefreshKeysDialog/RefreshKeysDialog.tsx @@ -7,7 +7,7 @@ import { DialogTitle, } from "@components/UI/Dialog.tsx"; import { useNodeAsProto } from "@core/hooks/useNodesAsProto.ts"; -import { useNodeErrors } from "@meshtastic/sdk-react"; +import { useNodeErrors } from "@core/kmp/hooks"; import { LockKeyholeOpenIcon } from "lucide-react"; import { useTranslation } from "react-i18next"; import { useRefreshKeysDialog } from "./useRefreshKeysDialog.ts"; diff --git a/apps/web/src/components/Dialog/RefreshKeysDialog/useRefreshKeysDialog.ts b/apps/web/src/components/Dialog/RefreshKeysDialog/useRefreshKeysDialog.ts index d1b1046d0..e88c70ecb 100644 --- a/apps/web/src/components/Dialog/RefreshKeysDialog/useRefreshKeysDialog.ts +++ b/apps/web/src/components/Dialog/RefreshKeysDialog/useRefreshKeysDialog.ts @@ -1,5 +1,5 @@ import { useDevice } from "@core/stores"; -import { useActiveClient, useNodeErrors } from "@meshtastic/sdk-react"; +import { useActiveClient, useNodeErrors } from "@core/kmp/hooks"; import { useCallback } from "react"; export function useRefreshKeysDialog() { diff --git a/apps/web/src/components/Dialog/RemoveNodeDialog.tsx b/apps/web/src/components/Dialog/RemoveNodeDialog.tsx index 08d947eeb..07a671db7 100644 --- a/apps/web/src/components/Dialog/RemoveNodeDialog.tsx +++ b/apps/web/src/components/Dialog/RemoveNodeDialog.tsx @@ -1,7 +1,7 @@ import { Label } from "@components/UI/Label.tsx"; import { useNodeAsProto } from "@core/hooks/useNodesAsProto.ts"; import { useAppStore } from "@core/stores"; -import { useActiveClient } from "@meshtastic/sdk-react"; +import { useActiveClient } from "@core/kmp/hooks"; import { useTranslation } from "react-i18next"; import { DialogWrapper } from "./DialogWrapper.tsx"; diff --git a/apps/web/src/components/Dialog/ResetNodeDbDialog/ResetNodeDbDialog.test.tsx b/apps/web/src/components/Dialog/ResetNodeDbDialog/ResetNodeDbDialog.test.tsx index 3f75bac27..c09b7af24 100644 --- a/apps/web/src/components/Dialog/ResetNodeDbDialog/ResetNodeDbDialog.test.tsx +++ b/apps/web/src/components/Dialog/ResetNodeDbDialog/ResetNodeDbDialog.test.tsx @@ -9,7 +9,8 @@ const { mockUseActiveClient } = vi.hoisted(() => ({ mockUseActiveClient: vi.fn(), })); -vi.mock("@meshtastic/sdk-react", () => ({ +vi.mock("@core/kmp/hooks", async (importOriginal) => ({ + ...(await importOriginal()), useActiveClient: mockUseActiveClient, })); diff --git a/apps/web/src/components/Dialog/ResetNodeDbDialog/ResetNodeDbDialog.tsx b/apps/web/src/components/Dialog/ResetNodeDbDialog/ResetNodeDbDialog.tsx index d3ca6e0c7..1014538e4 100644 --- a/apps/web/src/components/Dialog/ResetNodeDbDialog/ResetNodeDbDialog.tsx +++ b/apps/web/src/components/Dialog/ResetNodeDbDialog/ResetNodeDbDialog.tsx @@ -1,5 +1,5 @@ import { toast } from "@core/hooks/useToast.ts"; -import { useActiveClient } from "@meshtastic/sdk-react"; +import { useActiveClient } from "@core/kmp/hooks"; import { useTranslation } from "react-i18next"; import { DialogWrapper } from "../DialogWrapper.tsx"; diff --git a/apps/web/src/components/Dialog/ShutdownDialog.tsx b/apps/web/src/components/Dialog/ShutdownDialog.tsx index f482be2e8..2a01eb9d0 100644 --- a/apps/web/src/components/Dialog/ShutdownDialog.tsx +++ b/apps/web/src/components/Dialog/ShutdownDialog.tsx @@ -1,10 +1,10 @@ import { Button } from "@components/UI/Button.tsx"; import { Input } from "@components/UI/Input.tsx"; -import { useDevice } from "@core/stores"; import { ClockIcon, PowerIcon } from "lucide-react"; import { useState } from "react"; import { useTranslation } from "react-i18next"; import { DialogWrapper } from "./DialogWrapper.tsx"; +import { useActiveClient } from "@core/kmp/hooks"; export interface ShutdownDialogProps { open: boolean; @@ -13,7 +13,7 @@ export interface ShutdownDialogProps { export const ShutdownDialog = ({ open, onOpenChange }: ShutdownDialogProps) => { const { t } = useTranslation("dialog"); - const { connection } = useDevice(); + const connection = useActiveClient(); const [time, setTime] = useState(5); const handleScheduledShutdown = () => { diff --git a/apps/web/src/components/PageComponents/Channels/BeaconOffers.tsx b/apps/web/src/components/PageComponents/Channels/BeaconOffers.tsx index e75970a1b..40feee308 100644 --- a/apps/web/src/components/PageComponents/Channels/BeaconOffers.tsx +++ b/apps/web/src/components/PageComponents/Channels/BeaconOffers.tsx @@ -3,9 +3,9 @@ import { type JoinableBeaconOffer, useBeaconOffers, } from "@core/hooks/useBeaconOffers.ts"; -import type { Node } from "@meshtastic/sdk"; +import type { Node } from "@core/storage/types.ts"; import { Protobuf } from "@core/protobuf.ts"; -import { useNodes } from "@meshtastic/sdk-react"; +import { useNodes } from "@core/kmp/hooks"; import { RadioTowerIcon } from "lucide-react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/Channels/Channels.tsx b/apps/web/src/components/PageComponents/Channels/Channels.tsx index 6dc7ca3fb..1bf37a145 100644 --- a/apps/web/src/components/PageComponents/Channels/Channels.tsx +++ b/apps/web/src/components/PageComponents/Channels/Channels.tsx @@ -4,7 +4,7 @@ import { useDeviceCapabilities } from "@core/hooks/useDeviceCapabilities.ts"; import { useDevice } from "@core/stores"; import { firmwareAtLeast } from "@core/utils/firmware.ts"; import type { Protobuf } from "@core/protobuf.ts"; -import { useChannels } from "@meshtastic/sdk-react"; +import { useChannels } from "@core/kmp/hooks"; import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import i18next from "i18next"; import { PlusIcon, QrCodeIcon, UploadIcon } from "lucide-react"; diff --git a/apps/web/src/components/PageComponents/Map/Layers/NodesLayer.tsx b/apps/web/src/components/PageComponents/Map/Layers/NodesLayer.tsx index 2630a9ec0..32aa92612 100644 --- a/apps/web/src/components/PageComponents/Map/Layers/NodesLayer.tsx +++ b/apps/web/src/components/PageComponents/Map/Layers/NodesLayer.tsx @@ -15,7 +15,7 @@ import { PopupWrapper } from "@components/PageComponents/Map/Popups/PopupWrapper import { useMapFitting } from "@core/hooks/useMapFitting"; import { hasPos, toLngLat } from "@core/utils/geo.ts"; import type { Protobuf } from "@core/protobuf.ts"; -import { useNodeErrors } from "@meshtastic/sdk-react"; +import { useNodeErrors } from "@core/kmp/hooks"; import { useCallback, useMemo } from "react"; import { useTranslation } from "react-i18next"; import type { MapRef } from "react-map-gl/maplibre"; diff --git a/apps/web/src/components/PageComponents/Messages/MessageInput.test.tsx b/apps/web/src/components/PageComponents/Messages/MessageInput.test.tsx index 27992c4f3..f94285779 100644 --- a/apps/web/src/components/PageComponents/Messages/MessageInput.test.tsx +++ b/apps/web/src/components/PageComponents/Messages/MessageInput.test.tsx @@ -1,4 +1,4 @@ -import type { ConversationKey } from "@meshtastic/sdk"; +import type { ConversationKey } from "@core/storage/types.ts"; import { act, fireEvent, @@ -40,7 +40,8 @@ const mockSetText = vi.fn(); const mockClear = vi.fn(); let mockDraftText = ""; -vi.mock("@meshtastic/sdk-react", () => ({ +vi.mock("@core/kmp/hooks", async (importOriginal) => ({ + ...(await importOriginal()), useDraft: vi.fn(() => ({ text: mockDraftText, setText: mockSetText, diff --git a/apps/web/src/components/PageComponents/Messages/MessageInput.tsx b/apps/web/src/components/PageComponents/Messages/MessageInput.tsx index 45669d4c0..2e544d0ce 100644 --- a/apps/web/src/components/PageComponents/Messages/MessageInput.tsx +++ b/apps/web/src/components/PageComponents/Messages/MessageInput.tsx @@ -1,7 +1,7 @@ import { Button } from "@components/UI/Button.tsx"; import { Input } from "@components/UI/Input.tsx"; -import type { ConversationKey } from "@meshtastic/sdk"; -import { useDraft } from "@meshtastic/sdk-react"; +import type { ConversationKey } from "@core/storage/types.ts"; +import { useDraft } from "@core/kmp/hooks"; import { SendIcon } from "lucide-react"; import { startTransition, useState } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/Messages/MessageItem.test.tsx b/apps/web/src/components/PageComponents/Messages/MessageItem.test.tsx index a1d8d2eb2..726298910 100644 --- a/apps/web/src/components/PageComponents/Messages/MessageItem.test.tsx +++ b/apps/web/src/components/PageComponents/Messages/MessageItem.test.tsx @@ -29,7 +29,8 @@ vi.mock("@core/hooks/useNodesAsProto.ts", () => ({ vi.mock("@components/UI/Avatar.tsx", () => ({ Avatar: () => null })); const resend = vi.fn(() => Promise.resolve({ status: "ok", value: 2 })); -vi.mock("@meshtastic/sdk-react", () => ({ +vi.mock("@core/kmp/hooks", async (importOriginal) => ({ + ...(await importOriginal()), useActiveClient: () => ({ chat: { resend } }), })); diff --git a/apps/web/src/components/PageComponents/Messages/MessageStatus.tsx b/apps/web/src/components/PageComponents/Messages/MessageStatus.tsx index 42025c32f..44751673d 100644 --- a/apps/web/src/components/PageComponents/Messages/MessageStatus.tsx +++ b/apps/web/src/components/PageComponents/Messages/MessageStatus.tsx @@ -6,7 +6,7 @@ import { messageStatus, } from "@core/utils/messageStatus.ts"; import { MessageState } from "@core/stores/messageStore"; -import { useActiveClient } from "@meshtastic/sdk-react"; +import { useActiveClient } from "@core/kmp/hooks"; import type { LucideIcon } from "lucide-react"; import { AlertCircle, diff --git a/apps/web/src/components/PageComponents/ModuleConfig/MQTT.test.tsx b/apps/web/src/components/PageComponents/ModuleConfig/MQTT.test.tsx index 64e3bcd26..7019fc459 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/MQTT.test.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/MQTT.test.tsx @@ -38,7 +38,7 @@ describe("MQTT module config", () => { ); expect((await editor.commit()).status).toBe("ok"); - const wire = radio.sentModuleConfig("mqtt"); + const wire = radio.sentModuleConfig("mqtt")?.value; expect(wire?.enabled).toBe(true); // Fields the user didn't touch still round-trip. expect(wire?.address).toBe("mqtt.example.org"); @@ -81,7 +81,7 @@ describe("MQTT module config", () => { expect(editor.dirtyModuleSections.value).toContain("mqtt"); expect((await editor.commit()).status).toBe("ok"); - expect(radio.sentModuleConfig("mqtt")?.enabled).toBe(true); + expect(radio.sentModuleConfig("mqtt")?.value.enabled).toBe(true); expect(editor.isDirty.value).toBe(false); }); }); diff --git a/apps/web/src/components/PageComponents/ModuleConfig/MeshBeacon.tsx b/apps/web/src/components/PageComponents/ModuleConfig/MeshBeacon.tsx index bfe06c507..5ac5b9de0 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/MeshBeacon.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/MeshBeacon.tsx @@ -18,7 +18,7 @@ import { useDevice } from "@core/stores"; import { channelSettingsByIndex } from "@core/utils/beaconJoin.ts"; import { getRegionPresetGroup } from "@core/utils/loraPresets.ts"; import { Protobuf } from "@core/protobuf.ts"; -import { useChannels } from "@meshtastic/sdk-react"; +import { useChannels } from "@core/kmp/hooks"; import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useMemo } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/ModuleConfig/RangeTest.tsx b/apps/web/src/components/PageComponents/ModuleConfig/RangeTest.tsx index 25454771c..0933f80bf 100644 --- a/apps/web/src/components/PageComponents/ModuleConfig/RangeTest.tsx +++ b/apps/web/src/components/PageComponents/ModuleConfig/RangeTest.tsx @@ -9,7 +9,7 @@ import { } from "@components/Form/DynamicForm.tsx"; import { useDevice } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; -import { useChannel } from "@meshtastic/sdk-react"; +import { useChannel } from "@core/kmp/hooks"; import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/PageComponents/Settings/DeviceConfig.test.tsx b/apps/web/src/components/PageComponents/Settings/DeviceConfig.test.tsx index e1e8956cc..de4e2fb0a 100644 --- a/apps/web/src/components/PageComponents/Settings/DeviceConfig.test.tsx +++ b/apps/web/src/components/PageComponents/Settings/DeviceConfig.test.tsx @@ -62,7 +62,7 @@ describe("Device settings", () => { ); expect((await editor.commit()).status).toBe("ok"); - const wire = radio.sentConfig("device"); + const wire = radio.sentConfig("device")?.value; expect(wire?.doubleTapAsButtonPress).toBe(true); expect(wire?.buttonGpio).toBe(4); expect(wire?.buzzerGpio).toBe(2); @@ -94,7 +94,7 @@ describe("Device settings", () => { expect(editor.dirtyRadioSections.value).toContain("device"); expect((await editor.commit()).status).toBe("ok"); - expect(radio.sentConfig("device")?.doubleTapAsButtonPress).toBe(true); + expect(radio.sentConfig("device")?.value.doubleTapAsButtonPress).toBe(true); expect(editor.isDirty.value).toBe(false); }); @@ -111,7 +111,7 @@ describe("Device settings", () => { ); expect((await editor.commit()).status).toBe("ok"); - expect(radio.sentConfig("bluetooth")?.enabled).toBe(true); + expect(radio.sentConfig("bluetooth")?.value.enabled).toBe(true); }); it("still requires a six-digit PIN for FIXED_PIN pairing", () => { diff --git a/apps/web/src/components/PageComponents/SettingsPages/useDeviceConnected.ts b/apps/web/src/components/PageComponents/SettingsPages/useDeviceConnected.ts index 64f99a681..b1f37ebf1 100644 --- a/apps/web/src/components/PageComponents/SettingsPages/useDeviceConnected.ts +++ b/apps/web/src/components/PageComponents/SettingsPages/useDeviceConnected.ts @@ -3,9 +3,6 @@ import { Types } from "@core/protobuf.ts"; /** True once the active node is connected and configured. */ export function useDeviceConnected(): boolean { - const { connection, status } = useDevice(); - return ( - connection !== undefined && - status === Types.DeviceStatusEnum.DeviceConfigured - ); + const { status } = useDevice(); + return status === Types.DeviceStatusEnum.DeviceConfigured; } diff --git a/apps/web/src/components/RegionSetupReminder.tsx b/apps/web/src/components/RegionSetupReminder.tsx index 35952c079..c7b7b794f 100644 --- a/apps/web/src/components/RegionSetupReminder.tsx +++ b/apps/web/src/components/RegionSetupReminder.tsx @@ -1,6 +1,6 @@ import { Button } from "@components/UI/Button.tsx"; import { useToast } from "@core/hooks/useToast.ts"; -import { useIsRegionUnset } from "@meshtastic/sdk-react"; +import { useIsRegionUnset } from "@core/kmp/hooks"; import { useNavigate } from "@tanstack/react-router"; import { useEffect, useRef } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index c5c8cbf03..0a4dee100 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -17,7 +17,7 @@ import { } from "@core/stores"; import { useIsMobile } from "@core/hooks/useIsMobile.ts"; import { cn } from "@core/utils/cn.ts"; -import { useTotalUnread } from "@meshtastic/sdk-react"; +import { useTotalUnread } from "@core/kmp/hooks"; import { useLocation, useNavigate } from "@tanstack/react-router"; import { CircleChevronLeft, diff --git a/apps/web/src/core/connections/lna.ts b/apps/web/src/core/connections/lna.ts new file mode 100644 index 000000000..29b9d3131 --- /dev/null +++ b/apps/web/src/core/connections/lna.ts @@ -0,0 +1,35 @@ +interface LocalNetworkRequestInit extends RequestInit { + targetAddressSpace?: "local" | "private" | "public"; +} + +/** + * Marks a plain-HTTP request from an HTTPS page as targeting the local + * network, so Chrome's Local Network Access gate lets it through once the + * user has granted the permission. Loopback is its own address space and + * already trusted, so it needs no annotation. + */ +export function withLocalNetworkTarget( + url: string, + init: RequestInit = {}, +): LocalNetworkRequestInit { + if (!url.startsWith("http:") || globalThis.location?.protocol !== "https:") { + return init; + } + if (isLoopback(url)) return init; + return { ...init, targetAddressSpace: "local" }; +} + +function isLoopback(url: string): boolean { + let host: string; + try { + host = new URL(url).hostname.toLowerCase(); + } catch { + return false; + } + return ( + host === "localhost" || + host.endsWith(".localhost") || + host === "[::1]" || + /^127\.\d+\.\d+\.\d+$/.test(host) + ); +} diff --git a/apps/web/src/core/connections/repositories.ts b/apps/web/src/core/connections/repositories.ts new file mode 100644 index 000000000..02cf06c2d --- /dev/null +++ b/apps/web/src/core/connections/repositories.ts @@ -0,0 +1,81 @@ +import type { SessionOptions } from "@core/kmp/session.ts"; +import { createLogger } from "@core/log.ts"; +import { coordinator, getStorageDb } from "@core/sdkStorage.ts"; +import { SqlocalDraftRepository } from "@core/storage/drafts.ts"; +import { SqlocalMessageRepository } from "@core/storage/messages.ts"; +import { SqlocalNodesRepository } from "@core/storage/nodes.ts"; +import { SqlocalTelemetryRepository } from "@core/storage/telemetry.ts"; + +const log = createLogger("repositories"); + +const CHAT_RETENTION = { + maxPerBucket: 1000, + olderThanMs: 1000 * 60 * 60 * 24 * 90, +}; +const TELEMETRY_RETENTION = { + maxPerNode: 500, + olderThanMs: 1000 * 60 * 60 * 24 * 30, +}; +const STORAGE_OPEN_TIMEOUT_MS = 5000; + +/** + * Storage scope used until the radio's node number is known. Node numbers + * and connection ids are both unsigned 32-bit, so no stored row has it and + * nothing is shown before the handshake names the radio. + */ +export const UNKNOWN_NODE_SCOPE = -1; + +/** + * Opens the message, draft, node and telemetry repositories against the + * shared OPFS-backed SQLite DB, scoped to `nodeNum` (the node this + * connection reached last time) so every connection to the same radio + * shares one history. If sqlocal is unavailable, hangs longer than + * `STORAGE_OPEN_TIMEOUT_MS`, or fails, the session runs without + * persistence and `persistent` is false. + */ +export async function openRepositories( + nodeNum?: number, +): Promise<{ options: SessionOptions; persistent: boolean }> { + const scope = nodeNum ?? UNKNOWN_NODE_SCOPE; + try { + const t0 = Date.now(); + const { db, persistent } = await Promise.race([ + getStorageDb(), + new Promise((_, reject) => + setTimeout( + () => + reject( + new Error( + `sqlocal DB open did not resolve within ${STORAGE_OPEN_TIMEOUT_MS}ms`, + ), + ), + STORAGE_OPEN_TIMEOUT_MS, + ), + ), + ]); + log.debug("openRepositories: storage DB ready", { + ms: Date.now() - t0, + persistent, + }); + return { + persistent, + options: { + messages: new SqlocalMessageRepository(db, { + deviceId: scope, + coordinator, + }), + drafts: new SqlocalDraftRepository(db, { deviceId: scope }), + nodes: new SqlocalNodesRepository(db, { deviceId: scope }), + telemetry: new SqlocalTelemetryRepository(db, { deviceId: scope }), + chatRetention: CHAT_RETENTION, + telemetryRetention: TELEMETRY_RETENTION, + }, + }; + } catch (err) { + log.warn("openRepositories: sqlocal unavailable, running in memory", { + name: err instanceof Error ? err.name : undefined, + message: err instanceof Error ? err.message : String(err), + }); + return { persistent: false, options: {} }; + } +} diff --git a/apps/web/src/core/connections/sdkClient.ts b/apps/web/src/core/connections/sdkClient.ts deleted file mode 100644 index d97c5a664..000000000 --- a/apps/web/src/core/connections/sdkClient.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { coordinator, getStorageDb } from "@core/sdkStorage.ts"; -import type { ConnectionId } from "@core/stores/deviceStore/types"; -import { createLogger } from "@core/log.ts"; -import { MeshDevice, type Transport } from "@meshtastic/sdk"; -import { SqlocalDraftRepository } from "@core/storage/drafts.ts"; -import { SqlocalMessageRepository } from "@core/storage/messages.ts"; -import { SqlocalNodesRepository } from "@core/storage/nodes.ts"; -import { SqlocalTelemetryRepository } from "@core/storage/telemetry.ts"; - -const log = createLogger("sdkClient"); - -const CHAT_RETENTION = { - maxPerBucket: 1000, - olderThanMs: 1000 * 60 * 60 * 24 * 90, -} as const; -const TELEMETRY_RETENTION = { - maxPerNode: 500, - olderThanMs: 1000 * 60 * 60 * 24 * 30, -} as const; -const STORAGE_OPEN_TIMEOUT_MS = 5000; - -/** - * Storage scope used until the radio's node number is known. Node numbers - * and connection ids are both unsigned 32-bit, so no stored row has it and - * nothing is shown before the handshake names the radio. - */ -export const UNKNOWN_NODE_SCOPE = -1; - -/** - * Builds a MeshDevice wired with persistence repositories opened against the - * shared OPFS-backed SQLite DB. - * - * History is stored per radio, not per saved connection: the repositories - * are scoped to `nodeNum` (the node this connection reached last time), so - * serial, Bluetooth and HTTP connections to the same radio share messages, - * drafts, nodes and telemetry. When `nodeNum` is unknown, or the radio turns - * out to be a different node, the SDK rescopes to the node number my_info - * reports (`storageScope: "node"`). - * - * Rows written before this was per node sit under the connection id in the - * same `device_id` column and are no longer read. Connection ids come from - * `randId()`, a uniformly random unsigned 32-bit integer, and node numbers - * are unsigned 32-bit too, so a given id matches a given node number with - * odds of 1 in 2^32 (about 4.3 billion). If it did, that node's history - * would also show the old rows of that one connection; nothing is lost. - * If sqlocal is unavailable, hangs longer than - * `STORAGE_OPEN_TIMEOUT_MS`, or fails for any reason, falls through to the - * SDK's in-memory repositories so the connect path is never blocked by - * persistence. `persistent` is false then: nothing from this session will - * be saved. - */ -export async function buildMeshDevice( - connectionId: ConnectionId, - deviceId: number, - transport: Transport, - nodeNum?: number, - { heartbeat = true }: { heartbeat?: boolean } = {}, -): Promise<{ meshDevice: MeshDevice; persistent: boolean }> { - log.debug("buildMeshDevice: enter", { connectionId, deviceId, nodeNum }); - const scope = nodeNum ?? UNKNOWN_NODE_SCOPE; - let chatRepository: SqlocalMessageRepository | undefined; - let draftRepository: SqlocalDraftRepository | undefined; - let nodesRepository: SqlocalNodesRepository | undefined; - let telemetryRepository: SqlocalTelemetryRepository | undefined; - let persistent = false; - try { - const t0 = Date.now(); - const { db, persistent: saved } = await Promise.race([ - getStorageDb(), - new Promise((_, reject) => - setTimeout( - () => - reject( - new Error( - `sqlocal DB open did not resolve within ${STORAGE_OPEN_TIMEOUT_MS}ms`, - ), - ), - STORAGE_OPEN_TIMEOUT_MS, - ), - ), - ]); - persistent = saved; - log.debug("buildMeshDevice: storage DB ready", { - ms: Date.now() - t0, - persistent, - }); - chatRepository = new SqlocalMessageRepository(db, { - deviceId: scope, - coordinator, - }); - draftRepository = new SqlocalDraftRepository(db, { - deviceId: scope, - }); - nodesRepository = new SqlocalNodesRepository(db, { - deviceId: scope, - }); - telemetryRepository = new SqlocalTelemetryRepository(db, { - deviceId: scope, - }); - log.debug("buildMeshDevice: repositories opened"); - } catch (err) { - const e = err as Error; - log.warn( - "buildMeshDevice: sqlocal unavailable, falling back to in-memory", - { - name: e?.name, - message: e?.message, - }, - ); - } - - const meshDevice = new MeshDevice(transport, { - configId: deviceId, - heartbeatIntervalMs: heartbeat ? undefined : false, - storageScope: "node", - storageNodeNum: nodeNum, - chat: - chatRepository || draftRepository - ? { - repository: chatRepository, - draftRepository, - retention: CHAT_RETENTION, - } - : undefined, - nodes: nodesRepository ? { repository: nodesRepository } : undefined, - telemetry: telemetryRepository - ? { repository: telemetryRepository, retention: TELEMETRY_RETENTION } - : undefined, - }); - return { meshDevice, persistent }; -} diff --git a/apps/web/src/core/hooks/useBeaconOffers.ts b/apps/web/src/core/hooks/useBeaconOffers.ts index 9c3e5a706..ed46f56ab 100644 --- a/apps/web/src/core/hooks/useBeaconOffers.ts +++ b/apps/web/src/core/hooks/useBeaconOffers.ts @@ -6,10 +6,9 @@ import { channelSettingsByIndex, planBeaconJoin, } from "@core/utils/beaconJoin.ts"; -import type { MeshBeaconOffer } from "@meshtastic/sdk"; -import { useActiveClient, useChannels } from "@meshtastic/sdk-react"; -import { useSignal } from "@core/kmp/hooks"; +import type { MeshBeaconOffer } from "@core/kmp/channels.ts"; import { useCallback, useMemo } from "react"; +import { useActiveClient, useChannels, useSignal } from "@core/kmp/hooks"; export interface JoinableBeaconOffer { readonly key: string; diff --git a/apps/web/src/core/hooks/useChatAsLegacyMessages.test.ts b/apps/web/src/core/hooks/useChatAsLegacyMessages.test.ts index af13e3b7e..491f89f46 100644 --- a/apps/web/src/core/hooks/useChatAsLegacyMessages.test.ts +++ b/apps/web/src/core/hooks/useChatAsLegacyMessages.test.ts @@ -2,7 +2,7 @@ import { MessageState, MessageType } from "@core/stores/messageStore"; import { type Message as SdkMessage, MessageState as SdkMessageState, -} from "@meshtastic/sdk"; +} from "@core/storage/types.ts"; import { Protobuf, type Types } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { toLegacy } from "./useChatAsLegacyMessages.ts"; diff --git a/apps/web/src/core/hooks/useChatAsLegacyMessages.ts b/apps/web/src/core/hooks/useChatAsLegacyMessages.ts index d697f44ee..a466c7862 100644 --- a/apps/web/src/core/hooks/useChatAsLegacyMessages.ts +++ b/apps/web/src/core/hooks/useChatAsLegacyMessages.ts @@ -3,10 +3,12 @@ import { MessageState as LegacyMessageState, MessageType, } from "@core/stores/messageStore"; -import type { Message as SdkMessage } from "@meshtastic/sdk"; -import { MessageState as SdkMessageState } from "@meshtastic/sdk"; +import { useChat, useDirectChat } from "@core/kmp/hooks"; import type { Types } from "@core/protobuf.ts"; -import { useChat, useDirectChat } from "@meshtastic/sdk-react"; +import { + type Message as SdkMessage, + MessageState as SdkMessageState, +} from "@core/storage/types.ts"; import { useMemo } from "react"; /** @@ -35,9 +37,7 @@ export function useChatAsLegacyMessages( params: UseChatAsLegacyMessagesParams, ): LegacyMessage[] { const broadcast = useChat( - params.type === MessageType.Broadcast - ? params.channelId - : (0 as Types.ChannelNumber), + params.type === MessageType.Broadcast ? params.channelId : 0, ); const direct = useDirectChat( params.type === MessageType.Direct ? params.peer : 0, @@ -57,8 +57,7 @@ export function toLegacy( message: SdkMessage, params: UseChatAsLegacyMessagesParams, ): LegacyMessage { - const legacy = { - type: params.type, + const base = { channel: message.channel, to: message.to, from: message.from, @@ -66,7 +65,11 @@ export function toLegacy( messageId: message.id, state: mapState(message.state), message: message.text, - } as LegacyMessage; + }; + const legacy: LegacyMessage = + params.type === MessageType.Direct + ? { ...base, type: MessageType.Direct } + : { ...base, type: MessageType.Broadcast }; if (message.signed !== undefined) { legacy.signed = message.signed; } diff --git a/apps/web/src/core/hooks/useChatLegacy.ts b/apps/web/src/core/hooks/useChatLegacy.ts deleted file mode 100644 index 0f0810d3a..000000000 --- a/apps/web/src/core/hooks/useChatLegacy.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { - type Message as LegacyMessage, - MessageType, -} from "@core/stores/messageStore"; -import type { Types } from "@core/protobuf.ts"; -import { useChat, useDirectChat } from "@meshtastic/sdk-react"; -import { useMemo } from "react"; -import { toLegacy } from "./useChatAsLegacyMessages.ts"; - -/** - * Adapter that surfaces SDK-managed chat history in the shape expected by - * the pre-SDK message components (`Message` from `messageStore`). Lets - * MessagesPage / ChannelChat / MessageItem keep their current props while - * reading from the OPFS-backed SQLite repository through the SDK chat - * slice. Removed once those components consume `Message` from the SDK - * directly. - */ -export interface UseChatAsLegacyMessagesBroadcast { - type: MessageType.Broadcast; - channelId: Types.ChannelNumber; -} - -export interface UseChatAsLegacyMessagesDirect { - type: MessageType.Direct; - peer: number; -} - -export type UseChatAsLegacyMessagesParams = - | UseChatAsLegacyMessagesBroadcast - | UseChatAsLegacyMessagesDirect; - -export function useChatAsLegacyMessages( - params: UseChatAsLegacyMessagesParams, -): LegacyMessage[] { - const broadcast = useChat( - params.type === MessageType.Broadcast - ? params.channelId - : (0 as Types.ChannelNumber), - ); - const direct = useDirectChat( - params.type === MessageType.Direct ? params.peer : 0, - ); - const sdkMessages = - params.type === MessageType.Broadcast - ? broadcast.messages - : direct.messages; - - return useMemo( - () => sdkMessages.map((m) => toLegacy(m, params)), - [sdkMessages, params], - ); -} diff --git a/apps/web/src/core/hooks/useDeviceCapabilities.ts b/apps/web/src/core/hooks/useDeviceCapabilities.ts index 9fbec483f..89c884f90 100644 --- a/apps/web/src/core/hooks/useDeviceCapabilities.ts +++ b/apps/web/src/core/hooks/useDeviceCapabilities.ts @@ -1,8 +1,7 @@ import { useDevice } from "@core/stores"; import { firmwareAtLeast } from "@core/utils/firmware.ts"; import type { Protobuf } from "@core/protobuf.ts"; -import { useActiveClient } from "@meshtastic/sdk-react"; -import { useSignal } from "@core/kmp/hooks"; +import { useActiveClient, useSignal } from "@core/kmp/hooks"; const EMPTY_REGION_PRESETS_SIGNAL = { value: undefined as Protobuf.Mesh.LoRaRegionPresetMap | undefined, diff --git a/apps/web/src/core/hooks/useFavoriteNode.test.ts b/apps/web/src/core/hooks/useFavoriteNode.test.ts index 7e181af84..a3f04262e 100644 --- a/apps/web/src/core/hooks/useFavoriteNode.test.ts +++ b/apps/web/src/core/hooks/useFavoriteNode.test.ts @@ -10,7 +10,8 @@ const { mockUseActiveClient } = vi.hoisted(() => ({ mockUseActiveClient: vi.fn(), })); -vi.mock("@meshtastic/sdk-react", () => ({ +vi.mock("@core/kmp/hooks", async (importOriginal) => ({ + ...(await importOriginal()), useActiveClient: mockUseActiveClient, })); diff --git a/apps/web/src/core/hooks/useFavoriteNode.ts b/apps/web/src/core/hooks/useFavoriteNode.ts index 59b35b3c6..2d31c8295 100644 --- a/apps/web/src/core/hooks/useFavoriteNode.ts +++ b/apps/web/src/core/hooks/useFavoriteNode.ts @@ -1,5 +1,5 @@ import { useToast } from "@core/hooks/useToast.ts"; -import { useActiveClient } from "@meshtastic/sdk-react"; +import { useActiveClient } from "@core/kmp/hooks"; import { useCallback } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/core/hooks/useIgnoreNode.test.ts b/apps/web/src/core/hooks/useIgnoreNode.test.ts index 0ddc0e245..bad2d6b6e 100644 --- a/apps/web/src/core/hooks/useIgnoreNode.test.ts +++ b/apps/web/src/core/hooks/useIgnoreNode.test.ts @@ -10,7 +10,8 @@ const { mockUseActiveClient } = vi.hoisted(() => ({ mockUseActiveClient: vi.fn(), })); -vi.mock("@meshtastic/sdk-react", () => ({ +vi.mock("@core/kmp/hooks", async (importOriginal) => ({ + ...(await importOriginal()), useActiveClient: mockUseActiveClient, })); diff --git a/apps/web/src/core/hooks/useIgnoreNode.ts b/apps/web/src/core/hooks/useIgnoreNode.ts index 73dd1fea3..24fb836c2 100644 --- a/apps/web/src/core/hooks/useIgnoreNode.ts +++ b/apps/web/src/core/hooks/useIgnoreNode.ts @@ -1,5 +1,5 @@ import { useToast } from "@core/hooks/useToast.ts"; -import { useActiveClient } from "@meshtastic/sdk-react"; +import { useActiveClient } from "@core/kmp/hooks"; import { useCallback } from "react"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/core/hooks/useLockdown.ts b/apps/web/src/core/hooks/useLockdown.ts index 646466e99..d549055c8 100644 --- a/apps/web/src/core/hooks/useLockdown.ts +++ b/apps/web/src/core/hooks/useLockdown.ts @@ -1,7 +1,6 @@ -import type { MeshClient } from "@meshtastic/sdk"; +import type { MeshSession } from "@core/kmp/session.ts"; import type { Protobuf } from "@core/protobuf.ts"; -import { useActiveClient } from "@meshtastic/sdk-react"; -import { useSignal } from "@core/kmp/hooks"; +import { useActiveClient, useSignal } from "@core/kmp/hooks"; type LockdownStatus = Protobuf.Mesh.LockdownStatus | undefined; @@ -19,7 +18,7 @@ const NOT_LOCKED = { }; export interface UseLockdownResult { - client: MeshClient | undefined; + client: MeshSession | undefined; /** Latest lockdown status; undefined when the firmware has no lockdown. */ status: LockdownStatus; /** True while the device withholds its config until it is unlocked. */ diff --git a/apps/web/src/core/hooks/useNodeTelemetryHistory.ts b/apps/web/src/core/hooks/useNodeTelemetryHistory.ts index 2b16f8bef..38721269d 100644 --- a/apps/web/src/core/hooks/useNodeTelemetryHistory.ts +++ b/apps/web/src/core/hooks/useNodeTelemetryHistory.ts @@ -1,7 +1,7 @@ -import type { ReadonlySignal, TelemetryReading } from "@meshtastic/sdk"; -import { useActiveClient } from "@meshtastic/sdk-react"; -import { useSignal } from "@core/kmp/hooks"; +import type { ReadonlySignal } from "@core/kmp/signals.ts"; +import type { TelemetryReading } from "@core/storage/types.ts"; import { useMemo } from "react"; +import { useActiveClient, useSignal } from "@core/kmp/hooks"; const EMPTY_HISTORY: TelemetryReading[] = []; const EMPTY_HISTORY_SIGNAL: ReadonlySignal = { diff --git a/apps/web/src/core/hooks/useNodesAsProto.test.ts b/apps/web/src/core/hooks/useNodesAsProto.test.ts index b8d14e9fa..674b5599c 100644 --- a/apps/web/src/core/hooks/useNodesAsProto.test.ts +++ b/apps/web/src/core/hooks/useNodesAsProto.test.ts @@ -1,4 +1,4 @@ -import type { Node as SdkNode } from "@meshtastic/sdk"; +import type { Node as SdkNode } from "@core/storage/types.ts"; import { describe, expect, it } from "vitest"; import { toNodeInfo } from "./useNodesAsProto.ts"; diff --git a/apps/web/src/core/hooks/useNodesAsProto.ts b/apps/web/src/core/hooks/useNodesAsProto.ts index 0c87b4fc1..4253528ea 100644 --- a/apps/web/src/core/hooks/useNodesAsProto.ts +++ b/apps/web/src/core/hooks/useNodesAsProto.ts @@ -1,9 +1,8 @@ import { create } from "@bufbuild/protobuf"; -import type { Node as SdkNode } from "@meshtastic/sdk"; +import type { Node as SdkNode } from "@core/storage/types.ts"; import { Protobuf } from "@core/protobuf.ts"; -import { useActiveClient } from "@meshtastic/sdk-react"; -import { useSignal } from "@core/kmp/hooks"; import { useMemo } from "react"; +import { useActiveClient, useSignal } from "@core/kmp/hooks"; /** * Adapter hooks that surface SDK-managed nodes in the diff --git a/apps/web/src/core/hooks/useNodesLegacy.ts b/apps/web/src/core/hooks/useNodesLegacy.ts deleted file mode 100644 index 30de94a12..000000000 --- a/apps/web/src/core/hooks/useNodesLegacy.ts +++ /dev/null @@ -1,43 +0,0 @@ -import type { Protobuf } from "@core/protobuf.ts"; -import { useMeshDevice, useNodes } from "@meshtastic/sdk-react"; -import { useMemo } from "react"; -import { toNodeInfo } from "./useNodesAsProto.ts"; - -/** - * Adapter hooks that surface SDK-managed nodes in the legacy - * `Protobuf.Mesh.NodeInfo` shape consumed by web components today. - * - * Lets components migrate off the Zustand `useNodeDB().getNodes/getNode` - * API one at a time without rewriting their templates. Removed once - * every consumer reads `Node` from the SDK directly. - */ - -export function useNodesAsProto(): Protobuf.Mesh.NodeInfo[] { - const nodes = useNodes(); - return useMemo(() => nodes.map(toNodeInfo), [nodes]); -} - -export function useNodeAsProto( - nodeNum: number, -): Protobuf.Mesh.NodeInfo | undefined { - const nodes = useNodes(); - return useMemo(() => { - const found = nodes.find((n) => n.num === nodeNum); - return found ? toNodeInfo(found) : undefined; - }, [nodes, nodeNum]); -} - -/** - * "My node" — the node info for the locally-connected device, if its - * NodeInfo packet has been observed yet. Returns undefined while the - * device is still configuring. - */ -export function useMyNodeAsProto(): Protobuf.Mesh.NodeInfo | undefined { - const { myNodeNum } = useMeshDevice(); - const nodes = useNodes(); - return useMemo(() => { - if (myNodeNum === undefined) return undefined; - const found = nodes.find((n) => n.num === myNodeNum); - return found ? toNodeInfo(found) : undefined; - }, [myNodeNum, nodes]); -} diff --git a/apps/web/src/core/kmp/channels.ts b/apps/web/src/core/kmp/channels.ts new file mode 100644 index 000000000..98ddf45d3 --- /dev/null +++ b/apps/web/src/core/kmp/channels.ts @@ -0,0 +1,73 @@ +import { fromBinary } from "@bufbuild/protobuf"; +import { Protobuf, type Types } from "@core/protobuf.ts"; +import { signal } from "@preact/signals-core"; +import { type ReadonlySignal, toReadonly } from "./signals.ts"; + +export interface Channel { + readonly index: number; + readonly role: Protobuf.Channel.Channel_Role; + readonly settings?: Protobuf.Channel.ChannelSettings; +} + +/** A Mesh Beacon invitation heard from another node. */ +export interface MeshBeaconOffer { + readonly from: number; + readonly rxTime: Date; + readonly beacon: Protobuf.MeshBeacon.MeshBeacon; +} + +export function channelFromProto(channel: Protobuf.Channel.Channel): Channel { + return { + index: channel.index, + role: channel.role, + settings: channel.settings, + }; +} + +/** The device's channel table and the Mesh Beacon offers heard this session. */ +export class ChannelsClient { + private readonly channels = signal>(new Map()); + private readonly listStore = signal>([]); + private readonly offers = signal>([]); + + readonly list: ReadonlySignal>; + /** Newest first, one per sender; our own and channel-less beacons are skipped. */ + readonly beaconOffers: ReadonlySignal>; + + constructor(private readonly myNodeNum: () => number | undefined) { + this.list = toReadonly(this.listStore); + this.beaconOffers = toReadonly(this.offers); + } + + applyChannel(channel: Protobuf.Channel.Channel): void { + const next = new Map(this.channels.peek()); + next.set(channel.index, channelFromProto(channel)); + this.channels.value = next; + this.listStore.value = [...next.values()].sort((a, b) => a.index - b.index); + } + + applyChannels(encoded: ReadonlyArray): void { + for (const bytes of encoded) { + this.applyChannel(fromBinary(Protobuf.Channel.ChannelSchema, bytes)); + } + } + + applyBeacon( + packet: Types.PacketMetadata, + ): void { + if (packet.from === this.myNodeNum() || !packet.data.offerChannel) return; + const others = this.offers.peek().filter((o) => o.from !== packet.from); + this.offers.value = [ + { from: packet.from, rxTime: packet.rxTime, beacon: packet.data }, + ...others, + ]; + } + + dismissBeaconOffer(from: number): void { + this.offers.value = this.offers.peek().filter((o) => o.from !== from); + } + + get(index: number): Channel | undefined { + return this.channels.peek().get(index); + } +} diff --git a/apps/web/src/core/kmp/chat.ts b/apps/web/src/core/kmp/chat.ts new file mode 100644 index 000000000..b502dcf75 --- /dev/null +++ b/apps/web/src/core/kmp/chat.ts @@ -0,0 +1,562 @@ +import { Protobuf, type Types } from "@core/protobuf.ts"; +import { + type ConversationKey, + conversationKeyString, + type DraftRepository, + type Message, + type MessageDeliveryPatch, + type MessageRepository, + MessageState, + parseConversationKey, + type RetentionPolicy, +} from "@core/storage/types.ts"; +import type { SendHandleJs } from "@meshtastic/sdk-kmp"; +import { type Signal, signal } from "@preact/signals-core"; +import { Result } from "better-result"; +import { BROADCAST_NUM } from "./packets.ts"; +import { type ReadonlySignal, toReadonly } from "./signals.ts"; + +export class ChatStore { + private readonly buckets = new Map>(); + private readonly readBuckets = new Map>(); + + bucketFor(key: string): ReadonlySignal { + this.writeBucket(key); + return this.readBuckets.get(key) ?? toReadonly(this.writeBucket(key)); + } + + append(key: string, message: Message): void { + const bucket = this.writeBucket(key); + bucket.value = [...bucket.value, message]; + } + + /** Adds stored messages, skipping ones already held, in time order. */ + merge(key: string, messages: ReadonlyArray): void { + if (messages.length === 0) return; + const bucket = this.writeBucket(key); + const seen = new Set(bucket.value.map((m) => m.id)); + const added = messages.filter((m) => { + if (seen.has(m.id)) return false; + seen.add(m.id); + return true; + }); + if (added.length === 0) return; + bucket.value = [...bucket.value, ...added].sort( + (a, b) => a.rxTime.getTime() - b.rxTime.getTime(), + ); + } + + hasMessage(key: string, id: number): boolean { + return this.buckets.get(key)?.value.some((m) => m.id === id) ?? false; + } + + prepend(key: string, message: Message): void { + const bucket = this.writeBucket(key); + bucket.value = [message, ...bucket.value]; + } + + clearBucket(key: string): void { + const bucket = this.buckets.get(key); + if (bucket && bucket.value.length > 0) bucket.value = []; + } + + clearAll(): void { + for (const bucket of this.buckets.values()) { + if (bucket.value.length > 0) bucket.value = []; + } + } + + remove(id: number): void { + for (const bucket of this.buckets.values()) { + if (bucket.value.some((m) => m.id === id)) { + bucket.value = bucket.value.filter((m) => m.id !== id); + return; + } + } + } + + getMessage(id: number): Message | undefined { + for (const bucket of this.buckets.values()) { + const found = bucket.value.find((m) => m.id === id); + if (found) return found; + } + return undefined; + } + + patch(id: number, patch: Partial): void { + for (const bucket of this.buckets.values()) { + const index = bucket.value.findIndex((m) => m.id === id); + const existing = bucket.value[index]; + if (index === -1 || !existing) continue; + const next = bucket.value.slice(); + next[index] = { ...existing, ...patch }; + bucket.value = next; + return; + } + } + + private writeBucket(key: string): Signal { + let bucket = this.buckets.get(key); + if (!bucket) { + bucket = signal([]); + this.buckets.set(key, bucket); + this.readBuckets.set(key, toReadonly(bucket)); + } + return bucket; + } +} + +export class DraftStore { + private readonly buckets = new Map>(); + private readonly read = new Map>(); + + get(key: ConversationKey): ReadonlySignal { + const k = conversationKeyString(key); + const bucket = this.ensure(k); + return this.read.get(k) ?? toReadonly(bucket); + } + + set(key: ConversationKey, text: string): void { + this.ensure(conversationKeyString(key)).value = text; + } + + reset(): void { + for (const bucket of this.buckets.values()) bucket.value = ""; + } + + private ensure(k: string): Signal { + let bucket = this.buckets.get(k); + if (!bucket) { + bucket = signal(""); + this.buckets.set(k, bucket); + this.read.set(k, toReadonly(bucket)); + } + return bucket; + } +} + +export interface SendTextInput { + text: string; + destination: Types.Destination; + channel?: Types.ChannelNumber; + replyId?: number; +} + +export class SendTextError extends Error { + constructor( + readonly reason: string, + readonly routingError?: Protobuf.Mesh.Routing_Error, + ) { + super(`Send failed: ${reason}`); + this.name = "SendTextError"; + } +} + +export interface ChatDrafts { + get(key: ConversationKey): ReadonlySignal; + set(key: ConversationKey, text: string): void; + clear(key: ConversationKey): void; +} + +export interface ChatUnread { + readonly byKey: ReadonlySignal>; + readonly total: ReadonlySignal; + count(key: ConversationKey): ReadonlySignal; + markRead(key: ConversationKey): void; +} + +export interface ChatTransport { + myNodeNum(): number; + sendText( + text: string, + to: number, + channel: number, + replyId?: number, + ): SendHandleJs; + warn(message: string, ...args: unknown[]): void; +} + +export interface ChatClientOptions { + repository?: MessageRepository; + draftRepository?: DraftRepository; + retention?: RetentionPolicy; + initialLoadLimit?: number; +} + +interface RoutingAck { + from: number; + error: Protobuf.Mesh.Routing_Error; + proof: Protobuf.Mesh.MeshPacket_AckProofStatus | undefined; +} + +const ROUTING_ERROR_BY_REASON: ReadonlyMap< + string, + Protobuf.Mesh.Routing_Error +> = new Map( + Object.entries(Protobuf.Mesh.Routing_Error).flatMap(([name, value]) => + typeof value === "number" ? [[name, value]] : [], + ), +); + +/** + * Chat over the Kotlin SDK: message buckets keyed by channel or peer, drafts + * keyed the same way, unread counts, and `send`. The SDK has no message + * store, so history lives in the web's repositories, keyed by node number. + */ +export class ChatClient { + private readonly store = new ChatStore(); + private readonly draftStore = new DraftStore(); + private readonly repository: MessageRepository | undefined; + private readonly draftRepository: DraftRepository | undefined; + private readonly retention: RetentionPolicy | undefined; + private readonly initialLoadLimit: number; + private readonly hydrated = new Set(); + private readonly draftsHydrated = new Set(); + private readonly unreadByKey = signal>(new Map()); + /** Routing acks that arrived before the send they answer settled. */ + private readonly earlyAcks = new Map(); + private epoch = 0; + + readonly drafts: ChatDrafts; + readonly unread: ChatUnread; + + constructor( + private readonly transport: ChatTransport, + options: ChatClientOptions = {}, + ) { + this.repository = options.repository; + this.draftRepository = options.draftRepository; + this.retention = options.retention; + this.initialLoadLimit = options.initialLoadLimit ?? 50; + this.drafts = { + get: (key) => this.draftFor(key), + set: (key, text) => this.setDraft(key, text), + clear: (key) => this.setDraft(key, ""), + }; + this.unread = { + byKey: toReadonly(this.unreadByKey), + total: this.deriveTotalUnread(), + count: (key) => this.deriveUnreadCount(key), + markRead: (key) => this.markRead(key), + }; + } + + /** Files direct messages we sent under their recipient, as older versions didn't. */ + refileSentDirect(myNodeNum: number): void { + void this.repository?.refileSentDirect?.(myNodeNum).catch(() => {}); + } + + /** An inbound TEXT_MESSAGE_APP packet. */ + receive(packet: Types.PacketMetadata): void { + const myNodeNum = this.transport.myNodeNum(); + const message: Message = { + id: packet.id, + from: packet.from, + to: packet.to, + channel: packet.channel, + rxTime: packet.rxTime, + type: packet.type, + text: packet.data, + state: MessageState.Ack, + signed: packet.xeddsaSigned || undefined, + snr: packet.rxSnr, + rssi: packet.rxRssi, + hopsAway: packet.hopsAway, + viaMqtt: packet.viaMqtt || undefined, + transport: packet.transportMechanism, + }; + const conv: ConversationKey = + packet.type === "direct" && packet.to !== BROADCAST_NUM + ? { + kind: "direct", + peer: packet.from === myNodeNum ? packet.to : packet.from, + } + : { kind: "channel", channel: packet.channel }; + const key = conversationKeyString(conv); + if (this.store.hasMessage(key, message.id)) return; + this.store.append(key, message); + void this.persistAppend(message, conv); + if (packet.from !== myNodeNum) this.bumpUnread(key); + } + + /** + * Fold one ack or NAK into the message it answers, as the Android app's + * handleAckNak does. An ack from the addressed node means the recipient + * got it (Ack); one from anyone else means it reached the mesh + * (Delivered). A NAK fails it. Once the recipient has acked, later acks + * and NAKs no longer change the state. + */ + applyAck( + id: number, + from: number, + error: Protobuf.Mesh.Routing_Error, + proof: Protobuf.Mesh.MeshPacket_AckProofStatus | undefined, + ): void { + const message = this.store.getMessage(id); + if (!message) { + const pending = this.earlyAcks.get(id) ?? []; + if (this.earlyAcks.size > 64) this.earlyAcks.clear(); + this.earlyAcks.set(id, [...pending, { from, error, proof }]); + return; + } + const patch: MessageDeliveryPatch = {}; + if (message.state !== MessageState.Ack) { + if (error === Protobuf.Mesh.Routing_Error.NONE) { + patch.state = + from === message.to ? MessageState.Ack : MessageState.Delivered; + patch.relays = (message.relays ?? 0) + 1; + patch.routingError = undefined; + } else { + patch.state = MessageState.Failed; + patch.routingError = error; + } + } + const Proof = Protobuf.Mesh.MeshPacket_AckProofStatus; + const current = message.ackProof; + if ( + proof !== undefined && + proof !== Proof.ACK_PROOF_ABSENT && + current !== Proof.ACK_PROOF_VALID && + (current !== Proof.ACK_PROOF_INVALID || proof === Proof.ACK_PROOF_VALID) + ) { + patch.ackProof = proof; + } + if (Object.keys(patch).length === 0) return; + this.store.patch(id, patch); + void this.repository?.updateDelivery(id, patch).catch(() => {}); + } + + resend( + message: Pick, + ): Promise> { + this.store.remove(message.id); + void this.repository?.remove(message.id).catch(() => {}); + return this.send({ + text: message.text, + destination: message.type === "direct" ? message.to : "broadcast", + channel: message.channel, + }); + } + + messages(channel: Types.ChannelNumber): ReadonlySignal { + const conv: ConversationKey = { kind: "channel", channel }; + this.ensureHydrated(conv); + return this.store.bucketFor(conversationKeyString(conv)); + } + + direct(peer: number): ReadonlySignal { + const conv: ConversationKey = { kind: "direct", peer }; + this.ensureHydrated(conv); + return this.store.bucketFor(conversationKeyString(conv)); + } + + async loadOlder( + conv: ConversationKey, + before: Date, + limit = 50, + ): Promise { + if (!this.repository) return []; + const epoch = this.epoch; + const older = await this.repository.loadBefore(conv, before, limit); + if (epoch !== this.epoch) return []; + const key = conversationKeyString(conv); + for (const message of [...older].reverse()) + this.store.prepend(key, message); + return older; + } + + async clearConversation(conv: ConversationKey): Promise { + const key = conversationKeyString(conv); + this.store.clearBucket(key); + this.hydrated.delete(key); + await this.repository?.clearConversation(conv).catch(() => {}); + } + + async clearAll(): Promise { + this.store.clearAll(); + this.hydrated.clear(); + await this.repository?.clear().catch(() => {}); + } + + /** + * Points the repositories at another node's history and reloads every + * conversation and draft loaded so far. Signals already handed out stay + * valid and update in place. + */ + rescope(scope: number): void { + this.repository?.setScope?.(scope); + this.draftRepository?.setScope?.(scope); + this.epoch++; + const conversations = [...this.hydrated]; + const drafts = [...this.draftsHydrated]; + this.store.clearAll(); + this.hydrated.clear(); + this.draftStore.reset(); + this.draftsHydrated.clear(); + if (this.unreadByKey.peek().size > 0) this.unreadByKey.value = new Map(); + for (const key of conversations) + this.ensureHydrated(parseConversationKey(key)); + for (const key of drafts) this.draftFor(parseConversationKey(key)); + } + + async send(input: SendTextInput): Promise> { + const to = + typeof input.destination === "number" ? input.destination : BROADCAST_NUM; + const conv: ConversationKey = + typeof input.destination === "number" + ? { kind: "direct", peer: input.destination } + : { kind: "channel", channel: input.channel ?? 0 }; + const key = conversationKeyString(conv); + let handle: SendHandleJs; + try { + handle = this.transport.sendText( + input.text, + to, + input.channel ?? 0, + input.replyId, + ); + } catch (e) { + return Result.err( + new SendTextError(e instanceof Error ? e.message : String(e)), + ); + } + const message: Message = { + id: handle.id, + from: this.transport.myNodeNum(), + to, + channel: input.channel ?? 0, + rxTime: new Date(), + type: typeof input.destination === "number" ? "direct" : "broadcast", + text: input.text, + state: MessageState.Pending, + }; + this.store.append(key, message); + void this.persistAppend(message, conv); + this.setDraft(conv, ""); + for (const ack of this.earlyAcks.get(handle.id) ?? []) { + this.applyAck(handle.id, ack.from, ack.error, ack.proof); + } + this.earlyAcks.delete(handle.id); + + const outcome = await handle.outcome; + const settled = this.store.getMessage(handle.id); + if (outcome.ok) { + if (settled?.state === MessageState.Pending) { + this.patchDelivery(handle.id, { state: MessageState.Delivered }); + } + return Result.ok(handle.id); + } + const reason = outcome.reason ?? "unknown"; + const routingError = ROUTING_ERROR_BY_REASON.get(reason); + if (settled?.state !== MessageState.Ack) { + this.patchDelivery(handle.id, { + state: MessageState.Failed, + ...(routingError === undefined ? {} : { routingError }), + }); + } + return Result.err(new SendTextError(reason, routingError)); + } + + private patchDelivery(id: number, patch: MessageDeliveryPatch): void { + this.store.patch(id, patch); + void this.repository?.updateDelivery(id, patch).catch(() => {}); + } + + private ensureHydrated(conv: ConversationKey): void { + const key = conversationKeyString(conv); + if (this.hydrated.has(key) || !this.repository) return; + this.hydrated.add(key); + const epoch = this.epoch; + void this.repository + .loadRecent(conv, this.initialLoadLimit) + .then((recent) => { + if (epoch === this.epoch) this.store.merge(key, recent); + }) + .catch(() => {}); + } + + private draftFor(conv: ConversationKey): ReadonlySignal { + const key = conversationKeyString(conv); + if (!this.draftsHydrated.has(key) && this.draftRepository) { + this.draftsHydrated.add(key); + const epoch = this.epoch; + void this.draftRepository + .load(conv) + .then((stored) => { + if (epoch === this.epoch && stored) this.draftStore.set(conv, stored); + }) + .catch(() => {}); + } + return this.draftStore.get(conv); + } + + private setDraft(conv: ConversationKey, text: string): void { + this.draftsHydrated.add(conversationKeyString(conv)); + this.draftStore.set(conv, text); + void this.draftRepository?.save(conv, text).catch(() => {}); + } + + private async persistAppend( + message: Message, + conv: ConversationKey, + ): Promise { + if (!this.repository) return; + try { + await this.repository.append(message, conv); + if (this.retention) await this.repository.prune(this.retention); + } catch (e) { + this.transport.warn("Could not save message", message.id, e); + } + } + + private bumpUnread(key: string): void { + const next = new Map(this.unreadByKey.peek()); + next.set(key, (next.get(key) ?? 0) + 1); + this.unreadByKey.value = next; + } + + private markRead(key: ConversationKey): void { + const k = conversationKeyString(key); + const current = this.unreadByKey.peek(); + if ((current.get(k) ?? 0) === 0) return; + const next = new Map(current); + next.delete(k); + this.unreadByKey.value = next; + } + + private deriveTotalUnread(): ReadonlySignal { + const total = (m: ReadonlyMap): number => { + let sum = 0; + for (const c of m.values()) sum += c; + return sum; + }; + return this.derive(total); + } + + private deriveUnreadCount(key: ConversationKey): ReadonlySignal { + const k = conversationKeyString(key); + return this.derive((m) => m.get(k) ?? 0); + } + + private derive( + pick: (m: ReadonlyMap) => number, + ): ReadonlySignal { + const src = this.unreadByKey; + return { + get value() { + return pick(src.value); + }, + peek: () => pick(src.peek()), + subscribe: (listener) => { + let first = true; + return src.subscribe((m) => { + if (first) { + first = false; + return; + } + listener(pick(m)); + }); + }, + }; + } +} diff --git a/apps/web/src/core/kmp/configEditorIo.test.ts b/apps/web/src/core/kmp/configEditorIo.test.ts index 8af22835a..2c8f3f05b 100644 --- a/apps/web/src/core/kmp/configEditorIo.test.ts +++ b/apps/web/src/core/kmp/configEditorIo.test.ts @@ -1,13 +1,10 @@ +import { interceptAdmin } from "@app/tests/adminInterceptor.ts"; +import { create } from "@bufbuild/protobuf"; import { Protobuf } from "@core/protobuf.ts"; -import { create, toBinary } from "@bufbuild/protobuf"; -import { MeshClient } from "@meshtastic/sdk"; -import { - createFakeTransport, - interceptAdminMessages, -} from "@meshtastic/sdk/testing"; import { describe, expect, it } from "vitest"; -import { facadeIo, meshClientIo } from "./configEditorIo.ts"; -import { FakeKmpClient } from "./fakeClient.ts"; +import { sessionIo } from "./configEditorIo.ts"; +import { FakeKmpClient, state } from "./fakeClient.ts"; +import { MeshSession } from "./session.ts"; const setOwner = (longName: string) => create(Protobuf.Admin.AdminMessageSchema, { @@ -30,17 +27,17 @@ const setLora = () => }, }); -describe("meshClientIo", () => { +describe("sessionIo", () => { function setup() { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const radio = interceptAdminMessages(client); + const kmp = new FakeKmpClient(); + const session = new MeshSession(kmp); + const radio = interceptAdmin(kmp); const pending: boolean[] = []; - client.events.onPendingSettingsChange.subscribe((p) => pending.push(p)); - return { client, radio, pending, io: meshClientIo(client) }; + session.events.onPendingSettingsChange.subscribe((p) => pending.push(p)); + return { kmp, session, radio, pending, io: sessionIo(session) }; } - it("wraps the messages in a begin/commit transaction", async () => { + it("commits the messages as one settings transaction", async () => { const { io, radio, pending } = setup(); const result = await io.commit([setLora(), setOwner("Alice")]); expect(result.status).toBe("ok"); @@ -53,99 +50,40 @@ describe("meshClientIo", () => { expect(pending).toEqual([true, false]); }); - it("closes the transaction when a send fails", async () => { - const { io, radio } = setup(); + it("reports a failed transaction", async () => { + const { io, radio, pending } = setup(); radio.failNext("setOwner"); const result = await io.commit([setLora(), setOwner("Alice")]); expect(result.status).toBe("error"); - expect(radio.cases()).toEqual([ - "beginEditSettings", - "setConfig", - "setOwner", - "commitEditSettings", - ]); + expect(pending).toEqual([true, false]); }); - it("relays config, module config and channel packets", () => { - const { io, client } = setup(); + it("relays config, module config, channel packets and disconnects", () => { + const { io, session, kmp } = setup(); const seen: string[] = []; io.onConfig((c) => seen.push(`config:${c.payloadVariant.case}`)); io.onModuleConfig((c) => seen.push(`module:${c.payloadVariant.case}`)); io.onChannel((c) => seen.push(`channel:${c.index}`)); - client.events.onConfigPacket.dispatch( + io.onDisconnect(() => seen.push("disconnect")); + session.events.onConfigPacket.dispatch( create(Protobuf.Config.ConfigSchema, { payloadVariant: { case: "lora", value: {} }, }), ); - client.events.onModuleConfigPacket.dispatch( + session.events.onModuleConfigPacket.dispatch( create(Protobuf.ModuleConfig.ModuleConfigSchema, { payloadVariant: { case: "mqtt", value: {} }, }), ); - client.events.onChannelPacket.dispatch( + session.events.onChannelPacket.dispatch( create(Protobuf.Channel.ChannelSchema, { index: 2 }), ); - expect(seen).toEqual(["config:lora", "module:mqtt", "channel:2"]); - }); -}); - -describe("facadeIo", () => { - it("relays the config bundle and channels as individual packets", () => { - const client = new FakeKmpClient(); - const io = facadeIo(client); - const seen: string[] = []; - io.onConfig((c) => seen.push(`config:${c.payloadVariant.case}`)); - io.onModuleConfig((c) => seen.push(`module:${c.payloadVariant.case}`)); - io.onChannel((c) => seen.push(`channel:${c.index}`)); - io.onDisconnect(() => seen.push("disconnect")); - - client.setConfigBundle({ - myInfo: new Uint8Array(), - metadata: new Uint8Array(), - configs: [ - toBinary( - Protobuf.Config.ConfigSchema, - create(Protobuf.Config.ConfigSchema, { - payloadVariant: { case: "device", value: {} }, - }), - ), - ], - moduleConfigs: [ - toBinary( - Protobuf.ModuleConfig.ModuleConfigSchema, - create(Protobuf.ModuleConfig.ModuleConfigSchema, { - payloadVariant: { case: "serial", value: {} }, - }), - ), - ], - }); - client.setChannels([ - toBinary( - Protobuf.Channel.ChannelSchema, - create(Protobuf.Channel.ChannelSchema, { index: 1 }), - ), - ]); - client.setState({ - kind: "disconnected", - attempt: 0, - maxAttempts: 10, - progress: 0, - }); - + kmp.setState(state("disconnected")); expect(seen).toEqual([ - "disconnect", - "config:device", - "module:serial", - "channel:1", + "config:lora", + "module:mqtt", + "channel:2", "disconnect", ]); }); - - it("commits through the facade's settings transaction", async () => { - const client = new FakeKmpClient(); - const io = facadeIo(client); - const result = await io.commit([setLora()]); - expect(result.status).toBe("ok"); - expect(client.admin().transactions).toHaveLength(1); - }); }); diff --git a/apps/web/src/core/kmp/configEditorIo.ts b/apps/web/src/core/kmp/configEditorIo.ts index c78345a80..620aa7ade 100644 --- a/apps/web/src/core/kmp/configEditorIo.ts +++ b/apps/web/src/core/kmp/configEditorIo.ts @@ -1,170 +1,39 @@ -import { Protobuf, Types } from "@core/protobuf.ts"; -import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; -import { DeviceStatusEnum, type MeshClient } from "@meshtastic/sdk"; -import type { MeshtasticClient } from "@meshtastic/sdk-kmp"; -import { Result } from "better-result"; import { editSettings } from "./admin.ts"; import { ConfigEditor, type ConfigEditorIo } from "./configEditor.ts"; import { moduleMessagesFor } from "./moduleMessages.ts"; +import type { MeshSession } from "./session.ts"; -type AdminMessages = readonly Protobuf.Admin.AdminMessage[]; - -/** The editor's device access through the Kotlin SDK facade. */ -export function facadeIo(client: MeshtasticClient): ConfigEditorIo { +/** The editor's device access through a session over the Kotlin SDK. */ +export function sessionIo(session: MeshSession): ConfigEditorIo { return { - onConfig: (cb) => - client.onConfigBundle((bundle) => { - for (const bytes of bundle?.configs ?? []) { - cb(fromBinary(Protobuf.Config.ConfigSchema, bytes)); - } - }), - onModuleConfig: (cb) => - client.onConfigBundle((bundle) => { - for (const bytes of bundle?.moduleConfigs ?? []) { - cb(fromBinary(Protobuf.ModuleConfig.ModuleConfigSchema, bytes)); - } - }), - onChannel: (cb) => - client.onChannels((channels) => { - for (const bytes of channels ?? []) { - cb(fromBinary(Protobuf.Channel.ChannelSchema, bytes)); - } - }), + onConfig: (cb) => session.events.onConfigPacket.subscribe(cb), + onModuleConfig: (cb) => session.events.onModuleConfigPacket.subscribe(cb), + onChannel: (cb) => session.events.onChannelPacket.subscribe(cb), onDisconnect: (cb) => - client.onConnectionState((state) => { + session.events.onConnectionState.subscribe((state) => { if (state.kind === "disconnected") cb(); }), - commit: (messages) => editSettings(client, messages), - }; -} - -/** - * The editor's device access through the TypeScript SDK client, for the - * Serial and Bluetooth connections it still carries. - */ -export function meshClientIo(client: MeshClient): ConfigEditorIo { - return { - onConfig: (cb) => client.events.onConfigPacket.subscribe(cb), - onModuleConfig: (cb) => client.events.onModuleConfigPacket.subscribe(cb), - onChannel: (cb) => client.events.onChannelPacket.subscribe(cb), - onDisconnect: (cb) => - client.events.onDeviceStatus.subscribe((status) => { - if (status === DeviceStatusEnum.DeviceDisconnected) cb(); - }), - commit: (messages) => commitThroughMeshClient(client, messages), - }; -} - -async function commitThroughMeshClient( - client: MeshClient, - messages: AdminMessages, -): Promise> { - let disconnected = false; - const off = client.events.onDeviceStatus.subscribe((status) => { - if (status === DeviceStatusEnum.DeviceDisconnected) disconnected = true; - }); - client.events.onPendingSettingsChange.dispatch(true); - try { - const begin = await sendAdmin(client, { - case: "beginEditSettings", - value: true, - }); - if (Result.isError(begin)) return begin; - for (const message of messages) { - const sent = await sendAdmin(client, message.payloadVariant); - if (Result.isError(sent)) { - // There is no abort message. Close the transaction rather than - // leave it open; the editor keeps everything dirty for a resend. - if (!disconnected) { - await sendAdmin(client, { case: "commitEditSettings", value: true }); - } - return sent; + commit: async (messages) => { + session.events.onPendingSettingsChange.dispatch(true); + try { + return await editSettings(session.kmp, messages); + } finally { + session.events.onPendingSettingsChange.dispatch(false); } - } - return sendAdmin(client, { case: "commitEditSettings", value: true }); - } finally { - off(); - client.events.onPendingSettingsChange.dispatch(false); - } -} - -function isBadSessionKey(e: unknown): boolean { - return ( - typeof e === "object" && - e !== null && - "error" in e && - e.error === Protobuf.Mesh.Routing_Error.ADMIN_BAD_SESSION_KEY - ); -} - -/** - * Sends an admin message to the local node, stamped with its session - * passkey; on `ADMIN_BAD_SESSION_KEY` asks for a fresh one and retries once. - */ -async function sendAdmin( - client: MeshClient, - payloadVariant: Protobuf.Admin.AdminMessage["payloadVariant"], -): Promise> { - const nodeNum = client.myNodeNum; - const send = () => - client.sendPacket( - toBinary( - Protobuf.Admin.AdminMessageSchema, - create(Protobuf.Admin.AdminMessageSchema, { - payloadVariant, - sessionPasskey: client.device.session.get(nodeNum), - }), - ), - Protobuf.Portnums.PortNum.ADMIN_APP, - "self", - Types.ChannelNumber.Primary, - true, - true, - ); - try { - await send(); - return Result.ok(undefined); - } catch (e) { - if (!isBadSessionKey(e)) return Result.err(toError(e)); - client.device.session.forget(nodeNum); - const arrived = client.device.session.waitFor(nodeNum); - client - .sendPacket( - toBinary( - Protobuf.Admin.AdminMessageSchema, - create(Protobuf.Admin.AdminMessageSchema, { - payloadVariant: { case: "getOwnerRequest", value: true }, - }), - ), - Protobuf.Portnums.PortNum.ADMIN_APP, - nodeNum, - Types.ChannelNumber.Primary, - ) - .catch(() => undefined); - if (!(await arrived)) return Result.err(toError(e)); - try { - await send(); - return Result.ok(undefined); - } catch (retry) { - return Result.err(toError(retry)); - } - } -} - -function toError(e: unknown): Error { - return e instanceof Error ? e : new Error(String(e)); + }, + }; } -const editors = new WeakMap(); +const editors = new WeakMap(); -/** The one editor for a TypeScript SDK client, created on first use. */ -export function editorFor(client: MeshClient): ConfigEditor { - const existing = editors.get(client); +/** The one editor for a session, created on first use. */ +export function editorFor(session: MeshSession): ConfigEditor { + const existing = editors.get(session); if (existing) return existing; - const messages = moduleMessagesFor(client); - const editor = new ConfigEditor(meshClientIo(client), { + const messages = moduleMessagesFor(session); + const editor = new ConfigEditor(sessionIo(session), { onStagedAdminMessageCommitted: (message) => messages.applySent(message), }); - editors.set(client, editor); + editors.set(session, editor); return editor; } diff --git a/apps/web/src/core/kmp/connectionState.test.ts b/apps/web/src/core/kmp/connectionState.test.ts index d65e25483..2cd797753 100644 --- a/apps/web/src/core/kmp/connectionState.test.ts +++ b/apps/web/src/core/kmp/connectionState.test.ts @@ -24,7 +24,7 @@ describe("toConnectionStatus", () => { expect(toConnectionStatus(state("configuring", { phase: "Stage2" }))).toBe( "configuring", ); - expect(toConnectionStatus(state("connected"))).toBe("connected"); + expect(toConnectionStatus(state("connected"))).toBe("configured"); expect(toConnectionStatus(state("reconnecting", { attempt: 3 }))).toBe( "connecting", ); diff --git a/apps/web/src/core/kmp/connectionState.ts b/apps/web/src/core/kmp/connectionState.ts index 2c6576880..3dbc6c88a 100644 --- a/apps/web/src/core/kmp/connectionState.ts +++ b/apps/web/src/core/kmp/connectionState.ts @@ -80,10 +80,8 @@ export function connectFailure(error: unknown): ConnectFailure { /** * Maps the SDK's connection state onto the saved-connection status the - * drawer and overlay already render. `configuring` is the SDK handshake; - * `configured` is only reached once the web client has its own config - * stream (see `useConnections`), so the SDK's `connected` maps to - * `connected` here. + * drawer and overlay render. `configuring` is the SDK handshake and + * `connected` means it finished, which the app calls `configured`. */ export function toConnectionStatus(state: ConnectionStateJs): ConnectionStatus { switch (state.kind) { @@ -93,7 +91,7 @@ export function toConnectionStatus(state: ConnectionStateJs): ConnectionStatus { case "configuring": return "configuring"; case "connected": - return "connected"; + return "configured"; default: return "disconnected"; } diff --git a/apps/web/src/core/kmp/device.ts b/apps/web/src/core/kmp/device.ts new file mode 100644 index 000000000..d01a55e52 --- /dev/null +++ b/apps/web/src/core/kmp/device.ts @@ -0,0 +1,219 @@ +import { create } from "@bufbuild/protobuf"; +import { Protobuf, Types } from "@core/protobuf.ts"; +import { type FirmwareSupport, firmwareSupport } from "@core/utils/firmware.ts"; +import type { ConnectionStateJs } from "@meshtastic/sdk-kmp"; +import { computed, signal } from "@preact/signals-core"; +import { Result } from "better-result"; +import { type ReadonlySignal, toReadonly } from "./signals.ts"; + +export const DEFAULT_UNLOCK_BOOTS = 50; + +export interface UnlockOptions { + passphrase: string; + /** Reboots the unlock survives. Defaults to {@link DEFAULT_UNLOCK_BOOTS}. */ + bootsRemaining?: number; + /** Hours until the unlock expires; 0 or unset means no time limit. */ + validForHours?: number; + /** Per-boot session cap in seconds; 0 or unset means unlimited. */ + maxSessionSeconds?: number; +} + +const LOCKED_STATES = new Set([ + Protobuf.Mesh.LockdownStatus_State.NEEDS_PROVISION, + Protobuf.Mesh.LockdownStatus_State.LOCKED, + Protobuf.Mesh.LockdownStatus_State.UNLOCK_FAILED, +]); + +/** True while the device withholds its config until the client unlocks it. */ +export const isLockedState = ( + status: Protobuf.Mesh.LockdownStatus | undefined, +): boolean => !!status && LOCKED_STATES.has(status.state); + +export function toDeviceStatus( + state: ConnectionStateJs, +): Types.DeviceStatusEnum { + switch (state.kind) { + case "connecting": + return Types.DeviceStatusEnum.DeviceConnecting; + case "configuring": + return Types.DeviceStatusEnum.DeviceConfiguring; + case "connected": + return Types.DeviceStatusEnum.DeviceConfigured; + case "reconnecting": + return Types.DeviceStatusEnum.DeviceReconnecting; + default: + return Types.DeviceStatusEnum.DeviceDisconnected; + } +} + +export interface DeviceAdmin { + sendAdmin( + variant: Protobuf.Admin.AdminMessage["payloadVariant"], + ): Promise>; + /** Runs the handshake again, e.g. after the device was unlocked. */ + rehandshake(): Promise; + warn(message: string, ...args: unknown[]): void; +} + +/** + * The connected device: its status, identity, metadata, lockdown state and + * the admin commands that act on it as a whole. + */ +export class DeviceClient { + private readonly statusStore = signal( + Types.DeviceStatusEnum.DeviceDisconnected, + ); + private readonly configuredStore = signal(false); + private readonly pendingStore = signal(false); + private readonly myNodeNumStore = signal(undefined); + private readonly metadataStore = signal< + Protobuf.Mesh.DeviceMetadata | undefined + >(undefined); + private readonly myNodeInfoStore = signal< + Protobuf.Mesh.MyNodeInfo | undefined + >(undefined); + private readonly supportStore = signal("unknown"); + private readonly lockdownStore = signal< + Protobuf.Mesh.LockdownStatus | undefined + >(undefined); + private readonly presetsStore = signal< + Protobuf.Mesh.LoRaRegionPresetMap | undefined + >(undefined); + private unlockPending = false; + + readonly status: ReadonlySignal; + readonly isConfigured: ReadonlySignal; + readonly pendingSettingsChanges: ReadonlySignal; + readonly myNodeNum: ReadonlySignal; + readonly metadata: ReadonlySignal; + readonly myNodeInfo: ReadonlySignal; + readonly firmwareSupport: ReadonlySignal; + readonly lockdownStatus: ReadonlySignal< + Protobuf.Mesh.LockdownStatus | undefined + >; + readonly isLocked: ReadonlySignal; + readonly regionPresets: ReadonlySignal< + Protobuf.Mesh.LoRaRegionPresetMap | undefined + >; + + constructor(private readonly admin: DeviceAdmin) { + this.status = toReadonly(this.statusStore); + this.isConfigured = toReadonly(this.configuredStore); + this.pendingSettingsChanges = toReadonly(this.pendingStore); + this.myNodeNum = toReadonly(this.myNodeNumStore); + this.metadata = toReadonly(this.metadataStore); + this.myNodeInfo = toReadonly(this.myNodeInfoStore); + this.firmwareSupport = toReadonly(this.supportStore); + this.lockdownStatus = toReadonly(this.lockdownStore); + this.regionPresets = toReadonly(this.presetsStore); + this.isLocked = toReadonly( + computed(() => isLockedState(this.lockdownStore.value)), + ); + } + + applyConnectionState(state: ConnectionStateJs): void { + const status = toDeviceStatus(state); + this.statusStore.value = status; + if (status === Types.DeviceStatusEnum.DeviceConfigured) { + this.configuredStore.value = true; + } else if (status === Types.DeviceStatusEnum.DeviceConfiguring) { + this.configuredStore.value = false; + } else if (status === Types.DeviceStatusEnum.DeviceDisconnected) { + this.configuredStore.value = false; + this.unlockPending = false; + this.lockdownStore.value = undefined; + } + } + + applyMyNodeInfo(info: Protobuf.Mesh.MyNodeInfo): void { + this.myNodeInfoStore.value = info; + this.myNodeNumStore.value = info.myNodeNum; + } + + applyMetadata(metadata: Protobuf.Mesh.DeviceMetadata): void { + this.metadataStore.value = metadata; + this.supportStore.value = firmwareSupport(metadata.firmwareVersion); + } + + applyLockdownStatus(status: Protobuf.Mesh.LockdownStatus): void { + const wasLocked = isLockedState(this.lockdownStore.peek()); + this.lockdownStore.value = status; + // After an unlock the device only releases its config to a new + // handshake on the same link; run one when this session saw it locked + // or sent a passphrase, so a repeated UNLOCKED can't loop. + if ( + status.state === Protobuf.Mesh.LockdownStatus_State.UNLOCKED && + (wasLocked || this.unlockPending) + ) { + this.unlockPending = false; + this.admin.rehandshake().catch((e: unknown) => { + this.admin.warn("Handshake after unlock failed", e); + }); + } else if (isLockedState(status)) { + this.unlockPending = false; + } + } + + applyRegionPresets(presets: Protobuf.Mesh.LoRaRegionPresetMap): void { + this.presetsStore.value = presets; + } + + setPendingSettingsChanges(pending: boolean): void { + this.pendingStore.value = pending; + } + + private lockdownAuth( + auth: Parameters< + typeof create + >[1], + ): Promise { + return this.admin + .sendAdmin({ + case: "lockdownAuth", + value: create(Protobuf.Admin.LockdownAuthSchema, auth), + }) + .then((result) => { + if (Result.isError(result)) throw result.error; + }); + } + + /** Sends the lockdown passphrase; the result arrives on `lockdownStatus`. */ + unlock(options: UnlockOptions): Promise { + this.unlockPending = true; + const hours = options.validForHours ?? 0; + return this.lockdownAuth({ + passphrase: new TextEncoder().encode(options.passphrase), + bootsRemaining: Math.max( + 0, + options.bootsRemaining ?? DEFAULT_UNLOCK_BOOTS, + ), + validUntilEpoch: + hours > 0 ? Math.floor(Date.now() / 1000) + hours * 3600 : 0, + maxSessionSeconds: Math.max(0, options.maxSessionSeconds ?? 0), + }); + } + + lockNow(): Promise { + return this.lockdownAuth({ lockNow: true }); + } + + /** Turns lockdown off for good: the device decrypts its storage and reboots. */ + disableLockdown(passphrase: string): Promise { + return this.lockdownAuth({ + passphrase: new TextEncoder().encode(passphrase), + disable: true, + }); + } + + reboot(seconds = 0): Promise> { + return this.admin.sendAdmin({ case: "rebootSeconds", value: seconds }); + } + + rebootOta(seconds = 0): Promise> { + return this.admin.sendAdmin({ case: "rebootOtaSeconds", value: seconds }); + } + + shutdown(seconds = 0): Promise> { + return this.admin.sendAdmin({ case: "shutdownSeconds", value: seconds }); + } +} diff --git a/apps/web/src/core/kmp/emitter.ts b/apps/web/src/core/kmp/emitter.ts new file mode 100644 index 000000000..b4c2784b7 --- /dev/null +++ b/apps/web/src/core/kmp/emitter.ts @@ -0,0 +1,17 @@ +/** A plain event: subscribe for later values, dispatch to every listener. */ +export class Emitter { + private readonly listeners = new Set<(value: T) => void>(); + + subscribe(listener: (value: T) => void): () => void { + this.listeners.add(listener); + return () => { + this.listeners.delete(listener); + }; + } + + dispatch(value: T): void { + for (const listener of [...this.listeners]) { + listener(value); + } + } +} diff --git a/apps/web/src/core/kmp/hooks/index.ts b/apps/web/src/core/kmp/hooks/index.ts index ac770eeec..084c39f0a 100644 --- a/apps/web/src/core/kmp/hooks/index.ts +++ b/apps/web/src/core/kmp/hooks/index.ts @@ -1,3 +1,9 @@ +export { + MeshRegistryProvider, + type MeshRegistryProviderProps, + useActiveClient, + useMeshRegistry, +} from "./registry.tsx"; export { useConfigEditor } from "./useConfigEditor.ts"; export { MODULE_MESSAGES_TIMEOUT_MS, @@ -5,4 +11,24 @@ export { useRingtone, type UseModuleMessagesResult, } from "./useModuleMessages.ts"; +export { + type UseChatResult, + type UseDraftResult, + type UseMeshDeviceResult, + useChannel, + useChannels, + useChat, + useConnectionProgress, + useDirectChat, + useDraft, + useHasNodeError, + useIsRegionUnset, + useMeshDevice, + useNodeError, + useNodeErrors, + useNodes, + useTotalUnread, + useUnreadByKey, + useUnreadCount, +} from "./useSession.ts"; export { useSignal } from "./useSignal.ts"; diff --git a/apps/web/src/core/kmp/hooks/registry.tsx b/apps/web/src/core/kmp/hooks/registry.tsx new file mode 100644 index 000000000..15c572ed6 --- /dev/null +++ b/apps/web/src/core/kmp/hooks/registry.tsx @@ -0,0 +1,35 @@ +import type { MeshRegistry } from "@core/kmp/registry.ts"; +import type { MeshSession } from "@core/kmp/session.ts"; +import { createContext, type ReactNode, useContext } from "react"; +import { useSignal } from "./useSignal.ts"; + +const MeshRegistryContext = createContext(undefined); + +export interface MeshRegistryProviderProps { + registry: MeshRegistry; + children: ReactNode; +} + +export function MeshRegistryProvider({ + registry, + children, +}: MeshRegistryProviderProps) { + return ( + + {children} + + ); +} + +export function useMeshRegistry(): MeshRegistry { + const registry = useContext(MeshRegistryContext); + if (!registry) { + throw new Error("useMeshRegistry must be used within MeshRegistryProvider"); + } + return registry; +} + +/** The session of the connection the app is looking at, if any. */ +export function useActiveClient(): MeshSession | undefined { + return useSignal(useMeshRegistry().active); +} diff --git a/apps/web/src/core/kmp/hooks/useConfigEditor.ts b/apps/web/src/core/kmp/hooks/useConfigEditor.ts index b4c1d2d93..f8a134cf6 100644 --- a/apps/web/src/core/kmp/hooks/useConfigEditor.ts +++ b/apps/web/src/core/kmp/hooks/useConfigEditor.ts @@ -1,6 +1,6 @@ import type { ConfigEditor } from "@core/kmp/configEditor.ts"; import { editorFor } from "@core/kmp/configEditorIo.ts"; -import { useActiveClient } from "@meshtastic/sdk-react"; +import { useActiveClient } from "./registry.tsx"; /** * The active connection's `ConfigEditor`, or `undefined` when none is diff --git a/apps/web/src/core/kmp/hooks/useModuleMessages.ts b/apps/web/src/core/kmp/hooks/useModuleMessages.ts index 5b521544e..f08ed565e 100644 --- a/apps/web/src/core/kmp/hooks/useModuleMessages.ts +++ b/apps/web/src/core/kmp/hooks/useModuleMessages.ts @@ -3,7 +3,7 @@ import { moduleMessagesFor, } from "@core/kmp/moduleMessages.ts"; import { constantSignal } from "@core/kmp/signals.ts"; -import { useActiveClient } from "@meshtastic/sdk-react"; +import { useActiveClient } from "./registry.tsx"; import { Result } from "better-result"; import { useCallback, useEffect, useRef, useState } from "react"; import { useSignal } from "./useSignal.ts"; diff --git a/apps/web/src/core/kmp/hooks/useSession.ts b/apps/web/src/core/kmp/hooks/useSession.ts new file mode 100644 index 000000000..3c8cd3f8f --- /dev/null +++ b/apps/web/src/core/kmp/hooks/useSession.ts @@ -0,0 +1,163 @@ +import type { Channel } from "@core/kmp/channels.ts"; +import type { SendTextError, SendTextInput } from "@core/kmp/chat.ts"; +import type { NodeError } from "@core/kmp/nodes.ts"; +import type { ConnectionProgress } from "@core/kmp/session.ts"; +import { constantSignal, type ReadonlySignal } from "@core/kmp/signals.ts"; +import type { Protobuf, Types } from "@core/protobuf.ts"; +import type { ConversationKey, Message, Node } from "@core/storage/types.ts"; +import type { Result } from "better-result"; +import { useCallback, useMemo } from "react"; +import { useActiveClient } from "./registry.tsx"; +import { useSignal } from "./useSignal.ts"; + +const NO_NODES = constantSignal>([]); +const NO_ERRORS = constantSignal>([]); +const NO_CHANNELS = constantSignal>([]); +const NO_MESSAGES = constantSignal([]); +const NO_TEXT = constantSignal(""); +const ZERO = constantSignal(0); +const NO_UNREAD = constantSignal>(new Map()); +const IDLE = constantSignal({ phase: "idle" }); +const FALSE = constantSignal(false); +const NOTHING = constantSignal(undefined); + +export function useNodes(): ReadonlyArray { + const client = useActiveClient(); + return useSignal(client?.nodes.list ?? NO_NODES); +} + +export function useNodeErrors(): ReadonlyArray { + const client = useActiveClient(); + return useSignal(client?.nodes.errors ?? NO_ERRORS); +} + +export function useNodeError(nodeNum: number): NodeError | undefined { + return useNodeErrors().find((e) => e.node === nodeNum); +} + +export function useHasNodeError(nodeNum: number): boolean { + return useNodeError(nodeNum) !== undefined; +} + +export function useChannels(): ReadonlyArray { + const client = useActiveClient(); + return useSignal(client?.channels.list ?? NO_CHANNELS); +} + +export function useChannel(index: number): Channel | undefined { + return useChannels().find((c) => c.index === index); +} + +export interface UseChatResult { + messages: Message[]; + send(input: SendTextInput): Promise>; + loadOlder(before: Date, limit?: number): Promise; +} + +function noClient(): never { + throw new Error("No active connection"); +} + +function useConversation(conv: ConversationKey): UseChatResult { + const client = useActiveClient(); + const id = conv.kind === "channel" ? conv.channel : conv.peer; + const sig = useMemo>(() => { + if (!client) return NO_MESSAGES; + return conv.kind === "channel" + ? client.chat.messages(conv.channel) + : client.chat.direct(conv.peer); + }, [client, conv.kind, id]); + const messages = useSignal(sig); + const send = useCallback( + (input: SendTextInput) => (client ? client.chat.send(input) : noClient()), + [client], + ); + const loadOlder = useCallback( + (before: Date, limit?: number) => + client ? client.chat.loadOlder(conv, before, limit) : noClient(), + [client, conv.kind, id], + ); + return { messages, send, loadOlder }; +} + +export function useChat(channel: Types.ChannelNumber): UseChatResult { + return useConversation({ kind: "channel", channel }); +} + +/** Direct messages with one peer; from-me-to-peer and from-peer-to-me share the bucket. */ +export function useDirectChat(peer: number): UseChatResult { + return useConversation({ kind: "direct", peer }); +} + +export interface UseDraftResult { + text: string; + setText(value: string): void; + clear(): void; +} + +export function useDraft(conv: ConversationKey): UseDraftResult { + const client = useActiveClient(); + const id = conv.kind === "channel" ? conv.channel : conv.peer; + const sig = useMemo( + () => client?.chat.drafts.get(conv) ?? NO_TEXT, + [client, conv.kind, id], + ); + const text = useSignal(sig); + const setText = useCallback( + (value: string) => client?.chat.drafts.set(conv, value), + [client, conv.kind, id], + ); + const clear = useCallback( + () => client?.chat.drafts.clear(conv), + [client, conv.kind, id], + ); + return { text, setText, clear }; +} + +export function useTotalUnread(): number { + const client = useActiveClient(); + return useSignal(client?.chat.unread.total ?? ZERO); +} + +export function useUnreadCount(key: ConversationKey): number { + const client = useActiveClient(); + const id = key.kind === "channel" ? key.channel : key.peer; + const sig = useMemo( + () => client?.chat.unread.count(key) ?? ZERO, + [client, key.kind, id], + ); + return useSignal(sig); +} + +export function useUnreadByKey(): ReadonlyMap { + const client = useActiveClient(); + return useSignal(client?.chat.unread.byKey ?? NO_UNREAD); +} + +export interface UseMeshDeviceResult { + status: Types.DeviceStatusEnum | undefined; + isConfigured: boolean; + myNodeNum: number | undefined; + metadata: Protobuf.Mesh.DeviceMetadata | undefined; +} + +export function useMeshDevice(): UseMeshDeviceResult { + const client = useActiveClient(); + const status = useSignal(client?.device.status ?? NOTHING); + const isConfigured = useSignal(client?.device.isConfigured ?? FALSE); + const myNodeNum = useSignal(client?.device.myNodeNum ?? NOTHING); + const metadata = useSignal(client?.device.metadata ?? NOTHING); + return { status, isConfigured, myNodeNum, metadata }; +} + +/** True when the device's LoRa region is UNSET: freshly flashed, not transmitting. */ +export function useIsRegionUnset(): boolean { + const client = useActiveClient(); + return useSignal(client?.config.isRegionUnset ?? FALSE); +} + +/** Handshake progress of the active connection; idle without one. */ +export function useConnectionProgress(): ConnectionProgress { + const client = useActiveClient(); + return useSignal(client?.progress ?? IDLE); +} diff --git a/apps/web/src/core/kmp/moduleMessages.ts b/apps/web/src/core/kmp/moduleMessages.ts index d47b81ebc..0f4e9594e 100644 --- a/apps/web/src/core/kmp/moduleMessages.ts +++ b/apps/web/src/core/kmp/moduleMessages.ts @@ -1,7 +1,7 @@ import type { Protobuf } from "@core/protobuf.ts"; -import { DeviceStatusEnum, type MeshClient } from "@meshtastic/sdk"; import { signal } from "@preact/signals-core"; -import type { Result } from "better-result"; +import { Result } from "better-result"; +import type { MeshSession } from "./session.ts"; import { type ReadonlySignal, toReadonly } from "./signals.ts"; export type ModuleMessageKind = "cannedMessages" | "ringtone"; @@ -21,29 +21,22 @@ export interface ModuleMessages { applySent(message: Protobuf.Admin.AdminMessage): void; } -const stores = new WeakMap(); +const stores = new WeakMap(); -export function moduleMessagesFor(client: MeshClient): ModuleMessages { - const existing = stores.get(client); +export function moduleMessagesFor(session: MeshSession): ModuleMessages { + const existing = stores.get(session); if (existing) return existing; const cannedMessages = signal(undefined); const ringtone = signal(undefined); const listeners = new Set<(kind: ModuleMessageKind) => void>(); + const answered = (kind: ModuleMessageKind, value: string): void => { + (kind === "cannedMessages" ? cannedMessages : ringtone).value = value; + for (const cb of listeners) cb(kind); + }; - client.events.onAdminPacket.subscribe((packet) => { - if (packet.from !== client.myNodeNum) return; - const variant = packet.data.payloadVariant; - if (variant.case === "getCannedMessageModuleMessagesResponse") { - cannedMessages.value = variant.value; - for (const cb of listeners) cb("cannedMessages"); - } else if (variant.case === "getRingtoneResponse") { - ringtone.value = variant.value; - for (const cb of listeners) cb("ringtone"); - } - }); - client.events.onDeviceStatus.subscribe((status) => { - if (status === DeviceStatusEnum.DeviceDisconnected) { + session.events.onConnectionState.subscribe((state) => { + if (state.kind === "disconnected") { cannedMessages.value = undefined; ringtone.value = undefined; } @@ -52,10 +45,14 @@ export function moduleMessagesFor(client: MeshClient): ModuleMessages { const store: ModuleMessages = { cannedMessages: toReadonly(cannedMessages), ringtone: toReadonly(ringtone), - request: (kind) => - kind === "cannedMessages" - ? client.config.requestCannedMessages() - : client.config.requestRingtone(), + request: async (kind) => { + const result = + kind === "cannedMessages" + ? await session.config.requestCannedMessages() + : await session.config.requestRingtone(); + if (Result.isOk(result)) answered(kind, result.value); + return result; + }, onResponse: (cb) => { listeners.add(cb); return () => listeners.delete(cb); @@ -69,6 +66,6 @@ export function moduleMessagesFor(client: MeshClient): ModuleMessages { } }, }; - stores.set(client, store); + stores.set(session, store); return store; } diff --git a/apps/web/src/core/kmp/nodes.ts b/apps/web/src/core/kmp/nodes.ts new file mode 100644 index 000000000..2657217e7 --- /dev/null +++ b/apps/web/src/core/kmp/nodes.ts @@ -0,0 +1,334 @@ +import { fromBinary } from "@bufbuild/protobuf"; +import { Protobuf } from "@core/protobuf.ts"; +import type { Node, NodesRepository } from "@core/storage/types.ts"; +import { firmwareAtLeast } from "@core/utils/firmware.ts"; +import type { NodeChangeJs } from "@meshtastic/sdk-kmp"; +import { signal } from "@preact/signals-core"; +import type { Result } from "better-result"; +import { deriveSignal as derive, type ReadonlySignal } from "./signals.ts"; + +export type NodeErrorType = + | Protobuf.Mesh.Routing_Error + | "MISMATCH_PKI" + | "DUPLICATE_PKI"; + +export interface NodeError { + readonly node: number; + readonly error: NodeErrorType; +} + +export function nodeFromProto(info: Protobuf.Mesh.NodeInfo): Node { + return { + num: info.num, + user: info.user, + position: info.position, + deviceMetrics: info.deviceMetrics, + lastHeard: info.lastHeard, + snr: info.snr, + channel: info.channel, + viaMqtt: info.viaMqtt, + hopsAway: info.hopsAway, + isFavorite: info.isFavorite, + isIgnored: info.isIgnored, + isKeyManuallyVerified: info.isKeyManuallyVerified, + isMuted: info.isMuted, + hasXeddsaSigned: info.hasXeddsaSigned, + heardOnCurrentLora: info.heardOnCurrentLora, + }; +} + +function equalKey(a?: Uint8Array, b?: Uint8Array): boolean { + if (!a || !b || a.byteLength !== b.byteLength) return false; + return a.every((byte, i) => byte === b[i]); +} + +export interface ValidatedNodeInfo { + readonly accepted: Protobuf.Mesh.NodeInfo | undefined; + readonly error: NodeErrorType | undefined; +} + +/** + * Checks an incoming NodeInfo against the known public keys: a new node + * presenting another node's key is dropped as DUPLICATE_PKI, a known node + * changing its key is dropped as MISMATCH_PKI, and a known node arriving + * without a key is ignored. + */ +export function validateIncomingNode( + incoming: Protobuf.Mesh.NodeInfo, + existingByNum: ReadonlyMap, +): ValidatedNodeInfo { + const existing = existingByNum.get(incoming.num); + const newKey = incoming.user?.publicKey; + if (!existing) { + if (newKey && newKey.length > 0) { + for (const node of existingByNum.values()) { + const otherKey = node.user?.publicKey; + if (otherKey && otherKey.length > 0 && equalKey(otherKey, newKey)) { + return { accepted: undefined, error: "DUPLICATE_PKI" }; + } + } + } + return { accepted: incoming, error: undefined }; + } + const oldKey = existing.user?.publicKey; + if (!oldKey || oldKey.length === 0 || equalKey(oldKey, newKey)) { + return { accepted: incoming, error: undefined }; + } + if (newKey && newKey.length > 0) { + return { accepted: undefined, error: "MISMATCH_PKI" }; + } + return { accepted: undefined, error: undefined }; +} + +export interface NodesAdmin { + /** Sends one admin message to the local node. */ + sendAdmin( + variant: Protobuf.Admin.AdminMessage["payloadVariant"], + ): Promise>; + firmwareVersion(): string | undefined; + myNodeNum(): number | undefined; +} + +/** + * The device's node DB as the SDK reports it, plus the per-node errors the + * web tracks (PKI collisions and routing failures) and the stored snapshot + * shown until the handshake's node DB arrives. + */ +export class NodesClient { + private readonly nodes = signal>(new Map()); + private readonly errorMap = signal>(new Map()); + private epoch = 0; + + readonly list: ReadonlySignal>; + readonly errors: ReadonlySignal>; + + constructor( + private readonly admin: NodesAdmin, + private readonly repository?: NodesRepository, + ) { + this.list = derive(this.nodes, (m) => [...m.values()]); + this.errors = derive(this.errorMap, (m) => [...m.values()]); + void this.hydrate(); + } + + applyChange(change: NodeChangeJs): void { + switch (change.kind) { + case "snapshot": { + const next = new Map(); + for (const bytes of change.nodes ?? []) { + const info = fromBinary(Protobuf.Mesh.NodeInfoSchema, bytes); + next.set( + info.num, + this.merged(info, this.nodes.peek().get(info.num)), + ); + } + this.nodes.value = next; + void this.repository?.upsertBatch([...next.values()]).catch(() => {}); + return; + } + case "added": + case "updated": { + if (change.node) { + this.handleIncoming( + fromBinary(Protobuf.Mesh.NodeInfoSchema, change.node), + ); + } + return; + } + case "removed": { + this.delete(change.nodeNum); + return; + } + default: + return; + } + } + + private handleIncoming(info: Protobuf.Mesh.NodeInfo): void { + const verdict = validateIncomingNode(info, this.nodes.peek()); + if (verdict.error) this.setError(info.num, verdict.error); + if (!verdict.accepted) return; + const node = this.merged(verdict.accepted, this.nodes.peek().get(info.num)); + this.set(node); + if (this.errorMap.peek().has(node.num)) this.clearError(node.num); + } + + private merged( + info: Protobuf.Mesh.NodeInfo, + existing: Node | undefined, + ): Node { + const mapped = nodeFromProto(info); + return { + ...mapped, + position: mapped.position ?? existing?.position, + deviceMetrics: mapped.deviceMetrics ?? existing?.deviceMetrics, + status: existing?.status, + heardOnCurrentLora: + mapped.heardOnCurrentLora || !this.firmwareReportsHeard(), + }; + } + + /** heard_on_current_lora exists from firmware 2.8.1. */ + private firmwareReportsHeard(): boolean { + const version = this.admin.firmwareVersion(); + return !!version && firmwareAtLeast(version, "2.8.1"); + } + + /** Every inbound packet with a time refreshes the sender's lastHeard and snr. */ + heard(packet: Protobuf.Mesh.MeshPacket): void { + if (!packet.rxTime) return; + this.patch(packet.from, { + lastHeard: packet.rxTime, + ...(packet.rxRssi !== undefined || packet.rxSnr !== 0 + ? { snr: packet.rxSnr } + : {}), + }); + } + + patch(nodeNum: number, partial: Partial): void { + if (nodeNum === 0) return; + const existing = this.nodes.peek().get(nodeNum); + const next: Node = existing + ? { ...existing, ...partial } + : { num: nodeNum, isFavorite: false, isIgnored: false, ...partial }; + this.set(next); + } + + routingError(nodeNum: number, reason: Protobuf.Mesh.Routing_Error): void { + const E = Protobuf.Mesh.Routing_Error; + if ( + reason === E.PKI_UNKNOWN_PUBKEY || + reason === E.PKI_FAILED || + reason === E.PKI_SEND_FAIL_PUBLIC_KEY || + reason === E.NO_CHANNEL + ) { + this.setError(nodeNum, reason); + } + } + + private set(node: Node): void { + const next = new Map(this.nodes.peek()); + next.set(node.num, node); + this.nodes.value = next; + void this.repository?.upsert(node).catch(() => {}); + } + + private delete(nodeNum: number): void { + const next = new Map(this.nodes.peek()); + if (next.delete(nodeNum)) this.nodes.value = next; + this.clearError(nodeNum); + void this.repository?.remove(nodeNum).catch(() => {}); + } + + private async hydrate(): Promise { + if (!this.repository) return; + const epoch = this.epoch; + try { + const persisted = await this.repository.loadAll(); + if (epoch !== this.epoch) return; + const next = new Map(this.nodes.peek()); + for (const node of persisted) { + if (!next.has(node.num)) next.set(node.num, node); + } + this.nodes.value = next; + } catch { + // nothing stored yet + } + } + + rescope(scope: number): void { + this.repository?.setScope?.(scope); + this.epoch++; + this.nodes.value = new Map(); + this.errorMap.value = new Map(); + void this.hydrate(); + } + + byNum(nodeNum: number): Node | undefined { + return this.nodes.peek().get(nodeNum); + } + + errorFor(nodeNum: number): NodeError | undefined { + return this.errorMap.peek().get(nodeNum); + } + + hasError(nodeNum: number): boolean { + return this.errorMap.peek().has(nodeNum); + } + + setError(nodeNum: number, error: NodeErrorType): void { + const next = new Map(this.errorMap.peek()); + next.set(nodeNum, { node: nodeNum, error }); + this.errorMap.value = next; + } + + clearError(nodeNum: number): void { + const next = new Map(this.errorMap.peek()); + if (next.delete(nodeNum)) this.errorMap.value = next; + } + + clearAllErrors(): void { + if (this.errorMap.peek().size > 0) this.errorMap.value = new Map(); + } + + async favorite(nodeNum: number): Promise> { + const result = await this.admin.sendAdmin({ + case: "setFavoriteNode", + value: nodeNum, + }); + if (result.status === "ok") this.patch(nodeNum, { isFavorite: true }); + return result; + } + + async unfavorite(nodeNum: number): Promise> { + const result = await this.admin.sendAdmin({ + case: "removeFavoriteNode", + value: nodeNum, + }); + if (result.status === "ok") this.patch(nodeNum, { isFavorite: false }); + return result; + } + + async ignore(nodeNum: number): Promise> { + const result = await this.admin.sendAdmin({ + case: "setIgnoredNode", + value: nodeNum, + }); + if (result.status === "ok") this.patch(nodeNum, { isIgnored: true }); + return result; + } + + async unignore(nodeNum: number): Promise> { + const result = await this.admin.sendAdmin({ + case: "removeIgnoredNode", + value: nodeNum, + }); + if (result.status === "ok") this.patch(nodeNum, { isIgnored: false }); + return result; + } + + remove(nodeNum: number): Promise> { + this.delete(nodeNum); + return this.admin.sendAdmin({ case: "removeByNodenum", value: nodeNum }); + } + + /** Wipes every node except, optionally, our own, then resets the device's node DB. */ + async reset( + options: { keepMyNode?: boolean } = {}, + ): Promise> { + const myNodeNum = this.admin.myNodeNum(); + const me = + options.keepMyNode && myNodeNum !== undefined + ? this.nodes.peek().get(myNodeNum) + : undefined; + this.nodes.value = me ? new Map([[me.num, me]]) : new Map(); + this.errorMap.value = new Map(); + try { + await this.repository?.clear(); + if (me) await this.repository?.upsert(me); + } catch { + // storage is best effort + } + return this.admin.sendAdmin({ case: "nodedbReset", value: true }); + } +} diff --git a/apps/web/src/core/kmp/packets.ts b/apps/web/src/core/kmp/packets.ts new file mode 100644 index 000000000..a0e1bb85d --- /dev/null +++ b/apps/web/src/core/kmp/packets.ts @@ -0,0 +1,97 @@ +import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; +import { Protobuf, type Types } from "@core/protobuf.ts"; + +export const BROADCAST_NUM = 0xffffffff; + +/** + * Hops the packet took, from hop_start and hop_limit. Unknown when hop_start + * is 0 (firmware older than 2.3, which didn't set it) or hop_limit is above it. + */ +export function hopsAway( + hopStart: number, + hopLimit: number, +): number | undefined { + if (hopStart === 0 || hopLimit > hopStart) return undefined; + return hopStart - hopLimit; +} + +/** + * Metadata of an inbound packet. rx_snr is a plain proto3 float, so 0 can + * mean a 0 dB reading or no reading; rx_rssi is only set when the radio + * measured the packet, so it tells the two apart. + */ +export function packetMetadata( + packet: Protobuf.Mesh.MeshPacket, + data: Protobuf.Mesh.Data, +): Omit, "data"> { + const measured = packet.rxRssi !== undefined || packet.rxSnr !== 0; + return { + id: packet.id, + rxTime: packet.rxTime ? new Date(packet.rxTime * 1000) : new Date(), + type: packet.to === BROADCAST_NUM ? "broadcast" : "direct", + from: packet.from, + to: packet.to, + channel: packet.channel, + requestId: data.requestId || undefined, + xeddsaSigned: packet.xeddsaSigned, + ackProofStatus: packet.ackProofStatus, + rxSnr: measured ? packet.rxSnr : undefined, + rxRssi: packet.rxRssi, + hopsAway: hopsAway(packet.hopStart, packet.hopLimit), + viaMqtt: packet.viaMqtt, + transportMechanism: packet.transportMechanism, + }; +} + +export function withData( + meta: Omit, "data">, + data: T, +): Types.PacketMetadata { + return { ...meta, data }; +} + +export interface OutboundPacket { + payload: Uint8Array; + portNum: Protobuf.Portnums.PortNum; + destination: Types.Destination; + channel?: Types.ChannelNumber; + wantAck?: boolean; + wantResponse?: boolean; +} + +/** Encodes a MeshPacket for the facade's `sendPacket`; the SDK assigns the id. */ +export function encodeOutbound( + packet: OutboundPacket, + myNodeNum: number, +): Uint8Array { + const to = + packet.destination === "broadcast" + ? BROADCAST_NUM + : packet.destination === "self" + ? myNodeNum + : packet.destination; + return toBinary( + Protobuf.Mesh.MeshPacketSchema, + create(Protobuf.Mesh.MeshPacketSchema, { + to, + channel: packet.channel ?? 0, + wantAck: packet.wantAck ?? false, + payloadVariant: { + case: "decoded", + value: create(Protobuf.Mesh.DataSchema, { + portnum: packet.portNum, + payload: packet.payload, + wantResponse: packet.wantResponse ?? false, + }), + }, + }), + ); +} + +export function decodeMeshPacket(bytes: Uint8Array): Protobuf.Mesh.MeshPacket { + return fromBinary(Protobuf.Mesh.MeshPacketSchema, bytes); +} + +export function decodeFromRadio(bytes: Uint8Array): Protobuf.Mesh.FromRadio { + return fromBinary(Protobuf.Mesh.FromRadioSchema, bytes); +} diff --git a/apps/web/src/core/kmp/registry.ts b/apps/web/src/core/kmp/registry.ts new file mode 100644 index 000000000..c69b3a634 --- /dev/null +++ b/apps/web/src/core/kmp/registry.ts @@ -0,0 +1,40 @@ +import { signal } from "@preact/signals-core"; +import type { MeshSession } from "./session.ts"; +import { type ReadonlySignal, toReadonly } from "./signals.ts"; + +/** One session per connection, and which of them the app is looking at. */ +export class MeshRegistry { + private readonly sessions = new Map(); + private readonly activeStore = signal(undefined); + + readonly active: ReadonlySignal = toReadonly( + this.activeStore, + ); + + register(id: number, session: MeshSession): void { + this.sessions.set(id, session); + } + + unregister(id: number): void { + const session = this.sessions.get(id); + this.sessions.delete(id); + if (session && this.activeStore.peek() === session) { + this.activeStore.value = undefined; + } + } + + has(id: number): boolean { + return this.sessions.has(id); + } + + get(id: number): MeshSession | undefined { + return this.sessions.get(id); + } + + setActive(id: number): void { + this.activeStore.value = this.sessions.get(id); + } +} + +/** The app-wide registry. */ +export const meshRegistry = new MeshRegistry(); diff --git a/apps/web/src/core/kmp/session.test.ts b/apps/web/src/core/kmp/session.test.ts new file mode 100644 index 000000000..8f4a98c06 --- /dev/null +++ b/apps/web/src/core/kmp/session.test.ts @@ -0,0 +1,419 @@ +import { create, toBinary } from "@bufbuild/protobuf"; +import { Protobuf } from "@core/protobuf.ts"; +import { MessageState } from "@core/storage/types.ts"; +import { describe, expect, it } from "vitest"; +import { FakeKmpClient, state } from "./fakeClient.ts"; +import { validateIncomingNode } from "./nodes.ts"; +import { BROADCAST_NUM } from "./packets.ts"; +import { MeshSession } from "./session.ts"; + +const ME = 0x0a0b0c0d; +const PEER = 0x11223344; + +function frame( + payloadVariant: Protobuf.Mesh.FromRadio["payloadVariant"], +): Uint8Array { + return toBinary( + Protobuf.Mesh.FromRadioSchema, + create(Protobuf.Mesh.FromRadioSchema, { payloadVariant }), + ); +} + +function packet(init: { + id?: number; + from: number; + to: number; + portnum: Protobuf.Portnums.PortNum; + payload: Uint8Array; + requestId?: number; + rxTime?: number; + channel?: number; +}): Uint8Array { + return toBinary( + Protobuf.Mesh.MeshPacketSchema, + create(Protobuf.Mesh.MeshPacketSchema, { + id: init.id ?? 1, + from: init.from, + to: init.to, + channel: init.channel ?? 0, + rxTime: init.rxTime ?? 1_700_000_000, + payloadVariant: { + case: "decoded", + value: create(Protobuf.Mesh.DataSchema, { + portnum: init.portnum, + payload: init.payload, + requestId: init.requestId ?? 0, + }), + }, + }), + ); +} + +const text = (from: number, to: number, body: string, id = 1): Uint8Array => + packet({ + id, + from, + to, + portnum: Protobuf.Portnums.PortNum.TEXT_MESSAGE_APP, + payload: new TextEncoder().encode(body), + }); + +const ack = ( + from: number, + requestId: number, + error = Protobuf.Mesh.Routing_Error.NONE, +): Uint8Array => + packet({ + id: 900 + requestId, + from, + to: ME, + requestId, + portnum: Protobuf.Portnums.PortNum.ROUTING_APP, + payload: toBinary( + Protobuf.Mesh.RoutingSchema, + create(Protobuf.Mesh.RoutingSchema, { + variant: { case: "errorReason", value: error }, + }), + ), + }); + +const nodeInfo = (num: number, publicKey?: Uint8Array): Uint8Array => + toBinary( + Protobuf.Mesh.NodeInfoSchema, + create(Protobuf.Mesh.NodeInfoSchema, { + num, + user: create(Protobuf.Mesh.UserSchema, { + longName: `node ${num}`, + publicKey, + }), + }), + ); + +function connected(): { kmp: FakeKmpClient; session: MeshSession } { + const kmp = new FakeKmpClient(); + const session = new MeshSession(kmp); + kmp.setState(state("configuring")); + kmp.emitFrame( + frame({ + case: "myInfo", + value: create(Protobuf.Mesh.MyNodeInfoSchema, { myNodeNum: ME }), + }), + ); + kmp.setState(state("connected")); + return { kmp, session }; +} + +describe("MeshSession", () => { + it("reads the handshake into the device view and the progress counters", () => { + const kmp = new FakeKmpClient(); + const session = new MeshSession(kmp); + kmp.setState(state("configuring")); + kmp.emitFrame( + frame({ + case: "myInfo", + value: create(Protobuf.Mesh.MyNodeInfoSchema, { myNodeNum: ME }), + }), + ); + kmp.emitFrame( + frame({ + case: "metadata", + value: create(Protobuf.Mesh.DeviceMetadataSchema, { + firmwareVersion: "2.8.3.abcdef", + }), + }), + ); + kmp.emitFrame( + frame({ + case: "config", + value: create(Protobuf.Config.ConfigSchema, { + payloadVariant: { + case: "lora", + value: create(Protobuf.Config.Config_LoRaConfigSchema, { + region: Protobuf.Config.Config_LoRaConfig_RegionCode.UNSET, + }), + }, + }), + }), + ); + kmp.emitFrame( + frame({ + case: "channel", + value: create(Protobuf.Channel.ChannelSchema, { + index: 0, + role: Protobuf.Channel.Channel_Role.PRIMARY, + }), + }), + ); + expect(session.progress.value).toEqual({ + phase: "configuring", + received: { + config: 1, + modules: 0, + channels: 1, + nodes: 0, + myInfo: true, + metadata: true, + }, + }); + expect(session.device.myNodeNum.value).toBe(ME); + expect(session.device.metadata.value?.firmwareVersion).toBe("2.8.3.abcdef"); + expect(session.device.firmwareSupport.value).toBe("supported"); + expect(session.config.isRegionUnset.value).toBe(true); + expect(session.channels.list.value.map((c) => c.index)).toEqual([0]); + + kmp.setState(state("connected")); + expect(session.progress.value.phase).toBe("configured"); + expect(session.device.isConfigured.value).toBe(true); + }); + + it("files inbound text under its conversation and counts it unread", () => { + const { kmp, session } = connected(); + const direct = session.chat.direct(PEER); + const channel = session.chat.messages(0); + + kmp.emitPacket(text(PEER, ME, "hi", 10)); + kmp.emitPacket(text(PEER, BROADCAST_NUM, "all", 11)); + + expect(direct.value.map((m) => m.text)).toEqual(["hi"]); + expect(channel.value.map((m) => m.text)).toEqual(["all"]); + expect(direct.value[0]?.state).toBe(MessageState.Ack); + expect(session.chat.unread.total.value).toBe(2); + expect(session.chat.unread.byKey.value.get(`direct:${PEER}`)).toBe(1); + + session.chat.unread.markRead({ kind: "direct", peer: PEER }); + expect(session.chat.unread.total.value).toBe(1); + }); + + it("sends text under the SDK's packet id and settles it from the routing ack", async () => { + const { kmp, session } = connected(); + kmp.holdSends = true; + const direct = session.chat.direct(PEER); + + const sending = session.chat.send({ text: "yo", destination: PEER }); + const id = kmp.texts[0]?.id; + expect(id).toBeDefined(); + expect(direct.value.map((m) => [m.id, m.state])).toEqual([ + [id, MessageState.Pending], + ]); + + kmp.emitPacket(ack(PEER, id ?? 0)); + expect(direct.value[0]?.state).toBe(MessageState.Ack); + expect(direct.value[0]?.relays).toBe(1); + + kmp.settleSends({ ok: true, reason: null }); + const result = await sending; + expect(result.status).toBe("ok"); + expect(direct.value[0]?.state).toBe(MessageState.Ack); + }); + + it("marks a send the SDK gave up on as failed with the routing error", async () => { + const { kmp, session } = connected(); + kmp.sendOutcome = { ok: false, reason: "NO_CHANNEL" }; + const channel = session.chat.messages(0); + const result = await session.chat.send({ + text: "x", + destination: "broadcast", + channel: 0, + }); + expect(result.status).toBe("error"); + expect(channel.value[0]).toMatchObject({ + state: MessageState.Failed, + routingError: Protobuf.Mesh.Routing_Error.NO_CHANNEL, + }); + }); + + it("keeps an ack that beat the send's id and marks a relay ack as delivered", async () => { + const { kmp, session } = connected(); + kmp.holdSends = true; + const channel = session.chat.messages(0); + kmp.emitPacket(ack(0x55, 1)); + const sending = session.chat.send({ text: "x", destination: "broadcast" }); + expect(channel.value[0]?.state).toBe(MessageState.Delivered); + kmp.settleSends(); + await sending; + expect(channel.value[0]?.state).toBe(MessageState.Delivered); + }); + + it("mirrors the SDK's node DB and refuses a node presenting another node's key", () => { + const { kmp, session } = connected(); + const key = new Uint8Array([1, 2, 3]); + kmp.emitNodeChange({ + kind: "snapshot", + nodes: [nodeInfo(PEER, key), nodeInfo(0x99)], + node: null, + nodeNum: 0, + }); + expect(session.nodes.list.value.map((n) => n.num)).toEqual([PEER, 0x99]); + + kmp.emitNodeChange({ + kind: "added", + nodes: null, + node: nodeInfo(0x77, key), + nodeNum: 0x77, + }); + expect(session.nodes.byNum(0x77)).toBeUndefined(); + expect(session.nodes.errors.value).toEqual([ + { node: 0x77, error: "DUPLICATE_PKI" }, + ]); + + kmp.emitNodeChange({ + kind: "removed", + nodes: null, + node: null, + nodeNum: 0x99, + }); + expect(session.nodes.list.value.map((n) => n.num)).toEqual([PEER]); + }); + + it("refreshes lastHeard, position and status from live packets", () => { + const { kmp, session } = connected(); + kmp.emitPacket( + packet({ + from: PEER, + to: BROADCAST_NUM, + rxTime: 1_700_000_123, + portnum: Protobuf.Portnums.PortNum.POSITION_APP, + payload: toBinary( + Protobuf.Mesh.PositionSchema, + create(Protobuf.Mesh.PositionSchema, { latitudeI: 5 }), + ), + }), + ); + kmp.emitPacket( + packet({ + from: PEER, + to: BROADCAST_NUM, + rxTime: 1_700_000_123, + portnum: Protobuf.Portnums.PortNum.NODE_STATUS_APP, + payload: toBinary( + Protobuf.Mesh.StatusMessageSchema, + create(Protobuf.Mesh.StatusMessageSchema, { status: "busy" }), + ), + }), + ); + const node = session.nodes.byNum(PEER); + expect(node?.lastHeard).toBe(1_700_000_123); + expect(node?.position?.latitudeI).toBe(5); + expect(node?.status).toBe("busy"); + }); + + it("records a routing error against the node and raises it as a node error", () => { + const { kmp, session } = connected(); + kmp.emitPacket( + ack(PEER, 5, Protobuf.Mesh.Routing_Error.PKI_UNKNOWN_PUBKEY), + ); + expect(session.nodes.errors.value).toEqual([ + { node: PEER, error: Protobuf.Mesh.Routing_Error.PKI_UNKNOWN_PUBKEY }, + ]); + }); + + it("keeps telemetry history per node and folds device metrics into the node", () => { + const { kmp, session } = connected(); + const history = session.telemetry.history(PEER); + kmp.emitPacket( + packet({ + from: PEER, + to: BROADCAST_NUM, + portnum: Protobuf.Portnums.PortNum.TELEMETRY_APP, + payload: toBinary( + Protobuf.Telemetry.TelemetrySchema, + create(Protobuf.Telemetry.TelemetrySchema, { + variant: { + case: "deviceMetrics", + value: create(Protobuf.Telemetry.DeviceMetricsSchema, { + batteryLevel: 42, + }), + }, + }), + ), + }), + ); + expect(history.value.map((r) => r.kind)).toEqual(["deviceMetrics"]); + expect(session.nodes.byNum(PEER)?.deviceMetrics?.batteryLevel).toBe(42); + }); + + it("keeps beacon offers newest first, one per sender, and drops dismissed ones", () => { + const { kmp, session } = connected(); + const beacon = (from: number, name: string) => + packet({ + from, + to: BROADCAST_NUM, + portnum: Protobuf.Portnums.PortNum.MESH_BEACON_APP, + payload: toBinary( + Protobuf.MeshBeacon.MeshBeaconSchema, + create(Protobuf.MeshBeacon.MeshBeaconSchema, { + offerChannel: create(Protobuf.Channel.ChannelSettingsSchema, { + name, + }), + }), + ), + }); + kmp.emitPacket(beacon(PEER, "a")); + kmp.emitPacket(beacon(0x66, "b")); + kmp.emitPacket(beacon(PEER, "c")); + kmp.emitPacket(beacon(ME, "mine")); + expect( + session.channels.beaconOffers.value.map( + (o) => o.beacon.offerChannel?.name, + ), + ).toEqual(["c", "b"]); + session.channels.dismissBeaconOffer(PEER); + expect(session.channels.beaconOffers.value.map((o) => o.from)).toEqual([ + 0x66, + ]); + }); + + it("sends the lockdown passphrase and re-runs the handshake once unlocked", async () => { + const { kmp, session } = connected(); + kmp.emitFrame( + frame({ + case: "lockdownStatus", + value: create(Protobuf.Mesh.LockdownStatusSchema, { + state: Protobuf.Mesh.LockdownStatus_State.LOCKED, + }), + }), + ); + expect(session.device.isLocked.value).toBe(true); + await session.device.unlock({ passphrase: "open sesame" }); + expect(kmp.admin().sent).toHaveLength(1); + + kmp.emitFrame( + frame({ + case: "lockdownStatus", + value: create(Protobuf.Mesh.LockdownStatusSchema, { + state: Protobuf.Mesh.LockdownStatus_State.UNLOCKED, + }), + }), + ); + expect(session.device.isLocked.value).toBe(false); + await Promise.resolve(); + expect(kmp.disconnects).toHaveLength(1); + }); +}); + +describe("validateIncomingNode", () => { + const key = new Uint8Array([9, 9, 9]); + const node = (num: number, publicKey?: Uint8Array) => ({ + num, + isFavorite: false, + isIgnored: false, + user: create(Protobuf.Mesh.UserSchema, { publicKey }), + }); + + it("rejects a key change as MISMATCH_PKI and drops a keyless update", () => { + const existing = new Map([[1, node(1, key)]]); + const changed = create(Protobuf.Mesh.NodeInfoSchema, { + num: 1, + user: { publicKey: new Uint8Array([1]) }, + }); + expect(validateIncomingNode(changed, existing)).toEqual({ + accepted: undefined, + error: "MISMATCH_PKI", + }); + const keyless = create(Protobuf.Mesh.NodeInfoSchema, { num: 1 }); + expect(validateIncomingNode(keyless, existing)).toEqual({ + accepted: undefined, + error: undefined, + }); + }); +}); diff --git a/apps/web/src/core/kmp/session.ts b/apps/web/src/core/kmp/session.ts new file mode 100644 index 000000000..40e85373a --- /dev/null +++ b/apps/web/src/core/kmp/session.ts @@ -0,0 +1,577 @@ +import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; +import { createLogger } from "@core/log.ts"; +import { Protobuf, Types } from "@core/protobuf.ts"; +import type { + DraftRepository, + MessageRepository, + NodesRepository, + RetentionPolicy, + TelemetryRepository, + TelemetryRetentionPolicy, +} from "@core/storage/types.ts"; +import type { + AdminResultJs, + ConnectionStateJs, + MeshtasticClient, + SendOutcomeJs, +} from "@meshtastic/sdk-kmp"; +import { signal } from "@preact/signals-core"; +import { Result } from "better-result"; +import { + adminMessage, + type AdminVariant, + encodeAdminMessage, + getText, + sendAdmin, + toResult, +} from "./admin.ts"; +import { ChannelsClient } from "./channels.ts"; +import { ChatClient } from "./chat.ts"; +import { DeviceClient } from "./device.ts"; +import { Emitter } from "./emitter.ts"; +import { NodesClient } from "./nodes.ts"; +import { + decodeFromRadio, + decodeMeshPacket, + encodeOutbound, + type OutboundPacket, + packetMetadata, + withData, +} from "./packets.ts"; +import { type ReadonlySignal, toReadonly } from "./signals.ts"; +import { TelemetryClient } from "./telemetry.ts"; + +const log = createLogger("session"); + +export interface ConnectionProgressCounters { + config: number; + modules: number; + channels: number; + nodes: number; + myInfo: boolean; + metadata: boolean; +} + +export type ConnectionProgress = + | { phase: "idle" } + | { phase: "configuring"; received: ConnectionProgressCounters } + | { phase: "configured"; received: ConnectionProgressCounters }; + +const EMPTY_COUNTERS: ConnectionProgressCounters = { + config: 0, + modules: 0, + channels: 0, + nodes: 0, + myInfo: false, + metadata: false, +}; + +export interface SessionOptions { + messages?: MessageRepository; + drafts?: DraftRepository; + nodes?: NodesRepository; + telemetry?: TelemetryRepository; + chatRetention?: RetentionPolicy; + telemetryRetention?: TelemetryRetentionPolicy; +} + +type Packet = Types.PacketMetadata; + +/** + * Everything the web reads from one radio, built on the Kotlin SDK facade: + * the decoded FromRadio and MeshPacket streams as typed events, and the + * device, nodes, channels, chat and telemetry views over them. The SDK + * owns the connection, handshake and node DB; this owns what the SDK does + * not keep (messages, drafts, telemetry history, per-node errors) and the + * web's view of the rest. + */ +export class MeshSession { + readonly events = { + onFromRadio: new Emitter(), + onMeshPacket: new Emitter(), + onMessagePacket: new Emitter>(), + onRoutingPacket: new Emitter>(), + onPositionPacket: new Emitter>(), + onUserPacket: new Emitter>(), + onTelemetryPacket: new Emitter>(), + onTraceRoutePacket: new Emitter>(), + onWaypointPacket: new Emitter>(), + onNeighborInfoPacket: new Emitter>(), + onAdminPacket: new Emitter>(), + onNodeStatusPacket: new Emitter>(), + onMeshBeaconPacket: new Emitter>(), + onClientNotificationPacket: new Emitter(), + onDeviceMetadataPacket: new Emitter<{ + from: number; + data: Protobuf.Mesh.DeviceMetadata; + }>(), + onMyNodeInfo: new Emitter(), + onNodeInfoPacket: new Emitter(), + onConfigPacket: new Emitter(), + onModuleConfigPacket: new Emitter(), + onChannelPacket: new Emitter(), + onLockdownStatus: new Emitter(), + onRegionPresets: new Emitter(), + onLogRecord: new Emitter(), + onRebooted: new Emitter(), + onConnectionState: new Emitter(), + onDeviceStatus: new Emitter(), + onPendingSettingsChange: new Emitter(), + }; + + readonly device: DeviceClient; + readonly nodes: NodesClient; + readonly channels: ChannelsClient; + readonly chat: ChatClient; + readonly telemetry: TelemetryClient; + readonly config: { + readonly isRegionUnset: ReadonlySignal; + requestCannedMessages(): Promise>; + requestRingtone(): Promise>; + }; + readonly progress: ReadonlySignal; + readonly log = log; + + private readonly progressStore = signal({ + phase: "idle", + }); + private readonly regionUnset = signal(false); + private readonly unsubscribes: Array<() => void> = []; + private rehandshaking = false; + + constructor( + readonly kmp: MeshtasticClient, + options: SessionOptions = {}, + ) { + const admin = { + sendAdmin: (variant: AdminVariant) => this.sendAdmin(variant), + firmwareVersion: () => this.device.metadata.peek()?.firmwareVersion, + myNodeNum: () => this.device.myNodeNum.peek(), + rehandshake: () => this.rehandshake(), + warn: (message: string, ...args: unknown[]) => log.warn(message, ...args), + }; + this.device = new DeviceClient(admin); + this.nodes = new NodesClient(admin, options.nodes); + this.channels = new ChannelsClient(() => this.device.myNodeNum.peek()); + this.chat = new ChatClient( + { + myNodeNum: () => this.myNodeNum, + sendText: (text, to, channel, replyId) => + kmp.sendText(text, to, channel, replyId), + warn: admin.warn, + }, + { + repository: options.messages, + draftRepository: options.drafts, + retention: options.chatRetention, + }, + ); + this.telemetry = new TelemetryClient({ + repository: options.telemetry, + retention: options.telemetryRetention, + }); + this.config = { + isRegionUnset: toReadonly(this.regionUnset), + requestCannedMessages: () => + getText(kmp, { + case: "getCannedMessageModuleMessagesRequest", + value: true, + }), + requestRingtone: () => + getText(kmp, { case: "getRingtoneRequest", value: true }), + }; + this.progress = toReadonly(this.progressStore); + + this.events.onPendingSettingsChange.subscribe((pending) => + this.device.setPendingSettingsChanges(pending), + ); + this.unsubscribes.push( + kmp.onConnectionState((state) => this.handleConnectionState(state)), + kmp.onFromRadio((bytes) => this.handleFromRadio(bytes)), + kmp.onPacket((bytes) => this.handlePacket(bytes)), + kmp.onNodeChange((change) => this.nodes.applyChange(change)), + ); + } + + /** The local node number, or 0 before the handshake names it. */ + get myNodeNum(): number { + return this.device.myNodeNum.peek() ?? this.kmp.myNodeNum ?? 0; + } + + /** True while a deliberate disconnect/connect cycle is running. */ + get isRehandshaking(): boolean { + return this.rehandshaking; + } + + sendAdmin( + variant: AdminVariant, + dest?: number, + ): Promise> { + return sendAdmin(this.kmp, variant, dest); + } + + sendPacket(packet: OutboundPacket): Promise { + return this.kmp.sendPacket(encodeOutbound(packet, this.myNodeNum)).outcome; + } + + sendWaypoint( + waypoint: Protobuf.Mesh.Waypoint, + destination: Types.Destination, + channel: Types.ChannelNumber = 0, + ): Promise { + return this.sendPacket({ + payload: toBinary(Protobuf.Mesh.WaypointSchema, waypoint), + portNum: Protobuf.Portnums.PortNum.WAYPOINT_APP, + destination, + channel, + }); + } + + requestPosition(nodeNum: number): Promise { + return this.kmp.requestPosition(nodeNum).outcome; + } + + async traceRoute( + nodeNum: number, + ): Promise> { + const result = toResult(await this.kmp.traceRoute(nodeNum)); + if (Result.isError(result)) return Result.err(result.error); + const bytes = result.value.value; + return bytes + ? Result.ok(fromBinary(Protobuf.Mesh.RouteDiscoverySchema, bytes)) + : Result.err(new Error("empty-response")); + } + + sendKeyVerification( + messageType: Protobuf.Admin.KeyVerificationAdmin_MessageType, + remoteNodenum: number, + nonce: bigint, + securityNumber?: number, + ): Promise> { + return this.sendAdmin({ + case: "keyVerification", + value: create(Protobuf.Admin.KeyVerificationAdminSchema, { + messageType, + remoteNodenum, + nonce, + securityNumber, + }), + }); + } + + private async adminOrThrow(variant: AdminVariant): Promise { + const result = await this.sendAdmin(variant); + if (Result.isError(result)) throw result.error; + } + + reboot(seconds = 0): Promise { + return this.adminOrThrow({ case: "rebootSeconds", value: seconds }); + } + + rebootOta(seconds = 0): Promise { + return this.adminOrThrow({ case: "rebootOtaSeconds", value: seconds }); + } + + shutdown(seconds = 0): Promise { + return this.adminOrThrow({ case: "shutdownSeconds", value: seconds }); + } + + enterDfuMode(): Promise { + return this.adminOrThrow({ case: "enterDfuModeRequest", value: true }); + } + + factoryResetDevice(): Promise { + return this.adminOrThrow({ case: "factoryResetDevice", value: 1 }); + } + + /** The SDK's AdminApi has no config-only reset, so this goes out as a raw admin packet. */ + async factoryResetConfig(): Promise { + const outcome = await this.sendPacket({ + payload: encodeAdminMessage( + adminMessage({ case: "factoryResetConfig", value: 1 }), + ), + portNum: Protobuf.Portnums.PortNum.ADMIN_APP, + destination: "self", + wantAck: true, + }); + if (!outcome.ok) throw new Error(outcome.reason ?? "factory reset failed"); + } + + /** Runs the handshake again by cycling the SDK connection. */ + async rehandshake(): Promise { + this.rehandshaking = true; + try { + await this.kmp.disconnect(); + await this.kmp.connect(); + } finally { + this.rehandshaking = false; + } + } + + disconnect(): Promise { + return this.kmp.disconnect(); + } + + /** Stops feeding the session; the SDK client is left to its owner. */ + close(): void { + for (const off of this.unsubscribes.splice(0)) off(); + } + + /** Points message, node and telemetry history at `nodeNum`'s. */ + rescope(nodeNum: number): void { + this.chat.rescope(nodeNum); + this.nodes.rescope(nodeNum); + this.telemetry.rescope(nodeNum); + } + + private handleConnectionState(state: ConnectionStateJs): void { + this.device.applyConnectionState(state); + this.events.onConnectionState.dispatch(state); + this.events.onDeviceStatus.dispatch(this.device.status.peek()); + switch (state.kind) { + case "connecting": + case "reconnecting": + this.progressStore.value = { phase: "idle" }; + return; + case "configuring": + if (this.progressStore.peek().phase !== "configuring") { + this.progressStore.value = { + phase: "configuring", + received: { ...EMPTY_COUNTERS }, + }; + } + return; + case "connected": { + const current = this.progressStore.peek(); + this.progressStore.value = { + phase: "configured", + received: + current.phase === "idle" ? { ...EMPTY_COUNTERS } : current.received, + }; + return; + } + default: + this.progressStore.value = { phase: "idle" }; + } + } + + private bump(field: keyof ConnectionProgressCounters): void { + const current = this.progressStore.peek(); + const received = + current.phase === "idle" ? { ...EMPTY_COUNTERS } : current.received; + const value = received[field]; + this.progressStore.value = { + phase: current.phase === "configured" ? "configured" : "configuring", + received: { + ...received, + [field]: typeof value === "number" ? value + 1 : true, + }, + }; + } + + private handleFromRadio(bytes: Uint8Array): void { + let frame: Protobuf.Mesh.FromRadio; + try { + frame = decodeFromRadio(bytes); + } catch (e) { + log.warn("undecodable FromRadio frame", e); + return; + } + this.events.onFromRadio.dispatch(frame); + const variant = frame.payloadVariant; + switch (variant.case) { + case "myInfo": + this.bump("myInfo"); + this.device.applyMyNodeInfo(variant.value); + this.chat.refileSentDirect(variant.value.myNodeNum); + this.events.onMyNodeInfo.dispatch(variant.value); + return; + case "metadata": + this.bump("metadata"); + this.device.applyMetadata(variant.value); + this.events.onDeviceMetadataPacket.dispatch({ + from: 0, + data: variant.value, + }); + return; + case "nodeInfo": + this.bump("nodes"); + this.events.onNodeInfoPacket.dispatch(variant.value); + return; + case "config": + this.bump("config"); + if (variant.value.payloadVariant.case === "lora") { + this.regionUnset.value = + variant.value.payloadVariant.value.region === + Protobuf.Config.Config_LoRaConfig_RegionCode.UNSET; + } + this.events.onConfigPacket.dispatch(variant.value); + return; + case "moduleConfig": + this.bump("modules"); + this.events.onModuleConfigPacket.dispatch(variant.value); + return; + case "channel": + this.bump("channels"); + this.channels.applyChannel(variant.value); + this.events.onChannelPacket.dispatch(variant.value); + return; + case "clientNotification": + this.events.onClientNotificationPacket.dispatch(variant.value); + return; + case "lockdownStatus": + this.device.applyLockdownStatus(variant.value); + this.events.onLockdownStatus.dispatch(variant.value); + return; + case "regionPresets": + this.device.applyRegionPresets(variant.value); + this.events.onRegionPresets.dispatch(variant.value); + return; + case "logRecord": + this.events.onLogRecord.dispatch(variant.value); + return; + case "rebooted": + if (variant.value) this.events.onRebooted.dispatch(); + return; + default: + return; + } + } + + private handlePacket(bytes: Uint8Array): void { + let packet: Protobuf.Mesh.MeshPacket; + try { + packet = decodeMeshPacket(bytes); + } catch (e) { + log.warn("undecodable MeshPacket", e); + return; + } + this.events.onMeshPacket.dispatch(packet); + this.nodes.heard(packet); + if (packet.payloadVariant.case !== "decoded") return; + const data = packet.payloadVariant.value; + const meta = packetMetadata(packet, data); + const PortNum = Protobuf.Portnums.PortNum; + try { + switch (data.portnum) { + case PortNum.TEXT_MESSAGE_APP: { + const text = withData(meta, new TextDecoder().decode(data.payload)); + this.chat.receive(text); + this.events.onMessagePacket.dispatch(text); + return; + } + case PortNum.ROUTING_APP: { + const routing = fromBinary(Protobuf.Mesh.RoutingSchema, data.payload); + if (routing.variant.case === "errorReason") { + this.chat.applyAck( + meta.requestId ?? meta.id, + meta.from, + routing.variant.value, + meta.ackProofStatus, + ); + if (routing.variant.value !== Protobuf.Mesh.Routing_Error.NONE) { + this.nodes.routingError(meta.from, routing.variant.value); + } + } + this.events.onRoutingPacket.dispatch(withData(meta, routing)); + return; + } + case PortNum.POSITION_APP: { + const position = fromBinary( + Protobuf.Mesh.PositionSchema, + data.payload, + ); + this.nodes.patch(meta.from, { position }); + this.events.onPositionPacket.dispatch(withData(meta, position)); + return; + } + case PortNum.NODEINFO_APP: { + const user = fromBinary(Protobuf.Mesh.UserSchema, data.payload); + this.nodes.patch(meta.from, { user }); + this.events.onUserPacket.dispatch(withData(meta, user)); + return; + } + case PortNum.TELEMETRY_APP: { + const telemetry = fromBinary( + Protobuf.Telemetry.TelemetrySchema, + data.payload, + ); + if (telemetry.variant.case === "deviceMetrics") { + this.nodes.patch(meta.from, { + deviceMetrics: telemetry.variant.value, + }); + } + const reading = withData(meta, telemetry); + this.telemetry.receive(reading); + this.events.onTelemetryPacket.dispatch(reading); + return; + } + case PortNum.TRACEROUTE_APP: + this.events.onTraceRoutePacket.dispatch( + withData( + meta, + fromBinary(Protobuf.Mesh.RouteDiscoverySchema, data.payload), + ), + ); + return; + case PortNum.WAYPOINT_APP: + this.events.onWaypointPacket.dispatch( + withData( + meta, + fromBinary(Protobuf.Mesh.WaypointSchema, data.payload), + ), + ); + return; + case PortNum.NEIGHBORINFO_APP: + this.events.onNeighborInfoPacket.dispatch( + withData( + meta, + fromBinary(Protobuf.Mesh.NeighborInfoSchema, data.payload), + ), + ); + return; + case PortNum.ADMIN_APP: { + const admin = fromBinary( + Protobuf.Admin.AdminMessageSchema, + data.payload, + ); + const response = admin.payloadVariant; + if ( + response.case === "getDeviceMetadataResponse" && + (meta.from === 0 || meta.from === this.myNodeNum) + ) { + this.device.applyMetadata(response.value); + this.events.onDeviceMetadataPacket.dispatch({ + from: meta.from, + data: response.value, + }); + } + this.events.onAdminPacket.dispatch(withData(meta, admin)); + return; + } + case PortNum.NODE_STATUS_APP: { + const status = fromBinary( + Protobuf.Mesh.StatusMessageSchema, + data.payload, + ); + this.nodes.patch(meta.from, { status: status.status }); + this.events.onNodeStatusPacket.dispatch(withData(meta, status)); + return; + } + case PortNum.MESH_BEACON_APP: { + const beacon = withData( + meta, + fromBinary(Protobuf.MeshBeacon.MeshBeaconSchema, data.payload), + ); + this.channels.applyBeacon(beacon); + this.events.onMeshBeaconPacket.dispatch(beacon); + return; + } + default: + return; + } + } catch (e) { + log.warn("undecodable payload", { portnum: data.portnum }, e); + } + } +} diff --git a/apps/web/src/core/kmp/signals.ts b/apps/web/src/core/kmp/signals.ts index b54a1141c..d41926087 100644 --- a/apps/web/src/core/kmp/signals.ts +++ b/apps/web/src/core/kmp/signals.ts @@ -37,3 +37,31 @@ export function toReadonly( export function constantSignal(value: T): ReadonlySignal { return { value, peek: () => value, subscribe: () => () => {} }; } + +/** A read-only view of `pick(source.value)`, recomputed only when the source changes. */ +export function deriveSignal( + source: ReadonlySignal, + pick: (value: T) => U, +): ReadonlySignal { + let last: { from: T; to: U } | undefined; + const memo = (from: T): U => { + if (!last || last.from !== from) last = { from, to: pick(from) }; + return last.to; + }; + return { + get value() { + return memo(source.value); + }, + peek: () => memo(source.peek()), + subscribe: (listener) => { + let first = true; + return source.subscribe((v) => { + if (first) { + first = false; + return; + } + listener(memo(v)); + }); + }, + }; +} diff --git a/apps/web/src/core/kmp/telemetry.ts b/apps/web/src/core/kmp/telemetry.ts new file mode 100644 index 000000000..b9d413efe --- /dev/null +++ b/apps/web/src/core/kmp/telemetry.ts @@ -0,0 +1,150 @@ +import type { Protobuf, Types } from "@core/protobuf.ts"; +import type { + TelemetryReading, + TelemetryRepository, + TelemetryRetentionPolicy, +} from "@core/storage/types.ts"; +import { type Signal, signal } from "@preact/signals-core"; +import { type ReadonlySignal, toReadonly } from "./signals.ts"; + +const MAX_HISTORY = 256; +const HYDRATE_LIMIT = 256; + +export interface TelemetryClientOptions { + repository?: TelemetryRepository; + retention?: TelemetryRetentionPolicy; +} + +/** Telemetry readings per node, live and from storage. */ +export class TelemetryClient { + private readonly latestStore = new Map< + number, + Signal + >(); + private readonly latestRead = new Map< + number, + ReadonlySignal + >(); + private readonly historyStore = new Map>(); + private readonly historyRead = new Map< + number, + ReadonlySignal + >(); + private readonly hydrated = new Set(); + private readonly repository: TelemetryRepository | undefined; + private readonly retention: TelemetryRetentionPolicy | undefined; + private epoch = 0; + + constructor(options: TelemetryClientOptions = {}) { + this.repository = options.repository; + this.retention = options.retention; + } + + receive(packet: Types.PacketMetadata): void { + const reading: TelemetryReading = { + nodeNum: packet.from, + time: packet.rxTime, + kind: packet.data.variant.case, + value: packet.data.variant.value, + }; + this.ensureLatest(reading.nodeNum).value = reading; + const history = this.ensureHistory(reading.nodeNum); + const next = [...history.value, reading]; + if (next.length > MAX_HISTORY) next.splice(0, next.length - MAX_HISTORY); + history.value = next; + void this.persist(reading); + } + + latest(nodeNum: number): ReadonlySignal { + void this.hydrate(nodeNum); + const sig = this.ensureLatest(nodeNum); + return this.latestRead.get(nodeNum) ?? toReadonly(sig); + } + + history(nodeNum: number): ReadonlySignal { + void this.hydrate(nodeNum); + const sig = this.ensureHistory(nodeNum); + return this.historyRead.get(nodeNum) ?? toReadonly(sig); + } + + rescope(scope: number): void { + this.repository?.setScope?.(scope); + this.epoch++; + const nodes = [...this.hydrated]; + this.hydrated.clear(); + for (const sig of this.latestStore.values()) sig.value = undefined; + for (const sig of this.historyStore.values()) { + if (sig.value.length > 0) sig.value = []; + } + for (const nodeNum of nodes) void this.hydrate(nodeNum); + } + + async clearNode(nodeNum: number): Promise { + this.hydrated.delete(nodeNum); + await this.repository?.clearNode(nodeNum); + } + + async clear(): Promise { + this.hydrated.clear(); + await this.repository?.clear(); + } + + private async persist(reading: TelemetryReading): Promise { + if (!this.repository) return; + try { + await this.repository.append(reading); + if (this.retention) await this.repository.prune(this.retention); + } catch (e) { + console.warn("[telemetry] persistence failed:", e); + } + } + + private async hydrate(nodeNum: number): Promise { + if (this.hydrated.has(nodeNum) || !this.repository) return; + this.hydrated.add(nodeNum); + const epoch = this.epoch; + try { + const readings = await this.repository.loadRecent(nodeNum, HYDRATE_LIMIT); + if (epoch !== this.epoch || readings.length === 0) return; + const history = this.ensureHistory(nodeNum); + const keyOf = (r: TelemetryReading): string => + `${r.kind}:${r.time.getTime()}`; + const seen = new Set(history.value.map(keyOf)); + const added = readings.filter((r) => { + const key = keyOf(r); + if (seen.has(key)) return false; + seen.add(key); + return true; + }); + if (added.length === 0) return; + const next = [...history.value, ...added].sort( + (a, b) => a.time.getTime() - b.time.getTime(), + ); + if (next.length > MAX_HISTORY) next.splice(0, next.length - MAX_HISTORY); + history.value = next; + this.ensureLatest(nodeNum).value = next[next.length - 1]; + } catch (e) { + console.warn("[telemetry] hydrate failed:", e); + } + } + + private ensureLatest(nodeNum: number): Signal { + let sig = this.latestStore.get(nodeNum); + if (!sig) { + sig = signal(undefined); + this.latestStore.set(nodeNum, sig); + this.latestRead.set(nodeNum, toReadonly(sig)); + } + return sig; + } + + private ensureHistory(nodeNum: number): Signal { + let sig = this.historyStore.get(nodeNum); + if (!sig) { + sig = signal([]); + this.historyStore.set(nodeNum, sig); + this.historyRead.set(nodeNum, toReadonly(sig)); + } + return sig; + } +} diff --git a/apps/web/src/core/kmp/transport.test.ts b/apps/web/src/core/kmp/transport.test.ts deleted file mode 100644 index 2dcee922a..000000000 --- a/apps/web/src/core/kmp/transport.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; -import { DeviceStatusEnum, type DeviceOutput } from "@meshtastic/sdk"; -import { Protobuf } from "@core/protobuf.ts"; -import { describe, expect, it } from "vitest"; -import { FakeKmpClient, state } from "./fakeClient.ts"; -import { kmpTransport } from "./transport.ts"; - -async function readAll( - stream: ReadableStream, - count: number, -): Promise { - const reader = stream.getReader(); - const out: DeviceOutput[] = []; - while (out.length < count) { - const { value, done } = await reader.read(); - if (done) break; - out.push(value); - } - reader.releaseLock(); - return out; -} - -describe("kmpTransport", () => { - it("replays FromRadio frames from the SDK as packets", async () => { - const client = new FakeKmpClient(); - await client.connect(); - const transport = kmpTransport(client); - const myInfo = toBinary( - Protobuf.Mesh.FromRadioSchema, - create(Protobuf.Mesh.FromRadioSchema, { - payloadVariant: { - case: "myInfo", - value: { myNodeNum: 0x0a0b0c0d }, - }, - }), - ); - client.emitFrame(myInfo); - - const [status, packet] = await readAll(transport.fromDevice, 2); - expect(status).toEqual({ - type: "status", - data: { status: DeviceStatusEnum.DeviceConnected }, - }); - if (packet?.type !== "packet") throw new Error("expected a packet"); - const decoded = fromBinary(Protobuf.Mesh.FromRadioSchema, packet.data); - expect(decoded.payloadVariant.case).toBe("myInfo"); - }); - - it("writes ToRadio bytes through the SDK", async () => { - const client = new FakeKmpClient(); - await client.connect(); - const transport = kmpTransport(client); - const writer = transport.toDevice.getWriter(); - const bytes = new Uint8Array([1, 2, 3]); - await writer.write(bytes); - expect(client.sent).toEqual([bytes]); - }); - - it("rejects writes while the SDK is reconnecting", async () => { - const client = new FakeKmpClient(); - await client.connect(); - const transport = kmpTransport(client); - client.setState(state("reconnecting", { attempt: 2 })); - const writer = transport.toDevice.getWriter(); - await expect(writer.write(new Uint8Array([1]))).rejects.toMatchObject({ - name: "not-connected", - }); - }); - - it("maps SDK states to device status events", async () => { - const client = new FakeKmpClient(); - await client.connect(); - const transport = kmpTransport(client); - client.setState(state("reconnecting", { attempt: 1 })); - client.setState(state("configuring", { phase: "Stage1" })); - client.setState(state("connected")); - const events = await readAll(transport.fromDevice, 3); - expect( - events.map((e) => (e.type === "status" ? e.data.status : e.type)), - ).toEqual([ - DeviceStatusEnum.DeviceConnected, - DeviceStatusEnum.DeviceReconnecting, - DeviceStatusEnum.DeviceConnected, - ]); - }); - - it("disconnects the SDK client and closes the stream once", async () => { - const client = new FakeKmpClient(); - await client.connect(); - const transport = kmpTransport(client); - await transport.disconnect(); - await transport.disconnect(); - expect(client.disconnects).toHaveLength(2); - const reader = transport.fromDevice.getReader(); - const first = await reader.read(); - expect(first).toEqual({ - value: { - type: "status", - data: { status: DeviceStatusEnum.DeviceConnected }, - }, - done: false, - }); - const last = await reader.read(); - expect(last.done).toBe(true); - client.emitFrame(new Uint8Array([9])); - }); -}); diff --git a/apps/web/src/core/kmp/transport.ts b/apps/web/src/core/kmp/transport.ts deleted file mode 100644 index b56bc2d85..000000000 --- a/apps/web/src/core/kmp/transport.ts +++ /dev/null @@ -1,82 +0,0 @@ -import type { ConnectionStateJs, MeshtasticClient } from "@meshtastic/sdk-kmp"; -import { - type DeviceOutput, - DeviceStatusEnum, - type Transport, -} from "@meshtastic/sdk"; - -function toDeviceStatus( - state: ConnectionStateJs, -): DeviceStatusEnum | undefined { - switch (state.kind) { - case "connected": - return DeviceStatusEnum.DeviceConnected; - case "reconnecting": - return DeviceStatusEnum.DeviceReconnecting; - case "disconnected": - return DeviceStatusEnum.DeviceDisconnected; - default: - return undefined; - } -} - -/** - * Presents a Kotlin SDK client as the TypeScript SDK's `Transport`, so the - * existing `MeshDevice` keeps feeding the stores while the Kotlin SDK owns - * the connection: every FromRadio frame the SDK receives is replayed here - * as bare protobuf bytes, and every ToRadio the web client writes goes - * through the SDK's send path. - */ -export function kmpTransport(client: MeshtasticClient): Transport { - let controller: ReadableStreamDefaultController | undefined; - let closed = false; - const unsubscribe: Array<() => void> = []; - - const close = (): void => { - if (closed) { - return; - } - closed = true; - for (const off of unsubscribe) { - off(); - } - controller?.close(); - }; - - const fromDevice = new ReadableStream({ - start(c) { - controller = c; - unsubscribe.push( - client.onFromRadio((bytes) => { - if (!closed) { - c.enqueue({ type: "packet", data: bytes }); - } - }), - client.onConnectionState((state) => { - const status = toDeviceStatus(state); - if (status !== undefined && !closed) { - c.enqueue({ type: "status", data: { status } }); - } - }), - ); - }, - cancel() { - close(); - }, - }); - - const toDevice = new WritableStream({ - write(chunk) { - client.sendRaw(chunk); - }, - }); - - return { - fromDevice, - toDevice, - async disconnect() { - close(); - await client.disconnect(); - }, - }; -} diff --git a/apps/web/src/core/meshRegistry.ts b/apps/web/src/core/meshRegistry.ts deleted file mode 100644 index f37b51a32..000000000 --- a/apps/web/src/core/meshRegistry.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { MeshRegistry } from "@meshtastic/sdk"; - -/** - * App-wide MeshRegistry singleton. - * - * Holds one `MeshClient` per active connection. Wrapped at the root by - * `` so descendant components - * can use `useMeshDevice()`, `useChat()`, etc. against the active client. - * - * During Phase B migration the registry coexists with the legacy Zustand - * deviceStore; `useConnections` continues to instantiate `MeshDevice` (the - * SDK's Phase-A shim) until per-slice migrations land. - */ -export const meshRegistry = new MeshRegistry(); diff --git a/apps/web/src/core/stores/deviceStore/deviceStore.mock.ts b/apps/web/src/core/stores/deviceStore/deviceStore.mock.ts index 90204c4a4..0fc71f1ea 100644 --- a/apps/web/src/core/stores/deviceStore/deviceStore.mock.ts +++ b/apps/web/src/core/stores/deviceStore/deviceStore.mock.ts @@ -23,7 +23,6 @@ export const mockDeviceStore: Device = { hardware: {} as Protobuf.Mesh.MyNodeInfo, metadata: new Map(), traceroutes: new Map(), - connection: undefined, activeNode: 0, waypoints: [], pendingSettingsChanges: false, @@ -62,7 +61,6 @@ export const mockDeviceStore: Device = { addWaypoint: vi.fn(), removeWaypoint: vi.fn(), getWaypoint: vi.fn(), - addConnection: vi.fn(), addTraceRoute: vi.fn(), addMetadata: vi.fn(), setDialogOpen: vi.fn(), diff --git a/apps/web/src/core/stores/deviceStore/deviceStore.test.ts b/apps/web/src/core/stores/deviceStore/deviceStore.test.ts index 18d608f09..a6caafa14 100644 --- a/apps/web/src/core/stores/deviceStore/deviceStore.test.ts +++ b/apps/web/src/core/stores/deviceStore/deviceStore.test.ts @@ -1,8 +1,21 @@ -import { create, toBinary } from "@bufbuild/protobuf"; +import { create } from "@bufbuild/protobuf"; import { Protobuf, type Types } from "@core/protobuf.ts"; import { beforeEach, describe, expect, it, vi } from "vitest"; const idbMem = new Map(); +const registry = vi.hoisted(() => ({ + session: undefined as + | { + sendWaypoint: (...args: unknown[]) => unknown; + sendAdmin: (...args: unknown[]) => unknown; + } + | undefined, +})); + +vi.mock("@core/kmp/registry.ts", () => ({ + meshRegistry: { active: { peek: () => registry.session } }, +})); + vi.mock("idb-keyval", () => ({ get: vi.fn((key: string) => Promise.resolve(idbMem.get(key))), set: vi.fn((key: string, val: string) => { @@ -181,7 +194,7 @@ describe("DeviceStore – traceroutes & waypoints retention + merge on setHardwa // Old device with myNodeNum=777 and some waypoints (one expired) const oldDevice = state.addDevice(1); const mockSendWaypoint = vi.fn(); - oldDevice.addConnection({ sendWaypoint: mockSendWaypoint } as any); + registry.session = { sendWaypoint: mockSendWaypoint, sendAdmin: vi.fn() }; oldDevice.setHardware(makeHardware(777)); oldDevice.addWaypoint( @@ -349,33 +362,24 @@ describe("DeviceStore – persistence partialize & rehydrate", () => { }); }); -describe("DeviceStore – connection & sendAdminMessage", () => { +describe("DeviceStore – sendAdminMessage", () => { beforeEach(() => { idbMem.clear(); vi.clearAllMocks(); }); - it("sendAdminMessage calls through to connection.sendPacket with correct args", async () => { + it("sendAdminMessage hands the message's variant to the active session", async () => { const { useDeviceStore } = await freshStore(false); const state = useDeviceStore.getState(); const device = state.addDevice(77); - const sendPacket = vi.fn(); - device.addConnection({ sendPacket } as any); + const sendAdmin = vi.fn(); + registry.session = { sendWaypoint: vi.fn(), sendAdmin }; const message = makeAdminMessage({ logVerbosity: 1 }); device.sendAdminMessage(message); - expect(sendPacket).toHaveBeenCalledTimes(1); - const [bytes, port, dest] = sendPacket.mock.calls[0]!; - expect(port).toBe(Protobuf.Portnums.PortNum.ADMIN_APP); - expect(dest).toBe("self"); - - // sanity: encoded bytes match toBinary on the same schema - const expected = toBinary(Protobuf.Admin.AdminMessageSchema, message); - expect(bytes).toBeInstanceOf(Uint8Array); - - // compare content length as minimal assertion (exact byte-for-byte is fine too) - expect((bytes as Uint8Array).length).toBe(expected.length); + expect(sendAdmin).toHaveBeenCalledTimes(1); + expect(sendAdmin).toHaveBeenCalledWith(message.payloadVariant); }); }); diff --git a/apps/web/src/core/stores/deviceStore/index.ts b/apps/web/src/core/stores/deviceStore/index.ts index 21c4beb83..775df55ef 100644 --- a/apps/web/src/core/stores/deviceStore/index.ts +++ b/apps/web/src/core/stores/deviceStore/index.ts @@ -1,7 +1,7 @@ -import { create, toBinary } from "@bufbuild/protobuf"; +import { create } from "@bufbuild/protobuf"; +import { meshRegistry } from "@core/kmp/registry.ts"; import { evictOldestEntries } from "@core/stores/utils/evictOldestEntries.ts"; import { createStorage } from "@core/stores/utils/indexDB.ts"; -import type { MeshDevice } from "@meshtastic/sdk"; import { Protobuf, Types } from "@core/protobuf.ts"; import { type Draft, produce } from "immer"; import { create as createStore, type StateCreator } from "zustand"; @@ -52,7 +52,6 @@ export interface Device extends DeviceData { moduleConfig: Protobuf.LocalOnly.LocalModuleConfig; hardware: Protobuf.Mesh.MyNodeInfo; metadata: Map; - connection?: MeshDevice; activeNode: number; pendingSettingsChanges: boolean; messageDraft: string; @@ -81,7 +80,6 @@ export interface Device extends DeviceData { ) => void; removeWaypoint: (waypointId: number, toMesh: boolean) => Promise; getWaypoint: (waypointId: number) => WaypointWithMetadata | undefined; - addConnection: (connection: MeshDevice) => void; addTraceRoute: ( traceroute: Types.PacketMetadata, ) => void; @@ -169,7 +167,6 @@ function deviceFactory( moduleConfig: create(Protobuf.LocalOnly.LocalModuleConfigSchema), hardware: create(Protobuf.Mesh.MyNodeInfoSchema), metadata: new Map(), - connection: undefined, activeNode: 0, dialog: { import: false, @@ -470,7 +467,8 @@ function deviceFactory( } if (toMesh) { - if (!device.connection) { + const session = meshRegistry.active.peek(); + if (!session) { return; } @@ -483,7 +481,7 @@ function deviceFactory( expire: 1, }); - await device.connection.sendWaypoint( + await session.sendWaypoint( waypointToBroadcast, "broadcast", waypoint.metadata.channel, @@ -525,16 +523,6 @@ function deviceFactory( }), ); }, - addConnection: (connection) => { - set( - produce((draft) => { - const device = draft.devices.get(id); - if (device) { - device.connection = connection as unknown as Draft; - } - }), - ); - }, addMetadata: (from, metadata) => { set( produce((draft) => { @@ -599,11 +587,7 @@ function deviceFactory( return; } - device.connection?.sendPacket( - toBinary(Protobuf.Admin.AdminMessageSchema, message), - Protobuf.Portnums.PortNum.ADMIN_APP, - "self", - ); + void meshRegistry.active.peek()?.sendAdmin(message.payloadVariant); }, addClientNotification: ( diff --git a/apps/web/src/core/subscriptions.ts b/apps/web/src/core/subscriptions.ts index 02ef8c434..0a4637e19 100644 --- a/apps/web/src/core/subscriptions.ts +++ b/apps/web/src/core/subscriptions.ts @@ -1,116 +1,69 @@ import { useNewNodeNum } from "@core/hooks/useNewNodeNum"; +import type { MeshSession } from "@core/kmp/session.ts"; import { type Device } from "@core/stores"; -import type { MeshDevice } from "@meshtastic/sdk"; import { Protobuf } from "@core/protobuf.ts"; /** - * Wires up the legacy MeshDevice event stream into the web's Zustand stores. - * - * Note: the SDK now owns chat persistence (via SqlocalMessageRepository) and - * the entire NodesClient surface — node info, user, position, lastHeard / - * snr, favourite / ignored flags, and PKI-error tracking. This handler no - * longer mirrors any of that into the legacy stores; what remains is - * device-store-only state (waypoints, traceroutes, neighbour info, dialog - * open triggers, unread counts). + * Feeds a session's events into the web's device store: what the SDK and + * the session don't keep themselves (waypoints, traceroutes, neighbour + * info, dialog triggers, the config mirror the settings forms read). */ -export const subscribeAll = (device: Device, connection: MeshDevice) => { - connection.events.onDeviceMetadataPacket.subscribe((metadataPacket) => { - device.addMetadata(metadataPacket.from, metadataPacket.data); - }); - - connection.events.onRoutingPacket.subscribe((routingPacket) => { - switch (routingPacket.data.variant.case) { - case "errorReason": { - if ( - routingPacket.data.variant.value === Protobuf.Mesh.Routing_Error.NONE - ) { +export const subscribeAll = ( + device: Device, + session: MeshSession, +): (() => void) => { + const { events } = session; + const unsubscribes = [ + events.onDeviceMetadataPacket.subscribe(({ from, data }) => { + device.addMetadata(from, data); + }), + events.onRoutingPacket.subscribe((packet) => { + if (packet.data.variant.case !== "errorReason") return; + switch (packet.data.variant.value) { + case Protobuf.Mesh.Routing_Error.NONE: return; - } - console.info(`Routing Error: ${routingPacket.data.variant.value}`); - break; - } - case "routeReply": { - console.info(`Route Reply: ${routingPacket.data.variant.value}`); - break; - } - case "routeRequest": { - console.info(`Route Request: ${routingPacket.data.variant.value}`); - break; - } - } - }); - - connection.events.onDeviceStatus.subscribe((status) => { - device.setStatus(status); - }); - - connection.events.onWaypointPacket.subscribe((waypoint) => { - const { data, channel, from, rxTime } = waypoint; - device.addWaypoint(data, channel, from, rxTime); - }); - - connection.events.onMyNodeInfo.subscribe((nodeInfo) => { - useNewNodeNum(device.id, nodeInfo); - }); - - // onUserPacket / onPositionPacket / onNodeInfoPacket and device-metrics - // telemetry (battery / channel utilisation / voltage) are folded into nodes by - // the SDK NodesClient (see packages/sdk/src/features/nodes/NodesClient.ts). - - connection.events.onChannelPacket.subscribe((channel) => { - device.addChannel(channel); - }); - connection.events.onConfigPacket.subscribe((config) => { - device.setConfig(config); - }); - connection.events.onModuleConfigPacket.subscribe((moduleConfig) => { - device.setModuleConfig(moduleConfig); - }); - - // Inbound message handling (persistence, unread counts) lives entirely on - // the SDK ChatClient now — see ChatClient + chat.unread. - - connection.events.onTraceRoutePacket.subscribe((traceRoutePacket) => { - device.addTraceRoute({ - ...traceRoutePacket, - }); - }); - - connection.events.onPendingSettingsChange.subscribe((state) => { - device.setPendingSettingsChanges(state); - }); - - // onMeshPacket → lastHeard / snr per-node updates are handled by the SDK - // NodesClient. - - connection.events.onClientNotificationPacket.subscribe( - (clientNotificationPacket) => { - device.addClientNotification(clientNotificationPacket); - device.setDialogOpen("clientNotification", true); - }, - ); - - connection.events.onNeighborInfoPacket.subscribe((neighborInfo) => { - device.addNeighborInfo(neighborInfo.from, neighborInfo.data); - }); - - connection.events.onRoutingPacket.subscribe((routingPacket) => { - if (routingPacket.data.variant.case === "errorReason") { - switch (routingPacket.data.variant.value) { - case Protobuf.Mesh.Routing_Error.MAX_RETRANSMIT: - console.error(`Routing Error: ${routingPacket.data.variant.value}`); - break; case Protobuf.Mesh.Routing_Error.NO_CHANNEL: case Protobuf.Mesh.Routing_Error.PKI_UNKNOWN_PUBKEY: - console.error(`Routing Error: ${routingPacket.data.variant.value}`); - // Per-node error tracking lives on the SDK NodesClient - // (client.nodes.errors); the dialog open trigger stays here so the - // legacy device-store-driven dialog manager keeps working. + console.error(`Routing Error: ${packet.data.variant.value}`); device.setDialogOpen("refreshKeys", true); - break; + return; default: - break; + console.info(`Routing Error: ${packet.data.variant.value}`); } - } - }); + }), + events.onDeviceStatus.subscribe((status) => { + device.setStatus(status); + }), + events.onWaypointPacket.subscribe(({ data, channel, from, rxTime }) => { + device.addWaypoint(data, channel, from, rxTime); + }), + events.onMyNodeInfo.subscribe((info) => { + useNewNodeNum(device.id, info); + }), + events.onChannelPacket.subscribe((channel) => { + device.addChannel(channel); + }), + events.onConfigPacket.subscribe((config) => { + device.setConfig(config); + }), + events.onModuleConfigPacket.subscribe((moduleConfig) => { + device.setModuleConfig(moduleConfig); + }), + events.onTraceRoutePacket.subscribe((packet) => { + device.addTraceRoute(packet); + }), + events.onPendingSettingsChange.subscribe((pending) => { + device.setPendingSettingsChanges(pending); + }), + events.onClientNotificationPacket.subscribe((notification) => { + device.addClientNotification(notification); + device.setDialogOpen("clientNotification", true); + }), + events.onNeighborInfoPacket.subscribe((packet) => { + device.addNeighborInfo(packet.from, packet.data); + }), + ]; + return () => { + for (const off of unsubscribes) off(); + }; }; diff --git a/apps/web/src/core/utils/beaconJoin.test.ts b/apps/web/src/core/utils/beaconJoin.test.ts index 1f901b918..2e35a3fe6 100644 --- a/apps/web/src/core/utils/beaconJoin.test.ts +++ b/apps/web/src/core/utils/beaconJoin.test.ts @@ -1,5 +1,5 @@ import { create, type MessageInitShape } from "@bufbuild/protobuf"; -import type { Channel, MeshBeaconOffer } from "@meshtastic/sdk"; +import type { Channel, MeshBeaconOffer } from "@core/kmp/channels.ts"; import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { diff --git a/apps/web/src/core/utils/beaconJoin.ts b/apps/web/src/core/utils/beaconJoin.ts index c147a06bb..949522c77 100644 --- a/apps/web/src/core/utils/beaconJoin.ts +++ b/apps/web/src/core/utils/beaconJoin.ts @@ -1,13 +1,12 @@ import { create, toBinary } from "@bufbuild/protobuf"; import { channelSetToUrl } from "@core/utils/channelUrl.ts"; +import type { Channel, MeshBeaconOffer } from "@core/kmp/channels.ts"; import { type BeaconJoinOption, beaconJoinChannelSet, beaconJoinOption, - type Channel, isBeaconAlreadyJoined, - type MeshBeaconOffer, -} from "@meshtastic/sdk"; +} from "@core/utils/meshBeacon.ts"; import { Protobuf } from "@core/protobuf.ts"; type ChannelSettings = Protobuf.Channel.ChannelSettings; diff --git a/apps/web/src/core/utils/cleanNodes.test.ts b/apps/web/src/core/utils/cleanNodes.test.ts index 1467f0293..1fc1a6add 100644 --- a/apps/web/src/core/utils/cleanNodes.test.ts +++ b/apps/web/src/core/utils/cleanNodes.test.ts @@ -1,5 +1,5 @@ import { create } from "@bufbuild/protobuf"; -import type { Node } from "@meshtastic/sdk"; +import type { Node } from "@core/storage/types.ts"; import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { minDays, nodesToClean } from "./cleanNodes.ts"; diff --git a/apps/web/src/core/utils/cleanNodes.ts b/apps/web/src/core/utils/cleanNodes.ts index cf62c35e4..406608fe9 100644 --- a/apps/web/src/core/utils/cleanNodes.ts +++ b/apps/web/src/core/utils/cleanNodes.ts @@ -1,4 +1,4 @@ -import type { Node } from "@meshtastic/sdk"; +import type { Node } from "@core/storage/types.ts"; export const MIN_DAYS_KNOWN = 7; export const MIN_DAYS_UNKNOWN = 0; diff --git a/apps/web/src/core/utils/meshBeacon.test.ts b/apps/web/src/core/utils/meshBeacon.test.ts new file mode 100644 index 000000000..e023d4460 --- /dev/null +++ b/apps/web/src/core/utils/meshBeacon.test.ts @@ -0,0 +1,118 @@ +import { create } from "@bufbuild/protobuf"; +import { Protobuf } from "@core/protobuf.ts"; +import { describe, expect, it } from "vitest"; +import { + beaconJoinChannelSet, + beaconJoinOption, + isBeaconAlreadyJoined, +} from "./meshBeacon.ts"; + +const Preset = Protobuf.Config.Config_LoRaConfig_ModemPreset; +const Region = Protobuf.Config.Config_LoRaConfig_RegionCode; + +const lora = ( + init: Omit, "$typeName"> = {}, +) => + create(Protobuf.Config.Config_LoRaConfigSchema, { + usePreset: true, + modemPreset: Preset.LONG_FAST, + region: Region.US, + ...init, + }); + +const channel = (name: string, psk = new Uint8Array([1])) => + create(Protobuf.Channel.ChannelSettingsSchema, { name, psk }); + +const beacon = ( + init: Omit, "$typeName"> = {}, +) => + create(Protobuf.MeshBeacon.MeshBeaconSchema, { + message: "join", + offerChannel: channel("Hikers", new Uint8Array([7, 7])), + ...init, + }); + +describe("beaconJoinOption", () => { + it("is none without an offered channel", () => { + expect( + beaconJoinOption(beacon({ offerChannel: undefined }), lora(), []), + ).toBe("none"); + }); + + it("adds when the offered channel hashes like the primary", () => { + const radio = [channel("Hikers")]; + expect(beaconJoinOption(beacon(), lora(), radio)).toBe("add"); + }); + + it("treats an empty name as the preset name on both sides", () => { + const offer = beacon({ offerChannel: channel("") }); + expect(beaconJoinOption(offer, lora(), [channel("")])).toBe("add"); + expect(beaconJoinOption(offer, lora(), [channel("LongFast")])).toBe("add"); + }); + + it("switches when the preset or region differ", () => { + const radio = [channel("Hikers")]; + expect( + beaconJoinOption( + beacon({ offerPreset: Preset.SHORT_FAST }), + lora(), + radio, + ), + ).toBe("switch"); + expect( + beaconJoinOption(beacon({ offerRegion: Region.EU_868 }), lora(), radio), + ).toBe("switch"); + }); + + it("switches when the radio is pinned to a slot", () => { + expect( + beaconJoinOption(beacon(), lora({ channelNum: 5 }), [channel("Hikers")]), + ).toBe("switch"); + }); + + it("switches when the names differ, since the slots may", () => { + expect(beaconJoinOption(beacon(), lora(), [channel("LongFast")])).toBe( + "switch", + ); + }); +}); + +describe("beaconJoinChannelSet", () => { + it("turns position sharing off on the offered channel", () => { + const offered = channel("Hikers"); + offered.moduleSettings = create(Protobuf.Channel.ModuleSettingsSchema, { + positionPrecision: 32, + }); + const set = beaconJoinChannelSet( + beacon({ offerChannel: offered }), + "add", + lora(), + ); + expect(set?.settings[0]?.moduleSettings?.positionPrecision).toBe(0); + expect(set?.loraConfig).toBeUndefined(); + }); + + it("switches with a fresh LoRa config carrying the offered preset", () => { + const set = beaconJoinChannelSet( + beacon({ offerPreset: Preset.MEDIUM_FAST }), + "switch", + lora({ channelNum: 9, overrideFrequency: 915 }), + ); + expect(set?.loraConfig?.modemPreset).toBe(Preset.MEDIUM_FAST); + expect(set?.loraConfig?.region).toBe(Region.US); + expect(set?.loraConfig?.channelNum).toBe(0); + expect(set?.loraConfig?.overrideFrequency).toBe(0); + }); +}); + +describe("isBeaconAlreadyJoined", () => { + it("matches a channel with the same name and key", () => { + const radio = [channel(""), channel("Hikers", new Uint8Array([7, 7]))]; + expect(isBeaconAlreadyJoined(beacon(), lora(), radio)).toBe(true); + }); + + it("does not match the same name with a different key", () => { + const radio = [channel(""), channel("Hikers", new Uint8Array([8]))]; + expect(isBeaconAlreadyJoined(beacon(), lora(), radio)).toBe(false); + }); +}); diff --git a/apps/web/src/core/utils/meshBeacon.ts b/apps/web/src/core/utils/meshBeacon.ts new file mode 100644 index 000000000..f94db9694 --- /dev/null +++ b/apps/web/src/core/utils/meshBeacon.ts @@ -0,0 +1,138 @@ +import { create } from "@bufbuild/protobuf"; +import { Protobuf } from "@core/protobuf.ts"; + +type LoRaConfig = Protobuf.Config.Config_LoRaConfig; +type ChannelSettings = Protobuf.Channel.ChannelSettings; +type MeshBeacon = Protobuf.MeshBeacon.MeshBeacon; + +/** + * How an offer can be joined. "add" puts the channel in a free secondary + * slot with no reboot; "switch" retunes the radio onto the offered mesh and + * reboots it; "none" means the beacon offers no channel. + */ +export type BeaconJoinOption = "add" | "switch" | "none"; + +/** + * The name firmware hashes for the frequency slot: an empty channel name + * stands for the modem preset's name. + */ +function effectiveName( + settings: ChannelSettings | undefined, + lora: LoRaConfig, +) { + if (settings?.name) return settings.name; + const preset = + Protobuf.Config.Config_LoRaConfig_ModemPreset[lora.modemPreset]; + return (preset ?? "") + .toLowerCase() + .replace(/(^|_)([a-z])/g, (_, __, c: string) => c.toUpperCase()); +} + +const sameBytes = (a: Uint8Array, b: Uint8Array) => + a.length === b.length && a.every((v, i) => v === b[i]); + +/** A blank secondary slot left behind by a removed channel. */ +const isPlaceholder = (s: ChannelSettings) => !s.name && s.psk.length === 0; + +/** + * True when the offered channel is already on the radio: same effective name + * and key under the preset the offer would run on. + */ +export function isBeaconAlreadyJoined( + beacon: MeshBeacon, + lora: LoRaConfig | undefined, + channels: ReadonlyArray, +): boolean { + const offer = beacon.offerChannel; + if (!offer || !lora || channels.length === 0) return false; + const offerLora = create(Protobuf.Config.Config_LoRaConfigSchema, { + ...lora, + usePreset: true, + modemPreset: beacon.offerPreset ?? lora.modemPreset, + }); + const offerName = effectiveName(offer, offerLora); + return channels.some( + (s, index) => + (index === 0 || !isPlaceholder(s)) && + effectiveName(s, lora) === offerName && + sameBytes(s.psk, offer.psk), + ); +} + +/** + * Decide how to join, after the Android app's beaconJoinOption. Secondary + * channels ride the primary's frequency slot, so adding only works when the + * offered mesh is on the same slot under the same preset and region. + * + * Android computes both slots from the regional band plan. The web client + * has no band plan, so it only reports "add" when the slots are certainly + * equal: the offer advertises the radio's own slot, or both channels hash + * the same effective name. Anything else is a "switch", which costs a reboot + * but always works. + */ +export function beaconJoinOption( + beacon: MeshBeacon, + lora: LoRaConfig | undefined, + channels: ReadonlyArray, +): BeaconJoinOption { + const offer = beacon.offerChannel; + if (!offer) return "none"; + if (!lora) return "switch"; + const presetMatches = + beacon.offerPreset === undefined || + (lora.usePreset && beacon.offerPreset === lora.modemPreset); + const regionMatches = + beacon.offerRegion === Protobuf.Config.Config_LoRaConfig_RegionCode.UNSET || + beacon.offerRegion === lora.region; + if (!presetMatches || !regionMatches) return "switch"; + + const advertised = beacon.offerFrequencySlot; + if (advertised !== undefined && advertised > 0) { + return lora.channelNum === advertised ? "add" : "switch"; + } + // A radio pinned to a slot can't be compared with a hashed one. + if (lora.channelNum !== 0) return "switch"; + return effectiveName(channels[0], lora) === effectiveName(offer, lora) + ? "add" + : "switch"; +} + +/** + * The ChannelSet to hand the channel import flow. "add" carries only the + * channel. "switch" also carries a fresh LoRa config (not a copy of the + * current one, so no stale frequency or slot pin survives) with the offered + * preset and region. Position sharing is always turned off on the offered + * channel, so joining a stranger's mesh never shares our location. + */ +export function beaconJoinChannelSet( + beacon: MeshBeacon, + option: BeaconJoinOption, + lora: LoRaConfig | undefined, +): Protobuf.AppOnly.ChannelSet | undefined { + const offer = beacon.offerChannel; + if (!offer || option === "none") return undefined; + const channel = create(Protobuf.Channel.ChannelSettingsSchema, { + ...offer, + moduleSettings: create(Protobuf.Channel.ModuleSettingsSchema, { + isMuted: offer.moduleSettings?.isMuted ?? false, + positionPrecision: 0, + }), + }); + if (option === "add") { + return create(Protobuf.AppOnly.ChannelSetSchema, { settings: [channel] }); + } + const Region = Protobuf.Config.Config_LoRaConfig_RegionCode; + return create(Protobuf.AppOnly.ChannelSetSchema, { + settings: [channel], + loraConfig: create(Protobuf.Config.Config_LoRaConfigSchema, { + usePreset: true, + modemPreset: beacon.offerPreset ?? lora?.modemPreset, + // A full LoRaConfig replacement with region UNSET would stop transmit. + region: + beacon.offerRegion !== Region.UNSET ? beacon.offerRegion : lora?.region, + hopLimit: 3, + txEnabled: true, + channelNum: beacon.offerFrequencySlot ?? 0, + }), + }); +} diff --git a/apps/web/src/core/utils/telemetry.test.ts b/apps/web/src/core/utils/telemetry.test.ts index 3bdd22466..8e8cc81e7 100644 --- a/apps/web/src/core/utils/telemetry.test.ts +++ b/apps/web/src/core/utils/telemetry.test.ts @@ -1,5 +1,5 @@ import { create } from "@bufbuild/protobuf"; -import type { TelemetryReading } from "@meshtastic/sdk"; +import type { TelemetryReading } from "@core/storage/types.ts"; import { Protobuf } from "@core/protobuf.ts"; import { describe, expect, it } from "vitest"; import { diff --git a/apps/web/src/core/utils/telemetry.ts b/apps/web/src/core/utils/telemetry.ts index d3705875a..2990eb29f 100644 --- a/apps/web/src/core/utils/telemetry.ts +++ b/apps/web/src/core/utils/telemetry.ts @@ -1,4 +1,4 @@ -import type { TelemetryKind, TelemetryReading } from "@meshtastic/sdk"; +import type { TelemetryKind, TelemetryReading } from "@core/storage/types.ts"; /** * Pure helpers that turn SDK telemetry readings into display rows for the diff --git a/apps/web/src/index.tsx b/apps/web/src/index.tsx index e296ab40f..fba49ab48 100644 --- a/apps/web/src/index.tsx +++ b/apps/web/src/index.tsx @@ -9,9 +9,9 @@ import { Suspense } from "react"; import { createRoot } from "react-dom/client"; import "./i18n-config.ts"; import { router } from "@app/routes.tsx"; -import { meshRegistry } from "@core/meshRegistry.ts"; +import { meshRegistry } from "@core/kmp/registry.ts"; import { useAppStore } from "@core/stores"; -import { MeshRegistryProvider } from "@meshtastic/sdk-react"; +import { MeshRegistryProvider } from "@core/kmp/hooks"; import { type createRouter, RouterProvider } from "@tanstack/react-router"; import { useTranslation } from "react-i18next"; diff --git a/apps/web/src/pages/Connections/useConnections.devices.test.ts b/apps/web/src/pages/Connections/useConnections.devices.test.ts index 0ea77cc2a..10501992c 100644 --- a/apps/web/src/pages/Connections/useConnections.devices.test.ts +++ b/apps/web/src/pages/Connections/useConnections.devices.test.ts @@ -93,7 +93,7 @@ describe("useConnections over the Kotlin SDK (Serial and Bluetooth)", () => { expect(ok).toBe(true); expect(requestPort).not.toHaveBeenCalled(); expect(kmp.serialTargets).toEqual([{ port: undefined, ...ids }]); - expect(saved(conn.id)?.status).toBe("configuring"); + expect(saved(conn.id)?.status).toBe("configured"); await act(() => result.current.disconnect(conn.id)); }); @@ -241,7 +241,7 @@ describe("useConnections over the Kotlin SDK (Serial and Bluetooth)", () => { act(() => client.setState(state("connected"))); expect(saved(conn.id)).toMatchObject({ - status: "configuring", + status: "configured", reconnect: undefined, }); await act(() => result.current.disconnect(conn.id)); diff --git a/apps/web/src/pages/Connections/useConnections.kmp.test.ts b/apps/web/src/pages/Connections/useConnections.kmp.test.ts index 340826ad2..abf52962f 100644 --- a/apps/web/src/pages/Connections/useConnections.kmp.test.ts +++ b/apps/web/src/pages/Connections/useConnections.kmp.test.ts @@ -1,6 +1,7 @@ -import { fromBinary } from "@bufbuild/protobuf"; +import { create, toBinary } from "@bufbuild/protobuf"; import { FakeKmpClient, state } from "@core/kmp/fakeClient.ts"; import type { Connection } from "@app/core/stores/deviceStore/types"; +import { meshRegistry } from "@core/kmp/registry.ts"; import { useDeviceStore } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; import { act, renderHook } from "@testing-library/react"; @@ -38,6 +39,17 @@ vi.mock("@core/kmp/client.ts", async () => { const saved = (id: number): Connection | undefined => useDeviceStore.getState().savedConnections.find((c) => c.id === id); +const myInfo = (myNodeNum: number): Uint8Array => + toBinary( + Protobuf.Mesh.FromRadioSchema, + create(Protobuf.Mesh.FromRadioSchema, { + payloadVariant: { + case: "myInfo", + value: create(Protobuf.Mesh.MyNodeInfoSchema, { myNodeNum }), + }, + }), + ); + function named(name: string): Error { const error = new Error(name); error.name = name; @@ -50,7 +62,7 @@ describe("useConnections over the Kotlin SDK (HTTP)", () => { kmp.connectError = undefined; }); - it("connects through the SDK and asks the radio for its config", async () => { + it("connects through the SDK and reads the handshake it ran", async () => { const { result } = renderHook(() => useConnections()); const conn = result.current.addConnection({ type: "http", @@ -60,17 +72,12 @@ describe("useConnections over the Kotlin SDK (HTTP)", () => { const ok = await act(() => result.current.connect(conn.id)); expect(ok).toBe(true); - expect(saved(conn.id)?.status).toBe("configuring"); + expect(saved(conn.id)?.status).toBe("configured"); const client = kmp.client; if (!client) throw new Error("no client created"); - await vi.waitFor(() => { - const sent = client.sent.map((bytes) => - fromBinary(Protobuf.Mesh.ToRadioSchema, bytes), - ); - expect(sent.some((m) => m.payloadVariant.case === "wantConfigId")).toBe( - true, - ); - }); + expect(meshRegistry.get(conn.id)?.kmp).toBe(client); + act(() => client.emitFrame(myInfo(0x0a0b0c0d))); + expect(saved(conn.id)?.nodeNum).toBe(0x0a0b0c0d); await act(() => result.current.disconnect(conn.id)); expect(client.disconnects).toHaveLength(1); @@ -96,7 +103,7 @@ describe("useConnections over the Kotlin SDK (HTTP)", () => { act(() => client.setState(state("connected"))); expect(saved(conn.id)).toMatchObject({ - status: "configuring", + status: "configured", reconnect: undefined, }); diff --git a/apps/web/src/pages/Connections/useConnections.test.ts b/apps/web/src/pages/Connections/useConnections.test.ts index 8a72493a9..dc560832d 100644 --- a/apps/web/src/pages/Connections/useConnections.test.ts +++ b/apps/web/src/pages/Connections/useConnections.test.ts @@ -1,9 +1,10 @@ -import { create } from "@bufbuild/protobuf"; -import { UNKNOWN_NODE_SCOPE } from "@app/core/connections/sdkClient.ts"; +import { UNKNOWN_NODE_SCOPE } from "@app/core/connections/repositories.ts"; import type { Connection } from "@app/core/stores/deviceStore/types"; -import { useDeviceStore } from "@core/stores"; -import type { MeshDevice } from "@meshtastic/sdk"; +import { create, toBinary } from "@bufbuild/protobuf"; +import { FakeKmpClient } from "@core/kmp/fakeClient.ts"; +import { meshRegistry } from "@core/kmp/registry.ts"; import { Protobuf } from "@core/protobuf.ts"; +import { useDeviceStore } from "@core/stores"; import { act, renderHook } from "@testing-library/react"; import { afterEach, describe, expect, it, vi } from "vitest"; import { useConnections } from "./useConnections.ts"; @@ -25,56 +26,38 @@ vi.mock("@core/kmp/client.ts", async () => { return { createSerialClient: async () => new FakeKmpClient() }; }); -// The sqlocal repositories, replaced by the SDK's in-memory ones that record -// the scopes they are given. Called with `new`; the returned object is the -// instance. -function recording(kind: string, make: () => T) { +// The sqlocal repositories, replaced by empty ones that record the scopes +// they are given. Called with `new`; the returned object is the instance. +function recording(kind: string) { return function Recording(_db: unknown, options: { deviceId: number }) { scopes.opened.push([kind, options.deviceId]); - return Object.assign(make(), { + return { setScope(scope: number): void { scopes.switched.push([kind, scope]); }, - }); + loadAll: async () => [], + loadRecent: async () => [], + load: async () => "", + append: async () => {}, + upsert: async () => {}, + upsertBatch: async () => {}, + prune: async () => {}, + }; }; } -vi.mock("@core/storage/messages.ts", async () => { - const sdk = await import("@meshtastic/sdk"); - return { - SqlocalMessageRepository: recording( - "messages", - () => new sdk.InMemoryMessageRepository(), - ), - }; -}); -vi.mock("@core/storage/drafts.ts", async () => { - const sdk = await import("@meshtastic/sdk"); - return { - SqlocalDraftRepository: recording( - "drafts", - () => new sdk.InMemoryDraftRepository(), - ), - }; -}); -vi.mock("@core/storage/nodes.ts", async () => { - const sdk = await import("@meshtastic/sdk"); - return { - SqlocalNodesRepository: recording( - "nodes", - () => new sdk.InMemoryNodesRepository(), - ), - }; -}); -vi.mock("@core/storage/telemetry.ts", async () => { - const sdk = await import("@meshtastic/sdk"); - return { - SqlocalTelemetryRepository: recording( - "telemetry", - () => new sdk.InMemoryTelemetryRepository(), - ), - }; -}); +vi.mock("@core/storage/messages.ts", () => ({ + SqlocalMessageRepository: recording("messages"), +})); +vi.mock("@core/storage/drafts.ts", () => ({ + SqlocalDraftRepository: recording("drafts"), +})); +vi.mock("@core/storage/nodes.ts", () => ({ + SqlocalNodesRepository: recording("nodes"), +})); +vi.mock("@core/storage/telemetry.ts", () => ({ + SqlocalTelemetryRepository: recording("telemetry"), +})); const NODE = 0x0a0b0c0d; const KINDS = ["messages", "drafts", "nodes", "telemetry"]; @@ -82,15 +65,23 @@ const KINDS = ["messages", "drafts", "nodes", "telemetry"]; const saved = (id: number): Connection | undefined => useDeviceStore.getState().savedConnections.find((c) => c.id === id); -function meshDeviceFor(id: number): MeshDevice { - const meshDeviceId = saved(id)?.meshDeviceId; - const device = meshDeviceId - ? useDeviceStore.getState().getDevice(meshDeviceId) - : undefined; - if (!device?.connection) throw new Error("no MeshDevice for connection"); - return device.connection; +function kmpFor(id: number): FakeKmpClient { + const kmp = meshRegistry.get(id)?.kmp; + if (!(kmp instanceof FakeKmpClient)) throw new Error("no session"); + return kmp; } +const myInfo = (myNodeNum: number): Uint8Array => + toBinary( + Protobuf.Mesh.FromRadioSchema, + create(Protobuf.Mesh.FromRadioSchema, { + payloadVariant: { + case: "myInfo", + value: create(Protobuf.Mesh.MyNodeInfoSchema, { myNodeNum }), + }, + }), + ); + describe("useConnections storage scope", () => { afterEach(() => { scopes.opened.length = 0; @@ -110,13 +101,9 @@ describe("useConnections storage scope", () => { KINDS.map((kind) => [kind, UNKNOWN_NODE_SCOPE]), ); - act(() => { - meshDeviceFor(conn.id).events.onMyNodeInfo.dispatch( - create(Protobuf.Mesh.MyNodeInfoSchema, { myNodeNum: NODE }), - ); - }); + act(() => kmpFor(conn.id).emitFrame(myInfo(NODE))); expect(saved(conn.id)?.nodeNum).toBe(NODE); - // The SDK moves this session to the node straight away. + // The session moves to the node's history straight away. expect(scopes.switched).toEqual(KINDS.map((kind) => [kind, NODE])); await act(() => result.current.disconnect(conn.id)); @@ -127,11 +114,7 @@ describe("useConnections storage scope", () => { expect(scopes.opened).toEqual(KINDS.map((kind) => [kind, NODE])); // my_info for the same node changes nothing. - act(() => { - meshDeviceFor(conn.id).events.onMyNodeInfo.dispatch( - create(Protobuf.Mesh.MyNodeInfoSchema, { myNodeNum: NODE }), - ); - }); + act(() => kmpFor(conn.id).emitFrame(myInfo(NODE))); expect(scopes.switched).toEqual([]); expect(saved(conn.id)?.nodeNum).toBe(NODE); diff --git a/apps/web/src/pages/Connections/useConnections.ts b/apps/web/src/pages/Connections/useConnections.ts index acd2d6992..669f8fe5e 100644 --- a/apps/web/src/pages/Connections/useConnections.ts +++ b/apps/web/src/pages/Connections/useConnections.ts @@ -1,4 +1,3 @@ -import { buildMeshDevice } from "@app/core/connections/sdkClient.ts"; import { type BluetoothConnection, type ConnectionHandle, @@ -9,6 +8,18 @@ import { probeConnection, type SerialConnection, } from "@app/core/connections/browserDevices.ts"; +import { + openRepositories, + UNKNOWN_NODE_SCOPE, +} from "@app/core/connections/repositories.ts"; +import type { + Connection, + ConnectionId, + ConnectionStatus, + NewConnection, +} from "@app/core/stores/deviceStore/types"; +import { createConnectionFromInput } from "@app/pages/Connections/utils"; +import { toast } from "@core/hooks/useToast.ts"; import { type BluetoothTarget, createBluetoothClient, @@ -23,40 +34,25 @@ import { reconnectAttempt, toConnectionStatus, } from "@core/kmp/connectionState.ts"; -import { kmpTransport } from "@core/kmp/transport.ts"; -import { toast } from "@core/hooks/useToast.ts"; +import { meshRegistry } from "@core/kmp/registry.ts"; +import { MeshSession } from "@core/kmp/session.ts"; import { createLogger } from "@core/log.ts"; -import { MIN_FIRMWARE_VERSION } from "@core/utils/firmware.ts"; -import { - DeviceStatusEnum, - FirmwareTooOldError, - type Transport, -} from "@meshtastic/sdk"; -import { t } from "i18next"; - -const log = createLogger("useConnections"); -import type { - Connection, - ConnectionId, - ConnectionStatus, - NewConnection, -} from "@app/core/stores/deviceStore/types"; -import { createConnectionFromInput } from "@app/pages/Connections/utils"; -import { meshRegistry } from "@core/meshRegistry.ts"; import { useAppStore, useDeviceStore } from "@core/stores"; import { subscribeAll } from "@core/subscriptions.ts"; +import { MIN_FIRMWARE_VERSION } from "@core/utils/firmware.ts"; import { randId } from "@core/utils/randId.ts"; +import { t } from "i18next"; import { useCallback } from "react"; +const log = createLogger("useConnections"); + // Per-connection out-of-band handles tracked outside Zustand: // - heldSerialPorts / heldBluetoothDevices: the port or device the user // picked, so later connects reuse it without prompting. -// - configSubscriptions: handshake status / reboot unsubscribers. +// - sessionTeardowns: the session's subscriptions, released on teardown. const heldSerialPorts = new Map(); const heldBluetoothDevices = new Map(); -const configSubscriptions = new Map void>(); -// Kotlin SDK connection-state subscriptions for connections it owns. -const kmpSubscriptions = new Map void>(); +const sessionTeardowns = new Map void>(); /** * What the SDK opens for a serial connection. Automatic connects pass only @@ -122,6 +118,9 @@ async function bluetoothTarget( return { device, deviceId: device.id }; } +const savedConnection = (id: ConnectionId): Connection | undefined => + useDeviceStore.getState().savedConnections.find((c) => c.id === id); + export function useConnections() { const connections = useDeviceStore((s) => s.savedConnections); const addSavedConnection = useDeviceStore((s) => s.addSavedConnection); @@ -151,28 +150,17 @@ export function useConnections() { [updateSavedConnection], ); - const teardown = useCallback(async (id: ConnectionId, conn?: Connection) => { + const teardown = useCallback(async (id: ConnectionId) => { log.debug("teardown: enter", { id }); - kmpSubscriptions.get(id)?.(); - kmpSubscriptions.delete(id); - configSubscriptions.get(id)?.(); - configSubscriptions.delete(id); - - if (conn?.meshDeviceId) { - const device = useDeviceStore.getState().getDevice(conn.meshDeviceId); - try { - // Await the underlying transport's close so the port is fully - // released before the user clicks reconnect — otherwise port.open() - // can race the close and throw "port already open". - await device?.connection?.disconnect(); - log.debug("teardown: transport disconnect awaited"); - } catch (e) { - const err = e as Error; - log.warn("teardown: transport disconnect threw", { - name: err?.name, - message: err?.message, - }); - } + sessionTeardowns.get(id)?.(); + sessionTeardowns.delete(id); + try { + await meshRegistry.get(id)?.disconnect(); + } catch (e) { + log.warn("teardown: disconnect threw", { + name: e instanceof Error ? e.name : undefined, + message: e instanceof Error ? e.message : String(e), + }); } log.debug("teardown: done", { id }); }, []); @@ -180,19 +168,17 @@ export function useConnections() { const removeConnection = useCallback( async (id: ConnectionId) => { const conn = connections.find((c) => c.id === id); - await teardown(id, conn); + await teardown(id); heldSerialPorts.delete(id); heldBluetoothDevices.delete(id); if (conn?.meshDeviceId) { try { useDeviceStore.getState().removeDevice(conn.meshDeviceId); } catch (e) { - const err = e as Error; log.error("removeConnection: removeDevice threw", { id, meshDeviceId: conn.meshDeviceId, - name: err?.name, - message: err?.message, + message: e instanceof Error ? e.message : String(e), }); } } @@ -211,42 +197,24 @@ export function useConnections() { [connections, updateSavedConnection], ); - const setupMeshDevice = useCallback( - async ( - id: ConnectionId, - transport: Transport, - { sdkOwnsConnection = false }: { sdkOwnsConnection?: boolean } = {}, - ): Promise => { - // Reuse existing meshDeviceId if the device entry still exists; otherwise mint a new one. - const conn = connections.find((c) => c.id === id); + /** + * Connects through the Kotlin SDK, which owns the transport, the + * handshake and reconnects. A session over the client decodes what the + * SDK delivers into the app's stores, with history opened for the node + * this connection reached last time. + */ + const connectThroughKmp = useCallback( + async (id: ConnectionId, makeClient: () => Promise) => { + const client = await makeClient(); + const conn = savedConnection(id); let deviceId = conn?.meshDeviceId; if (deviceId && !useDeviceStore.getState().getDevice(deviceId)) { deviceId = undefined; } deviceId = deviceId ?? randId(); - const device = addDevice(deviceId); - // Flip status to "configuring" up front. buildMeshDevice awaits the - // OPFS DB open which can take a beat (or stall under multi-tab - // contention); we don't want the UI looking stuck at "connecting" - // while persistence is spinning up. - updateStatus(id, "configuring"); - log.debug("setupMeshDevice: building MeshDevice", { id, deviceId }); - - // Read the node number from the live store: the `connections` closure - // can predate the last handshake's update. - const nodeNum = useDeviceStore - .getState() - .savedConnections.find((c) => c.id === id)?.nodeNum; - const { meshDevice, persistent } = await buildMeshDevice( - id, - deviceId, - transport, - nodeNum, - { heartbeat: !sdkOwnsConnection }, - ); - log.debug("setupMeshDevice: MeshDevice built", { id, persistent }); + const { options, persistent } = await openRepositories(conn?.nodeNum); if (!persistent) { toast({ title: t("toasts.storageUnavailable", { ns: "connections" }), @@ -255,152 +223,30 @@ export function useConnections() { }), }); } + let scope = conn?.nodeNum ?? UNKNOWN_NODE_SCOPE; + const session = new MeshSession(client, options); - // Replace any client left from an earlier attempt, so the app reads + // Replace any session left from an earlier attempt, so the app reads // this session's state rather than the dead one's. - if (meshRegistry.has(id)) meshRegistry.unregister(id); - meshRegistry.register(id, meshDevice.meshClient); + sessionTeardowns.get(id)?.(); + meshRegistry.get(id)?.close(); + meshRegistry.unregister(id); + meshRegistry.register(id, session); meshRegistry.setActive(id); // Created now so it sees the handshake's config, not on first render. - editorFor(meshDevice.meshClient); - + editorFor(session); setSelectedDevice(deviceId); - device.addConnection(meshDevice); - subscribeAll(device, meshDevice); - + const unsubscribeStore = subscribeAll(device, session); setActiveConnectionId(id); device.setConnectionId(id); - - // MeshClient flips device.status to DeviceConfigured once both - // handshake stages (config, then NodeDB) are done, and starts its own - // heartbeat. onConfigComplete also fires after the config stage, so it - // can't be used here. `markConfigured` is idempotent. - let configuredHandled = false; - const markConfigured = (source: string): void => { - if (configuredHandled) return; - configuredHandled = true; - log.info("connect transitioned to configured", { id, source }); - updateStatus(id, "configured"); - const client = meshDevice.meshClient; - if (client.device.firmwareSupport.value === "shouldUpdate") { - toast({ - title: t("toasts.firmwareOutdated", { ns: "connections" }), - description: t("toasts.firmwareOutdatedDescription", { - ns: "connections", - version: client.device.metadata.value?.firmwareVersion, - minimum: MIN_FIRMWARE_VERSION, - }), - }); - } - }; - - const unsubStatusSignal = meshDevice.meshClient.device.status.subscribe( - (s) => { - if (s === DeviceStatusEnum.DeviceConfigured) - markConfigured("device.status"); - // The Kotlin SDK reconnected the transport; the next handshake - // must be able to mark the connection configured again. - if (s === DeviceStatusEnum.DeviceReconnecting) - configuredHandled = false; - }, - ); - // Catch-up: signal subscribe doesn't fire for the current value, so - // check synchronously if the device is already past the gate. - if ( - meshDevice.meshClient.device.status.value === - DeviceStatusEnum.DeviceConfigured - ) { - markConfigured("initial-check"); - } - - // Reboot: firmware emits `rebooted` after a soft reset (config write, - // OTA, manual reboot). The SDK re-runs the handshake, but the - // saved-connection status is already "configured" — so the overlay - // would stay hidden. Flip status back to "configuring" and reset - // `configuredHandled` so the next DeviceConfigured re-marks. - const unsubRebooted = meshDevice.events.onRebooted.subscribe(() => { - log.info("device rebooted — re-entering configuring", { id }); - configuredHandled = false; - updateStatus(id, "configuring"); - }); - - // History is stored per radio. The SDK switches this session to the - // node my_info names; saving it on the connection lets the next connect - // open that node's history straight away. - const unsubMyNodeInfo = meshDevice.events.onMyNodeInfo.subscribe( - ({ myNodeNum }) => { - if (myNodeNum <= 0) return; - const saved = useDeviceStore - .getState() - .savedConnections.find((c) => c.id === id); - if (saved && saved.nodeNum !== myNodeNum) { - updateSavedConnection(id, { nodeNum: myNodeNum }); - } - }, - ); - - configSubscriptions.set(id, () => { - unsubStatusSignal(); - unsubRebooted(); - unsubMyNodeInfo(); - }); - - log.debug("setupMeshDevice: calling configure()", { id }); - meshDevice - .configure() - .then(() => { - log.debug("setupMeshDevice: configure() resolved", { id }); - }) - .catch((error) => { - const e = error as Error; - log.error("setupMeshDevice: configure() rejected", { - id, - name: e?.name, - message: e?.message, - }); - updateStatus( - id, - "error", - error instanceof FirmwareTooOldError - ? t("errors.firmwareTooOld", { - ns: "connections", - version: error.firmwareVersion, - minimum: MIN_FIRMWARE_VERSION, - }) - : (error?.message ?? String(error)), - ); - }); - updateSavedConnection(id, { meshDeviceId: deviceId }); - return deviceId; - }, - [ - connections, - addDevice, - setSelectedDevice, - setActiveConnectionId, - updateSavedConnection, - updateStatus, - ], - ); - /** - * Connects through the Kotlin SDK, which owns the transport, the - * handshake and reconnects. The existing MeshDevice is fed from the SDK's - * frames so the rest of the app is unchanged. - */ - const connectThroughKmp = useCallback( - async (id: ConnectionId, makeClient: () => Promise) => { - const client = await makeClient(); let reconnecting = false; - kmpSubscriptions.get(id)?.(); - kmpSubscriptions.set( - id, - client.onConnectionState((state) => { - const saved = useDeviceStore - .getState() - .savedConnections.find((c) => c.id === id); - if (!saved) return; + let firmwareChecked = false; + const unsubscribes = [ + unsubscribeStore, + session.events.onConnectionState.subscribe((state) => { + if (!savedConnection(id)) return; const reconnect = reconnectAttempt(state); if (reconnect) { reconnecting = true; @@ -413,21 +259,8 @@ export function useConnections() { }); return; } - if (!reconnecting) return; - if (state.kind === "connected") { - reconnecting = false; - log.info("kmp: reconnected, re-running the handshake", { id }); - updateSavedConnection(id, { - status: "configuring", - reconnect: undefined, - }); - const device = saved.meshDeviceId - ? useDeviceStore.getState().getDevice(saved.meshDeviceId) - : undefined; - device?.connection?.configure().catch((error: unknown) => { - updateSavedConnection(id, connectFailure(error)); - }); - } else if (state.kind === "disconnected") { + if (state.kind === "disconnected") { + if (!reconnecting) return; reconnecting = false; log.error("kmp: reconnect attempts exhausted", { id }); updateSavedConnection(id, { @@ -438,16 +271,56 @@ export function useConnections() { }), errorKind: "network", }); + return; + } + reconnecting = false; + updateSavedConnection(id, { + status: toConnectionStatus(state), + reconnect: undefined, + }); + if (state.kind === "connected") { + if (firmwareChecked) return; + firmwareChecked = true; + if (session.device.firmwareSupport.peek() === "shouldUpdate") { + toast({ + title: t("toasts.firmwareOutdated", { ns: "connections" }), + description: t("toasts.firmwareOutdatedDescription", { + ns: "connections", + version: session.device.metadata.peek()?.firmwareVersion, + minimum: MIN_FIRMWARE_VERSION, + }), + }); + } } else { - updateSavedConnection(id, { status: toConnectionStatus(state) }); + firmwareChecked = false; + } + }), + // History is stored per radio. Saving the node on the connection lets + // the next connect open that node's history straight away. + session.events.onMyNodeInfo.subscribe(({ myNodeNum }) => { + if (myNodeNum <= 0) return; + if (savedConnection(id)?.nodeNum !== myNodeNum) { + updateSavedConnection(id, { nodeNum: myNodeNum }); } + if (scope !== myNodeNum) { + scope = myNodeNum; + session.rescope(myNodeNum); + } + }), + // Firmware emits `rebooted` after a soft reset; the SDK reconnects + // and runs the handshake again, so the overlay should show again. + session.events.onRebooted.subscribe(() => { + log.info("device rebooted, re-entering configuring", { id }); + updateStatus(id, "configuring"); }), - ); + ]; + sessionTeardowns.set(id, () => { + for (const off of unsubscribes) off(); + session.close(); + }); + try { await client.connect(); - await setupMeshDevice(id, kmpTransport(client), { - sdkOwnsConnection: true, - }); return true; } catch (error) { log.error("kmp: connect failed", { @@ -455,23 +328,27 @@ export function useConnections() { name: error instanceof Error ? error.name : undefined, message: error instanceof Error ? error.message : String(error), }); - kmpSubscriptions.get(id)?.(); - kmpSubscriptions.delete(id); + sessionTeardowns.get(id)?.(); + sessionTeardowns.delete(id); updateSavedConnection(id, connectFailure(error)); return false; } }, - [setupMeshDevice, updateSavedConnection], + [ + addDevice, + setSelectedDevice, + setActiveConnectionId, + updateSavedConnection, + updateStatus, + ], ); const connect = useCallback( async (id: ConnectionId, opts?: { allowPrompt?: boolean }) => { - // Read from the live store, not the memoized `connections` closure: callers - // such as addConnectionAndConnect() add a connection and connect to it in the - // same tick, before this hook re-renders, so the closure would be stale. - const conn = useDeviceStore - .getState() - .savedConnections.find((c) => c.id === id); + // Read from the live store, not the memoized `connections` closure: + // addConnectionAndConnect() adds a connection and connects to it in + // the same tick, before this hook re-renders. + const conn = savedConnection(id); if (!conn) { log.warn("connect: unknown connection id", { id }); return false; @@ -525,7 +402,7 @@ export function useConnections() { const conn = connections.find((c) => c.id === id); if (!conn) return; try { - await teardown(id, conn); + await teardown(id); if (conn.meshDeviceId) { useDeviceStore .getState() diff --git a/apps/web/src/pages/Connections/utils.ts b/apps/web/src/pages/Connections/utils.ts index e34bd61d1..da3839711 100644 --- a/apps/web/src/pages/Connections/utils.ts +++ b/apps/web/src/pages/Connections/utils.ts @@ -7,7 +7,7 @@ import type { import { randId } from "@app/core/utils/randId"; import { t } from "i18next"; import { Bluetooth, Cable, Globe, type LucideIcon } from "lucide-react"; -import { withLocalNetworkTarget } from "@meshtastic/transport-http"; +import { withLocalNetworkTarget } from "@app/core/connections/lna.ts"; export function createConnectionFromInput(input: NewConnection): Connection { const base = { diff --git a/apps/web/src/pages/Messages.tsx b/apps/web/src/pages/Messages.tsx index 53e8bc848..4f4f63079 100644 --- a/apps/web/src/pages/Messages.tsx +++ b/apps/web/src/pages/Messages.tsx @@ -18,7 +18,7 @@ import { useChannels, useNodeErrors, useUnreadByKey, -} from "@meshtastic/sdk-react"; +} from "@core/kmp/hooks"; import { useNavigate, useParams } from "@tanstack/react-router"; import { HashIcon, LockIcon, LockOpenIcon } from "lucide-react"; import { @@ -52,10 +52,7 @@ export const MessagesPage = () => { unreadByKey.get(`channel:${idx}`) ?? 0; const markChannelRead = useCallback( (idx: number) => - meshClient?.chat.unread.markRead({ - kind: "channel", - channel: idx as Types.ChannelNumber, - }), + meshClient?.chat.unread.markRead({ kind: "channel", channel: idx }), [meshClient], ); const markDirectRead = useCallback( diff --git a/apps/web/src/pages/Nodes/index.tsx b/apps/web/src/pages/Nodes/index.tsx index c192a2a9b..1aa3d2ef0 100644 --- a/apps/web/src/pages/Nodes/index.tsx +++ b/apps/web/src/pages/Nodes/index.tsx @@ -24,7 +24,7 @@ import useLang from "@core/hooks/useLang.ts"; import { useNodesAsProto } from "@core/hooks/useNodesAsProto.ts"; import { useAppStore, useDevice } from "@core/stores"; import { Protobuf, type Types } from "@core/protobuf.ts"; -import { useNodeErrors } from "@meshtastic/sdk-react"; +import { useActiveClient, useNodeErrors } from "@core/kmp/hooks"; import { numberToHexUnpadded } from "@noble/curves/utils.js"; import { LockIcon, LockOpenIcon } from "lucide-react"; import { @@ -46,7 +46,8 @@ export interface DeleteNoteDialogProps { const NodesPage = (): JSX.Element => { const { t } = useTranslation("nodes"); const { current } = useLang(); - const { hardware, connection, setDialogOpen } = useDevice(); + const { hardware, setDialogOpen } = useDevice(); + const connection = useActiveClient(); const { setNodeNumDetails } = useAppStore(); const { nodeFilter, defaultFilterValues, isFilterDirty } = useFilterNode(); @@ -111,20 +112,14 @@ const NodesPage = (): JSX.Element => { if (!connection) { return; } - connection.events.onTraceRoutePacket.subscribe(handleTraceroute); - return () => { - connection.events.onTraceRoutePacket.unsubscribe(handleTraceroute); - }; + return connection.events.onTraceRoutePacket.subscribe(handleTraceroute); }, [connection, handleTraceroute]); useEffect(() => { if (!connection) { return; } - connection.events.onPositionPacket.subscribe(handleLocation); - return () => { - connection.events.onPositionPacket.unsubscribe(handleLocation); - }; + return connection.events.onPositionPacket.subscribe(handleLocation); }, [connection, handleLocation]); const tableHeadings: Heading[] = [ diff --git a/apps/web/src/pages/Settings/Administration.tsx b/apps/web/src/pages/Settings/Administration.tsx index e8884f95a..9be0289cb 100644 --- a/apps/web/src/pages/Settings/Administration.tsx +++ b/apps/web/src/pages/Settings/Administration.tsx @@ -21,6 +21,7 @@ import { import { useState } from "react"; import { useTranslation } from "react-i18next"; import { type ConfigProps, SettingsCard } from "./SettingsTabs.tsx"; +import { useActiveClient } from "@core/kmp/hooks"; type AdminAction = { key: @@ -68,7 +69,8 @@ const ACTIONS: AdminAction[] = [ export const Administration = (_props: ConfigProps) => { const { t } = useTranslation("ui"); const { toast } = useToast(); - const { setDialogOpen, connection } = useDevice(); + const { setDialogOpen } = useDevice(); + const connection = useActiveClient(); const connected = useDeviceConnected(); const [dfuConfirmOpen, setDfuConfirmOpen] = useState(false); diff --git a/apps/web/src/pages/Settings/BackupRestore.tsx b/apps/web/src/pages/Settings/BackupRestore.tsx index 8baf58d89..c859b21ee 100644 --- a/apps/web/src/pages/Settings/BackupRestore.tsx +++ b/apps/web/src/pages/Settings/BackupRestore.tsx @@ -24,7 +24,7 @@ import { } from "@core/utils/profileExport.ts"; import type { ConfigEditor } from "@core/kmp/configEditor.ts"; import { Protobuf } from "@core/protobuf.ts"; -import { useActiveClient } from "@meshtastic/sdk-react"; +import { useActiveClient } from "@core/kmp/hooks"; import { useConfigEditor, useSignal } from "@core/kmp/hooks"; import { Result } from "better-result"; import { DownloadIcon, UploadIcon } from "lucide-react"; diff --git a/apps/web/src/pages/Settings/CleanNodeDb.tsx b/apps/web/src/pages/Settings/CleanNodeDb.tsx index 915c92c2f..292ac86c0 100644 --- a/apps/web/src/pages/Settings/CleanNodeDb.tsx +++ b/apps/web/src/pages/Settings/CleanNodeDb.tsx @@ -16,13 +16,12 @@ import { minDays, nodesToClean, } from "@core/utils/cleanNodes.ts"; -import type { Node } from "@meshtastic/sdk"; -import { useActiveClient } from "@meshtastic/sdk-react"; -import { useSignal } from "@core/kmp/hooks"; +import type { Node } from "@core/storage/types.ts"; import { EraserIcon } from "lucide-react"; import { useId, useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; import { type ConfigProps, SettingsCard } from "./SettingsTabs.tsx"; +import { useActiveClient, useSignal } from "@core/kmp/hooks"; const EMPTY_NODES: ReadonlyArray = []; const EMPTY_NODES_SIGNAL = { diff --git a/apps/web/src/pages/Settings/DebugPanel.tsx b/apps/web/src/pages/Settings/DebugPanel.tsx index 401b23f09..664c6c9f4 100644 --- a/apps/web/src/pages/Settings/DebugPanel.tsx +++ b/apps/web/src/pages/Settings/DebugPanel.tsx @@ -12,7 +12,7 @@ import { formatLogEntry, } from "@core/utils/logRecords.ts"; import { Protobuf } from "@core/protobuf.ts"; -import { useActiveClient } from "@meshtastic/sdk-react"; +import { useActiveClient } from "@core/kmp/hooks"; import { useNavigate } from "@tanstack/react-router"; import { DownloadIcon, ShieldIcon, Trash2Icon } from "lucide-react"; import { useEffect, useMemo, useRef, useState } from "react"; diff --git a/apps/web/src/tests/adminInterceptor.ts b/apps/web/src/tests/adminInterceptor.ts new file mode 100644 index 000000000..b2b9f1324 --- /dev/null +++ b/apps/web/src/tests/adminInterceptor.ts @@ -0,0 +1,137 @@ +import { create, fromBinary } from "@bufbuild/protobuf"; +import { adminOk, type FakeKmpClient } from "@core/kmp/fakeClient.ts"; +import { Protobuf } from "@core/protobuf.ts"; +import type { AdminResultJs } from "@meshtastic/sdk-kmp"; + +type AdminCase = NonNullable< + Protobuf.Admin.AdminMessage["payloadVariant"]["case"] +>; +type ConfigVariant = Protobuf.Config.Config["payloadVariant"]; +type ModuleConfigVariant = Protobuf.ModuleConfig.ModuleConfig["payloadVariant"]; +type ConfigCase = NonNullable; +type ModuleConfigCase = NonNullable; + +export interface HeldSend { + /** Resolves once the send is being held. */ + reached: Promise; + release(): void; +} + +export interface AdminInterceptor { + /** Every admin message sent, decoded, in order; a settings transaction is bracketed by begin/commit. */ + sent: Protobuf.Admin.AdminMessage[]; + cases(): (AdminCase | undefined)[]; + /** Holds the next send of `adminCase` (a transaction, for `commitEditSettings`) open until released. */ + hold(adminCase: AdminCase): HeldSend; + /** Makes the next send carrying `adminCase` fail. */ + failNext(adminCase: AdminCase): void; + sentConfig( + section: K, + ): Extract | undefined; + sentModuleConfig( + section: K, + ): Extract | undefined; +} + +const bracket = (adminCase: "beginEditSettings" | "commitEditSettings") => + create(Protobuf.Admin.AdminMessageSchema, { + payloadVariant: { case: adminCase, value: true }, + }); + +/** + * Watches the admin messages a fake facade client's local admin API is + * given, so a test can see what a commit sent and hold or fail it. + */ +export function interceptAdmin(client: FakeKmpClient): AdminInterceptor { + const admin = client.admin(); + const sent: Protobuf.Admin.AdminMessage[] = []; + const holds: { + adminCase: AdminCase; + onReached: () => void; + released: Promise; + }[] = []; + const failures: AdminCase[] = []; + + const decode = (bytes: Uint8Array) => + fromBinary(Protobuf.Admin.AdminMessageSchema, bytes); + + async function gate( + messages: Protobuf.Admin.AdminMessage[], + terminal: AdminCase | undefined, + ): Promise { + const cases = messages.map((m) => m.payloadVariant.case); + const failure = failures.findIndex((c) => cases.includes(c)); + if (failure !== -1) { + failures.splice(failure, 1); + return { ok: false, reason: "send failed", value: null, text: null }; + } + const held = holds.findIndex( + (h) => cases.includes(h.adminCase) || h.adminCase === terminal, + ); + if (held !== -1) { + const [hold] = holds.splice(held, 1); + if (hold) { + hold.onReached(); + await hold.released; + } + } + return adminOk(); + } + + admin.send = async (bytes) => { + const message = decode(bytes); + sent.push(message); + return gate([message], undefined); + }; + admin.editSettings = async (batch) => { + const messages = batch.map(decode); + sent.push(bracket("beginEditSettings"), ...messages); + const result = await gate(messages, "commitEditSettings"); + sent.push(bracket("commitEditSettings")); + return result; + }; + + return { + sent, + cases: () => sent.map((admin) => admin.payloadVariant.case), + hold(adminCase) { + let onReached = (): void => {}; + let release = (): void => {}; + const reached = new Promise((resolve) => { + onReached = resolve; + }); + const released = new Promise((resolve) => { + release = resolve; + }); + holds.push({ adminCase, onReached, released }); + return { reached, release }; + }, + failNext(adminCase) { + failures.push(adminCase); + }, + sentConfig(section) { + for (const admin of sent) { + if (admin.payloadVariant.case !== "setConfig") continue; + const variant = admin.payloadVariant.value.payloadVariant; + const match = [variant].find( + (v): v is Extract => + v.case === section, + ); + if (match) return match; + } + return undefined; + }, + sentModuleConfig(section) { + for (const admin of sent) { + if (admin.payloadVariant.case !== "setModuleConfig") continue; + const variant = admin.payloadVariant.value.payloadVariant; + const match = [variant].find( + (v): v is Extract => + v.case === section, + ); + if (match) return match; + } + return undefined; + }, + }; +} diff --git a/apps/web/src/tests/renderSettingsForm.tsx b/apps/web/src/tests/renderSettingsForm.tsx index 3f507efa3..c7450fa34 100644 --- a/apps/web/src/tests/renderSettingsForm.tsx +++ b/apps/web/src/tests/renderSettingsForm.tsx @@ -1,15 +1,14 @@ import { editorFor } from "@core/kmp/configEditorIo.ts"; -import { CurrentDeviceContext, useDeviceStore } from "@core/stores"; -import { MeshClient, MeshRegistry } from "@meshtastic/sdk"; +import { FakeKmpClient } from "@core/kmp/fakeClient.ts"; +import { MeshRegistryProvider } from "@core/kmp/hooks"; +import { MeshRegistry } from "@core/kmp/registry.ts"; +import { MeshSession } from "@core/kmp/session.ts"; import type { Protobuf } from "@core/protobuf.ts"; -import { - createFakeTransport, - interceptAdminMessages, -} from "@meshtastic/sdk/testing"; -import { MeshRegistryProvider } from "@meshtastic/sdk-react"; +import { CurrentDeviceContext, useDeviceStore } from "@core/stores"; import { cleanup, render } from "@testing-library/react"; import { type ReactElement, Suspense } from "react"; import { afterEach } from "vitest"; +import { interceptAdmin } from "./adminInterceptor.ts"; let nextDeviceId = 1000; const teardowns: (() => void)[] = []; @@ -31,13 +30,13 @@ export function renderSettingsForm( moduleConfig?: Protobuf.ModuleConfig.ModuleConfig[]; }, ) { - const { transport } = createFakeTransport(); + const kmp = new FakeKmpClient(); const registry = new MeshRegistry(); - const client = new MeshClient({ transport }); + const client = new MeshSession(kmp); const id = nextDeviceId++; registry.register(id, client); registry.setActive(id); - const radio = interceptAdminMessages(client); + const radio = interceptAdmin(kmp); const editor = editorFor(client); const stored = useDeviceStore.getState().addDevice(id); @@ -52,6 +51,7 @@ export function renderSettingsForm( teardowns.push(() => { registry.unregister(id); + client.close(); useDeviceStore.getState().removeDevice(id); }); From 659f3c1c2e3b5a8600f09a0bc916bd5478baea90 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 09:38:57 -0500 Subject: [PATCH 18/49] feat(web): the Kotlin SDK's storage over the sqlocal database SqlocalDeviceStorage implements the facade's DeviceStorageJs (node DB, config bundle, channels, heartbeats, session passkey) in the same database as the web's message, draft, node and telemetry history, keyed by node number like them; schema v5 adds the sdk_* tables and a node_info column while the TypeScript SDK's node rows stay readable as NodeInfo. The three facade factories receive it per connection. A migration test proves rows written by the old storage, under the same keys, stay readable. --- apps/web/src/core/connections/repositories.ts | 14 + apps/web/src/core/kmp/client.ts | 20 +- .../src/core/storage/deviceStorage.test.ts | 129 +++++++++ apps/web/src/core/storage/deviceStorage.ts | 271 ++++++++++++++++++ apps/web/src/core/storage/legacyRows.test.ts | 162 +++++++++++ apps/web/src/core/storage/schema.ts | 82 ++++++ .../src/pages/Connections/useConnections.ts | 7 +- packages/sdk-kmp/README.md | 5 + 8 files changed, 684 insertions(+), 6 deletions(-) create mode 100644 apps/web/src/core/storage/deviceStorage.test.ts create mode 100644 apps/web/src/core/storage/deviceStorage.ts create mode 100644 apps/web/src/core/storage/legacyRows.test.ts diff --git a/apps/web/src/core/connections/repositories.ts b/apps/web/src/core/connections/repositories.ts index 02cf06c2d..5d22d7d5b 100644 --- a/apps/web/src/core/connections/repositories.ts +++ b/apps/web/src/core/connections/repositories.ts @@ -1,6 +1,8 @@ import type { SessionOptions } from "@core/kmp/session.ts"; +import type { StorageJs } from "@meshtastic/sdk-kmp"; import { createLogger } from "@core/log.ts"; import { coordinator, getStorageDb } from "@core/sdkStorage.ts"; +import { sqlocalStorage } from "@core/storage/deviceStorage.ts"; import { SqlocalDraftRepository } from "@core/storage/drafts.ts"; import { SqlocalMessageRepository } from "@core/storage/messages.ts"; import { SqlocalNodesRepository } from "@core/storage/nodes.ts"; @@ -25,6 +27,18 @@ const STORAGE_OPEN_TIMEOUT_MS = 5000; */ export const UNKNOWN_NODE_SCOPE = -1; +/** + * The SDK's own storage (node DB, config bundle, channels, heartbeats) over + * the same DB and key. Opening fails loudly: the SDK then reports storage + * as degraded and runs the session in memory. + */ +export function sdkStorage(nodeNum?: number): StorageJs { + return sqlocalStorage( + async () => (await getStorageDb()).db, + nodeNum ?? UNKNOWN_NODE_SCOPE, + ); +} + /** * Opens the message, draft, node and telemetry repositories against the * shared OPFS-backed SQLite DB, scoped to `nodeNum` (the node this diff --git a/apps/web/src/core/kmp/client.ts b/apps/web/src/core/kmp/client.ts index 5ab86d267..72d2d011c 100644 --- a/apps/web/src/core/kmp/client.ts +++ b/apps/web/src/core/kmp/client.ts @@ -1,6 +1,10 @@ -import type { MeshtasticClient } from "@meshtastic/sdk-kmp"; +import type { MeshtasticClient, StorageJs } from "@meshtastic/sdk-kmp"; -export type { ConnectionStateJs, MeshtasticClient } from "@meshtastic/sdk-kmp"; +export type { + ConnectionStateJs, + MeshtasticClient, + StorageJs, +} from "@meshtastic/sdk-kmp"; /** Reconnect attempts the SDK makes before giving up, as the user approved. */ export const MAX_RECONNECT_ATTEMPTS = 10; @@ -21,9 +25,15 @@ export function loadKmp(): Promise { export async function createHttpClient( url: string, allowPrompt: boolean, + storage?: StorageJs, ): Promise { const kmp = await loadKmp(); - return kmp.createHttpClient(url, allowPrompt, MAX_RECONNECT_ATTEMPTS); + return kmp.createHttpClient( + url, + allowPrompt, + MAX_RECONNECT_ATTEMPTS, + storage, + ); } export interface SerialTarget { @@ -41,6 +51,7 @@ export interface BluetoothTarget { export async function createSerialClient( target: SerialTarget, + storage?: StorageJs, ): Promise { const kmp = await loadKmp(); return kmp.createSerialClient( @@ -48,16 +59,19 @@ export async function createSerialClient( target.usbVendorId, target.usbProductId, MAX_RECONNECT_ATTEMPTS, + storage, ); } export async function createBluetoothClient( target: BluetoothTarget, + storage?: StorageJs, ): Promise { const kmp = await loadKmp(); return kmp.createBluetoothClient( target.device, target.deviceId, MAX_RECONNECT_ATTEMPTS, + storage, ); } diff --git a/apps/web/src/core/storage/deviceStorage.test.ts b/apps/web/src/core/storage/deviceStorage.test.ts new file mode 100644 index 000000000..08ccdaeaa --- /dev/null +++ b/apps/web/src/core/storage/deviceStorage.test.ts @@ -0,0 +1,129 @@ +import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; +import { Protobuf } from "@core/protobuf.ts"; +import { beforeEach, describe, expect, it } from "vitest"; +import type { SqlocalDb } from "./db.ts"; +import { SqlocalDeviceStorage } from "./deviceStorage.ts"; +import { createMemoryDb } from "./memoryDb.ts"; +import { SqlocalNodesRepository } from "./nodes.ts"; + +const NODE = 0x0a0b0c0d; + +const nodeInfo = (num: number, longName: string) => + toBinary( + Protobuf.Mesh.NodeInfoSchema, + create(Protobuf.Mesh.NodeInfoSchema, { + num, + lastHeard: 1234, + isFavorite: true, + user: create(Protobuf.Mesh.UserSchema, { longName }), + }), + ); + +const bundle = () => ({ + myInfo: toBinary( + Protobuf.Mesh.MyNodeInfoSchema, + create(Protobuf.Mesh.MyNodeInfoSchema, { myNodeNum: NODE }), + ), + metadata: toBinary( + Protobuf.Mesh.DeviceMetadataSchema, + create(Protobuf.Mesh.DeviceMetadataSchema, { firmwareVersion: "2.8.3" }), + ), + configs: [ + toBinary( + Protobuf.Config.ConfigSchema, + create(Protobuf.Config.ConfigSchema, { + payloadVariant: { case: "lora", value: { region: 4 } }, + }), + ), + ], + moduleConfigs: [], + deviceUiConfig: null, +}); + +describe("SqlocalDeviceStorage", () => { + let db: SqlocalDb; + let storage: SqlocalDeviceStorage; + + beforeEach(async () => { + db = await createMemoryDb(); + storage = new SqlocalDeviceStorage(db, NODE); + }); + + it("round-trips nodes and keeps the web's node repository reading them", async () => { + await storage.saveNode(nodeInfo(1, "one")); + await storage.saveNode(nodeInfo(2, "two")); + await storage.saveNode(nodeInfo(1, "uno")); + const loaded = (await storage.loadNodes()).map((bytes) => + fromBinary(Protobuf.Mesh.NodeInfoSchema, bytes), + ); + expect(loaded.map((n) => [n.num, n.user?.longName, n.isFavorite])).toEqual([ + [1, "uno", true], + [2, "two", true], + ]); + + const web = new SqlocalNodesRepository(db, { deviceId: NODE }); + expect((await web.get(1))?.user?.longName).toBe("uno"); + + await storage.removeNode(1); + expect((await storage.loadNodes()).length).toBe(1); + }); + + it("round-trips the config bundle and channels", async () => { + expect(await storage.loadConfig()).toBeNull(); + await storage.saveConfig(bundle()); + const config = await storage.loadConfig(); + expect( + fromBinary( + Protobuf.Mesh.MyNodeInfoSchema, + config?.myInfo ?? new Uint8Array(), + ).myNodeNum, + ).toBe(NODE); + expect(config?.configs).toHaveLength(1); + expect(config?.deviceUiConfig).toBeNull(); + + const channel = (index: number) => + toBinary( + Protobuf.Channel.ChannelSchema, + create(Protobuf.Channel.ChannelSchema, { index }), + ); + await storage.saveChannels([channel(0), channel(1)]); + await storage.saveChannels([channel(0)]); + expect(await storage.loadChannels()).toEqual([channel(0)]); + }); + + it("keeps heartbeats and an unexpired passkey", async () => { + await storage.saveHeartbeat(7, 1000); + await storage.saveHeartbeat(7, 2000); + await storage.saveHeartbeat(8, 3000); + expect(await storage.loadHeartbeats()).toEqual([ + { nodeNum: 7, epochMillis: 2000 }, + { nodeNum: 8, epochMillis: 3000 }, + ]); + + expect(await storage.loadSessionPasskey()).toBeNull(); + await storage.saveSessionPasskey({ + bytes: new Uint8Array([1, 2]), + expiresAtEpochMs: Date.now() + 60_000, + }); + expect((await storage.loadSessionPasskey())?.bytes).toEqual( + new Uint8Array([1, 2]), + ); + await storage.saveSessionPasskey({ + bytes: new Uint8Array([3]), + expiresAtEpochMs: Date.now() - 1, + }); + expect(await storage.loadSessionPasskey()).toBeNull(); + }); + + it("moves to the node the handshake names instead of wiping", async () => { + const unknown = new SqlocalDeviceStorage(db, -1); + await storage.saveNode(nodeInfo(1, "known")); + expect(await unknown.loadNodes()).toEqual([]); + await unknown.recordOwnNode(NODE, "2.8.3"); + expect(unknown.currentScope).toBe(NODE); + expect((await unknown.loadNodes()).length).toBe(1); + + await unknown.clear(); + expect(await storage.loadNodes()).toEqual([]); + }); +}); diff --git a/apps/web/src/core/storage/deviceStorage.ts b/apps/web/src/core/storage/deviceStorage.ts new file mode 100644 index 000000000..05ebfe060 --- /dev/null +++ b/apps/web/src/core/storage/deviceStorage.ts @@ -0,0 +1,271 @@ +import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; +import { Protobuf } from "@core/protobuf.ts"; +import type { + ConfigBundleJs, + DeviceStorageJs, + HeartbeatJs, + PasskeyJs, + StorageJs, +} from "@meshtastic/sdk-kmp"; +import { and, eq } from "drizzle-orm"; +import type { SqlocalDb } from "./db.ts"; +import { + nodes, + sdkChannels, + sdkConfig, + sdkHeartbeats, + sdkOwnNode, + sdkPasskey, +} from "./schema.ts"; +import { base64Decode, base64Encode } from "./types.ts"; + +/** + * The Kotlin SDK's DeviceStorage over the shared sqlocal DB. Rows are + * keyed by node number, like the web's own history, so every connection to + * the same radio shares them: the scope starts as the node this connection + * reached last time and moves to the node the handshake names. + */ +export class SqlocalDeviceStorage implements DeviceStorageJs { + private scope: number; + + constructor( + private readonly db: SqlocalDb, + scope: number, + ) { + this.scope = scope; + } + + get currentScope(): number { + return this.scope; + } + + async loadNodes(): Promise { + const rows = await this.db + .select() + .from(nodes) + .where(eq(nodes.deviceId, this.scope)); + return rows.map((row) => + row.nodeInfo + ? base64Decode(row.nodeInfo) + : toBinary(Protobuf.Mesh.NodeInfoSchema, legacyNodeInfo(row)), + ); + } + + async saveNode(bytes: Uint8Array): Promise { + const info = fromBinary(Protobuf.Mesh.NodeInfoSchema, bytes); + const row = { + deviceId: this.scope, + num: info.num, + lastHeard: info.lastHeard || null, + snr: info.snr || null, + isFavorite: info.isFavorite, + isIgnored: info.isIgnored, + userJson: info.user + ? base64Encode(toBinary(Protobuf.Mesh.UserSchema, info.user)) + : null, + positionJson: info.position + ? base64Encode(toBinary(Protobuf.Mesh.PositionSchema, info.position)) + : null, + metricsJson: info.deviceMetrics + ? base64Encode( + toBinary( + Protobuf.Telemetry.DeviceMetricsSchema, + info.deviceMetrics, + ), + ) + : null, + nodeInfo: base64Encode(bytes), + }; + await this.db + .insert(nodes) + .values(row) + .onConflictDoUpdate({ target: [nodes.deviceId, nodes.num], set: row }); + } + + async removeNode(nodeNum: number): Promise { + await this.db + .delete(nodes) + .where(and(eq(nodes.deviceId, this.scope), eq(nodes.num, nodeNum))); + } + + async loadConfig(): Promise { + const rows = await this.db + .select() + .from(sdkConfig) + .where(eq(sdkConfig.deviceId, this.scope)) + .limit(1); + const row = rows[0]; + if (!row) return null; + return { + myInfo: base64Decode(row.myInfo), + metadata: base64Decode(row.metadata), + configs: decodeList(row.configs), + moduleConfigs: decodeList(row.moduleConfigs), + deviceUiConfig: row.deviceUiConfig + ? base64Decode(row.deviceUiConfig) + : null, + }; + } + + async saveConfig(bundle: ConfigBundleJs): Promise { + const row = { + deviceId: this.scope, + myInfo: base64Encode(bundle.myInfo), + metadata: base64Encode(bundle.metadata), + configs: encodeList(bundle.configs), + moduleConfigs: encodeList(bundle.moduleConfigs), + deviceUiConfig: bundle.deviceUiConfig + ? base64Encode(bundle.deviceUiConfig) + : null, + }; + await this.db + .insert(sdkConfig) + .values(row) + .onConflictDoUpdate({ target: sdkConfig.deviceId, set: row }); + } + + async loadChannels(): Promise { + const rows = await this.db + .select() + .from(sdkChannels) + .where(eq(sdkChannels.deviceId, this.scope)) + .orderBy(sdkChannels.idx); + return rows.map((row) => base64Decode(row.channel)); + } + + async saveChannels(channels: Uint8Array[]): Promise { + await this.db + .delete(sdkChannels) + .where(eq(sdkChannels.deviceId, this.scope)); + if (channels.length === 0) return; + await this.db.insert(sdkChannels).values( + channels.map((bytes, idx) => ({ + deviceId: this.scope, + idx, + channel: base64Encode(bytes), + })), + ); + } + + /** + * The handshake named the radio. History is keyed by node number, so a + * different node means a different key space rather than a wipe. + */ + async recordOwnNode(nodeNum: number, firmwareVersion: string): Promise { + this.scope = nodeNum; + const row = { deviceId: nodeNum, nodeNum, firmwareVersion }; + await this.db + .insert(sdkOwnNode) + .values(row) + .onConflictDoUpdate({ target: sdkOwnNode.deviceId, set: row }); + } + + async clear(): Promise { + const scope = this.scope; + await this.db.delete(nodes).where(eq(nodes.deviceId, scope)); + await this.db.delete(sdkConfig).where(eq(sdkConfig.deviceId, scope)); + await this.db.delete(sdkChannels).where(eq(sdkChannels.deviceId, scope)); + await this.db + .delete(sdkHeartbeats) + .where(eq(sdkHeartbeats.deviceId, scope)); + await this.db.delete(sdkPasskey).where(eq(sdkPasskey.deviceId, scope)); + await this.db.delete(sdkOwnNode).where(eq(sdkOwnNode.deviceId, scope)); + } + + close(): void {} + + async saveSessionPasskey(passkey: PasskeyJs): Promise { + const row = { + deviceId: this.scope, + passkey: base64Encode(passkey.bytes), + expiresAt: passkey.expiresAtEpochMs, + }; + await this.db + .insert(sdkPasskey) + .values(row) + .onConflictDoUpdate({ target: sdkPasskey.deviceId, set: row }); + } + + async loadSessionPasskey(): Promise { + const rows = await this.db + .select() + .from(sdkPasskey) + .where(eq(sdkPasskey.deviceId, this.scope)) + .limit(1); + const row = rows[0]; + if (!row || row.expiresAt <= Date.now()) return null; + return { + bytes: base64Decode(row.passkey), + expiresAtEpochMs: row.expiresAt, + }; + } + + async saveHeartbeat(nodeNum: number, epochMillis: number): Promise { + const row = { deviceId: this.scope, nodeNum, epochMs: epochMillis }; + await this.db + .insert(sdkHeartbeats) + .values(row) + .onConflictDoUpdate({ + target: [sdkHeartbeats.deviceId, sdkHeartbeats.nodeNum], + set: { epochMs: epochMillis }, + }); + } + + async loadHeartbeats(): Promise { + const rows = await this.db + .select() + .from(sdkHeartbeats) + .where(eq(sdkHeartbeats.deviceId, this.scope)); + return rows.map((row) => ({ + nodeNum: row.nodeNum, + epochMillis: row.epochMs, + })); + } +} + +/** A NodeInfo from the columns the TypeScript SDK's repository wrote. */ +function legacyNodeInfo( + row: typeof nodes.$inferSelect, +): Protobuf.Mesh.NodeInfo { + return create(Protobuf.Mesh.NodeInfoSchema, { + num: row.num, + user: row.userJson + ? fromBinary(Protobuf.Mesh.UserSchema, base64Decode(row.userJson)) + : undefined, + position: row.positionJson + ? fromBinary(Protobuf.Mesh.PositionSchema, base64Decode(row.positionJson)) + : undefined, + deviceMetrics: row.metricsJson + ? fromBinary( + Protobuf.Telemetry.DeviceMetricsSchema, + base64Decode(row.metricsJson), + ) + : undefined, + lastHeard: row.lastHeard ?? 0, + snr: row.snr ?? 0, + isFavorite: row.isFavorite, + isIgnored: row.isIgnored, + }); +} + +function encodeList(items: ReadonlyArray): string { + return JSON.stringify(items.map(base64Encode)); +} + +function decodeList(json: string): Uint8Array[] { + const parsed: unknown = JSON.parse(json); + if (!Array.isArray(parsed)) return []; + return parsed.flatMap((item) => + typeof item === "string" ? [base64Decode(item)] : [], + ); +} + +/** A `StorageJs` for the facade's factories, opening the DB on activation. */ +export function sqlocalStorage( + openDb: () => Promise, + scope: number, +): StorageJs { + return { + activate: async () => new SqlocalDeviceStorage(await openDb(), scope), + }; +} diff --git a/apps/web/src/core/storage/legacyRows.test.ts b/apps/web/src/core/storage/legacyRows.test.ts new file mode 100644 index 000000000..349442539 --- /dev/null +++ b/apps/web/src/core/storage/legacyRows.test.ts @@ -0,0 +1,162 @@ +import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; +import { Protobuf, Types } from "@core/protobuf.ts"; +import { drizzle } from "drizzle-orm/sql-js"; +import initSqlJs from "sql.js"; +import { describe, expect, it } from "vitest"; +import type { SqlocalDb } from "./db.ts"; +import { SqlocalDeviceStorage } from "./deviceStorage.ts"; +import { SqlocalDraftRepository } from "./drafts.ts"; +import { SqlocalMessageRepository } from "./messages.ts"; +import { SqlocalNodesRepository } from "./nodes.ts"; +import * as schema from "./schema.ts"; +import { MIGRATIONS } from "./schema.ts"; +import { SqlocalTelemetryRepository } from "./telemetry.ts"; +import { base64Encode, MessageState } from "./types.ts"; + +const NODE = 0x0a0b0c0d; +const PEER = 0x11223344; + +/** + * A database as the TypeScript SDK's sqlocal adapter left it (schema v4), + * with the rows it wrote under `device_id = `. + */ +async function legacyDb(): Promise<{ + db: SqlocalDb; + migrate: () => void; +}> { + const SQL = await initSqlJs({}); + const sqlite = new SQL.Database(); + const legacy = MIGRATIONS.filter((m) => m.version <= 4); + const later = MIGRATIONS.filter((m) => m.version > 4); + for (const migration of legacy) { + for (const statement of migration.sql) sqlite.run(statement); + sqlite.run("INSERT OR IGNORE INTO _schema (version) VALUES (?)", [ + migration.version, + ]); + } + sqlite.run( + `INSERT INTO messages (id, device_id, conversation_key, from_node, to_node, channel, rx_time, type, text, state, signed, relays) + VALUES (42, ?, 'direct:${PEER}', ?, ?, 0, 1700000000000, 'direct', 'old hello', 'ack', 1, 2)`, + [NODE, PEER, NODE], + ); + sqlite.run( + `INSERT INTO messages (id, device_id, conversation_key, from_node, to_node, channel, rx_time, type, text, state) + VALUES (43, ?, 'channel:0', ?, 4294967295, 0, 1700000001000, 'broadcast', 'old all', 'delivered')`, + [NODE, NODE], + ); + sqlite.run( + `INSERT INTO drafts (device_id, conversation_key, text, updated_at) VALUES (?, 'direct:${PEER}', 'unsent', 1)`, + [NODE], + ); + const user = base64Encode( + toBinary( + Protobuf.Mesh.UserSchema, + create(Protobuf.Mesh.UserSchema, { longName: "Peer", shortName: "PR" }), + ), + ); + const position = base64Encode( + toBinary( + Protobuf.Mesh.PositionSchema, + create(Protobuf.Mesh.PositionSchema, { latitudeI: 123, longitudeI: 456 }), + ), + ); + sqlite.run( + `INSERT INTO nodes (device_id, num, last_heard, snr, is_favorite, is_ignored, user_json, position_json, metrics_json) + VALUES (?, ?, 1700000000, 7, 1, 0, ?, ?, NULL)`, + [NODE, PEER, user, position], + ); + const metrics = base64Encode( + toBinary( + Protobuf.Telemetry.DeviceMetricsSchema, + create(Protobuf.Telemetry.DeviceMetricsSchema, { batteryLevel: 88 }), + ), + ); + sqlite.run( + `INSERT INTO telemetry (device_id, node_num, kind, ts, payload_json) VALUES (?, ?, 'deviceMetrics', 1700000002000, ?)`, + [NODE, PEER, metrics], + ); + const db: SqlocalDb = drizzle(sqlite, { schema, casing: "snake_case" }); + return { + db, + migrate: () => { + for (const migration of later) { + for (const statement of migration.sql) sqlite.run(statement); + sqlite.run("INSERT OR IGNORE INTO _schema (version) VALUES (?)", [ + migration.version, + ]); + } + }, + }; +} + +describe("rows written by the TypeScript SDK storage", () => { + it("stay readable under the same node-number key after the SDK storage migration", async () => { + const { db, migrate } = await legacyDb(); + migrate(); + + const messages = new SqlocalMessageRepository(db, { deviceId: NODE }); + const direct = await messages.loadRecent( + { kind: "direct", peer: PEER }, + 10, + ); + expect(direct).toMatchObject([ + { + id: 42, + from: PEER, + to: NODE, + text: "old hello", + state: MessageState.Ack, + signed: true, + relays: 2, + channel: Types.ChannelNumber.Primary, + }, + ]); + expect(direct[0]?.rxTime.getTime()).toBe(1700000000000); + const broadcast = await messages.loadRecent( + { kind: "channel", channel: Types.ChannelNumber.Primary }, + 10, + ); + expect(broadcast.map((m) => [m.text, m.state])).toEqual([ + ["old all", MessageState.Delivered], + ]); + + const drafts = new SqlocalDraftRepository(db, { deviceId: NODE }); + expect(await drafts.load({ kind: "direct", peer: PEER })).toBe("unsent"); + + const nodes = new SqlocalNodesRepository(db, { deviceId: NODE }); + const node = await nodes.get(PEER); + expect(node?.user?.longName).toBe("Peer"); + expect(node?.position?.latitudeI).toBe(123); + expect(node?.isFavorite).toBe(true); + expect(node?.lastHeard).toBe(1700000000); + + const telemetry = new SqlocalTelemetryRepository(db, { deviceId: NODE }); + const readings = await telemetry.loadRecent(PEER, 10); + expect(readings.map((r) => r.kind)).toEqual(["deviceMetrics"]); + expect( + readings[0]?.value?.$typeName === "meshtastic.DeviceMetrics" + ? readings[0].value.batteryLevel + : undefined, + ).toBe(88); + + // The SDK's node DB sees the old row as a NodeInfo until it rewrites it. + const storage = new SqlocalDeviceStorage(db, NODE); + const infos = (await storage.loadNodes()).map((bytes) => + fromBinary(Protobuf.Mesh.NodeInfoSchema, bytes), + ); + expect(infos.map((n) => [n.num, n.user?.shortName, n.snr])).toEqual([ + [PEER, "PR", 7], + ]); + expect(await storage.loadConfig()).toBeNull(); + expect(await storage.loadHeartbeats()).toEqual([]); + }); + + it("is not visible under another node's key", async () => { + const { db, migrate } = await legacyDb(); + migrate(); + const other = new SqlocalMessageRepository(db, { deviceId: NODE + 1 }); + expect(await other.loadRecent({ kind: "direct", peer: PEER }, 10)).toEqual( + [], + ); + }); +}); diff --git a/apps/web/src/core/storage/schema.ts b/apps/web/src/core/storage/schema.ts index 4d1713aa6..e0c0a420f 100644 --- a/apps/web/src/core/storage/schema.ts +++ b/apps/web/src/core/storage/schema.ts @@ -98,6 +98,8 @@ export const nodes = sqliteTable( userJson: text("user_json"), positionJson: text("position_json"), metricsJson: text("metrics_json"), + /** The whole NodeInfo as the SDK last saved it, base64; absent on rows older than v5. */ + nodeInfo: text("node_info"), }, (t) => ({ pk: primaryKey({ columns: [t.deviceId, t.num] }), @@ -126,6 +128,48 @@ export const telemetry = sqliteTable( export type TelemetryRow = typeof telemetry.$inferSelect; export type TelemetryInsert = typeof telemetry.$inferInsert; +/** The SDK's DeviceStorage: one config bundle per node, protobufs as base64. */ +export const sdkConfig = sqliteTable("sdk_config", { + deviceId: integer("device_id").primaryKey(), + myInfo: text("my_info").notNull(), + metadata: text("metadata").notNull(), + configs: text("configs").notNull(), + moduleConfigs: text("module_configs").notNull(), + deviceUiConfig: text("device_ui_config"), +}); + +export const sdkChannels = sqliteTable( + "sdk_channels", + { + deviceId: integer("device_id").notNull(), + idx: integer("idx").notNull(), + channel: text("channel").notNull(), + }, + (t) => ({ pk: primaryKey({ columns: [t.deviceId, t.idx] }) }), +); + +export const sdkHeartbeats = sqliteTable( + "sdk_heartbeats", + { + deviceId: integer("device_id").notNull(), + nodeNum: integer("node_num").notNull(), + epochMs: integer("epoch_ms").notNull(), + }, + (t) => ({ pk: primaryKey({ columns: [t.deviceId, t.nodeNum] }) }), +); + +export const sdkPasskey = sqliteTable("sdk_passkey", { + deviceId: integer("device_id").primaryKey(), + passkey: text("passkey").notNull(), + expiresAt: integer("expires_at").notNull(), +}); + +export const sdkOwnNode = sqliteTable("sdk_own_node", { + deviceId: integer("device_id").primaryKey(), + nodeNum: integer("node_num").notNull(), + firmwareVersion: text("firmware_version").notNull(), +}); + export const schemaVersion = sqliteTable("_schema", { version: integer("version").primaryKey(), }); @@ -213,4 +257,42 @@ export const MIGRATIONS: ReadonlyArray<{ version: number; sql: string[] }> = [ `ALTER TABLE messages ADD COLUMN transport INTEGER`, ], }, + { + // The Kotlin SDK's DeviceStorage (config bundle, channels, heartbeats, + // passkey) next to the existing tables, and the whole NodeInfo on nodes. + version: 5, + sql: [ + `ALTER TABLE nodes ADD COLUMN node_info TEXT`, + `CREATE TABLE IF NOT EXISTS sdk_config ( + device_id INTEGER PRIMARY KEY, + my_info TEXT NOT NULL, + metadata TEXT NOT NULL, + configs TEXT NOT NULL, + module_configs TEXT NOT NULL, + device_ui_config TEXT + )`, + `CREATE TABLE IF NOT EXISTS sdk_channels ( + device_id INTEGER NOT NULL, + idx INTEGER NOT NULL, + channel TEXT NOT NULL, + PRIMARY KEY (device_id, idx) + )`, + `CREATE TABLE IF NOT EXISTS sdk_heartbeats ( + device_id INTEGER NOT NULL, + node_num INTEGER NOT NULL, + epoch_ms INTEGER NOT NULL, + PRIMARY KEY (device_id, node_num) + )`, + `CREATE TABLE IF NOT EXISTS sdk_passkey ( + device_id INTEGER PRIMARY KEY, + passkey TEXT NOT NULL, + expires_at INTEGER NOT NULL + )`, + `CREATE TABLE IF NOT EXISTS sdk_own_node ( + device_id INTEGER PRIMARY KEY, + node_num INTEGER NOT NULL, + firmware_version TEXT NOT NULL + )`, + ], + }, ]; diff --git a/apps/web/src/pages/Connections/useConnections.ts b/apps/web/src/pages/Connections/useConnections.ts index 669f8fe5e..602742f84 100644 --- a/apps/web/src/pages/Connections/useConnections.ts +++ b/apps/web/src/pages/Connections/useConnections.ts @@ -10,6 +10,7 @@ import { } from "@app/core/connections/browserDevices.ts"; import { openRepositories, + sdkStorage, UNKNOWN_NODE_SCOPE, } from "@app/core/connections/repositories.ts"; import type { @@ -369,18 +370,18 @@ export function useConnections() { switch (conn.type) { case "http": return await connectThroughKmp(id, () => - createHttpClient(conn.url, allowPrompt), + createHttpClient(conn.url, allowPrompt, sdkStorage(conn.nodeNum)), ); case "serial": { const target = await serialTarget(conn, allowPrompt); return await connectThroughKmp(id, () => - createSerialClient(target), + createSerialClient(target, sdkStorage(conn.nodeNum)), ); } case "bluetooth": { const target = await bluetoothTarget(conn, allowPrompt); return await connectThroughKmp(id, () => - createBluetoothClient(target), + createBluetoothClient(target, sdkStorage(conn.nodeNum)), ); } } diff --git a/packages/sdk-kmp/README.md b/packages/sdk-kmp/README.md index 6506b0e10..0a41f6586 100644 --- a/packages/sdk-kmp/README.md +++ b/packages/sdk-kmp/README.md @@ -10,6 +10,11 @@ auto-reconnect, node DB, admin); this package owns only the glue: `MeshtasticClient`, `ConnectionStateJs`). Only plain objects, `Promise`s, `Uint8Array`s and unsubscribe functions cross into TypeScript; protobuf messages cross as bytes and are decoded with `@meshtastic/protobufs`. + Sends return a `SendHandleJs` (the packet id now, the outcome later). +- `Storage.kt`: `StorageJs` / `DeviceStorageJs`, the SDK's `StorageProvider` + and `DeviceStorage` as a host-implemented object the factories accept, so + the web keeps the SDK's node DB, config bundle, channels and heartbeats in + its own sqlocal database. - Browser transports implementing the SDK's `RadioTransport`: `HttpTransport.kt` (device HTTP API with Chrome Local Network Access handling in `Lna.kt`), `WebSerialTransport.kt` (stream framing from `Framing.kt`) and From 620c857cc32b62cb37554ab21858b0a21675a7db Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 09:40:42 -0500 Subject: [PATCH 19/49] chore: lockfile for the web app's storage dependencies --- pnpm-lock.yaml | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 470e3d70c..7390c512e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -69,21 +69,9 @@ importers: '@meshtastic/protobufs': specifier: workspace:* version: link:../../packages/protobufs - '@meshtastic/sdk': - specifier: workspace:* - version: link:../../packages/sdk '@meshtastic/sdk-kmp': specifier: workspace:* version: link:../../packages/sdk-kmp - '@meshtastic/sdk-react': - specifier: workspace:* - version: link:../../packages/sdk-react - '@meshtastic/sdk-storage-sqlocal': - specifier: workspace:* - version: link:../../packages/sdk-storage-sqlocal - '@meshtastic/transport-http': - specifier: workspace:* - version: link:../../packages/transport-http '@noble/curves': specifier: ^2.4.0 version: 2.4.0 @@ -183,6 +171,9 @@ importers: crypto-random-string: specifier: ^6.0.0 version: 6.0.0 + drizzle-orm: + specifier: ^0.45.4 + version: 0.45.4(@types/sql.js@1.4.11)(sql.js@1.15.0) i18next: specifier: ^26.4.5 version: 26.4.5(typescript@7.0.2) @@ -231,6 +222,9 @@ importers: rfc4648: specifier: ^1.5.4 version: 1.5.4 + sqlocal: + specifier: ^0.18.0 + version: 0.18.0(drizzle-orm@0.45.4(@types/sql.js@1.4.11)(sql.js@1.15.0))(react@19.3.1)(vite@8.3.4(@types/node@26.6.5)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)) tslog: specifier: ^5.2.0 version: 5.2.0 @@ -283,6 +277,9 @@ importers: '@types/serviceworker': specifier: ^0.0.203 version: 0.0.203 + '@types/sql.js': + specifier: ^1.4.11 + version: 1.4.11 '@types/w3c-web-serial': specifier: ^1.0.8 version: 1.0.8 @@ -307,6 +304,9 @@ importers: oxlint: specifier: ^1.88.0 version: 1.88.0 + sql.js: + specifier: ^1.15.0 + version: 1.15.0 tailwind-merge: specifier: ^3.7.0 version: 3.7.0 From 71e6fb0c2c02c6e44580ca75b14f831f81fc09f7 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 10:03:32 -0500 Subject: [PATCH 20/49] build(sdk-kmp): compile the Kotlin SDK from a pinned submodule Until meshtastic/meshtastic-sdk#215 publishes js artifacts the SDK exists in no Maven repository, so CI and clean checkouts could not build @meshtastic/sdk-kmp. vendor/meshtastic-sdk is now a git submodule pinned to that PR's head and settings.gradle.kts includes it as a composite build, substituting org.meshtastic:sdk-core and sdk-testing with its :core and :testing projects; mavenLocal() is gone. The build script initialises the submodule when it is missing, every workflow that builds sdk-kmp checks out submodules, and the READMEs document the one-line switch to the Maven Central release. --- .github/workflows/ci.yml | 2 ++ .github/workflows/e2e.yml | 2 ++ .github/workflows/nightly.yml | 2 ++ .github/workflows/pr.yml | 2 ++ .github/workflows/release-web.yml | 1 + .gitmodules | 4 ++++ .oxfmtrc.json | 2 +- README.md | 9 ++++++--- packages/sdk-kmp/README.md | 24 +++++++++++++++++------- packages/sdk-kmp/gradle.properties | 6 ++++-- packages/sdk-kmp/scripts/build.mjs | 19 +++++++++++++++++-- packages/sdk-kmp/settings.gradle.kts | 16 +++++++++++++--- packages/sdk-kmp/vendor/meshtastic-sdk | 1 + 13 files changed, 72 insertions(+), 18 deletions(-) create mode 160000 packages/sdk-kmp/vendor/meshtastic-sdk diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 325680964..4452782b3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,6 +15,8 @@ jobs: steps: - name: Checkout code uses: actions/checkout@v7 + with: + submodules: true - name: Setup pnpm uses: pnpm/action-setup@v6 diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index ab4f4790f..3ade3b99e 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -21,6 +21,8 @@ jobs: CI: "true" steps: - uses: actions/checkout@v7 + with: + submodules: true - uses: pnpm/action-setup@v6 diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 01e90977f..88bfe1c1a 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -19,6 +19,8 @@ jobs: steps: - name: Checkout code uses: actions/checkout@v7 + with: + submodules: true - name: Setup pnpm uses: pnpm/action-setup@v6 diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 70f6a2a8a..b23ef56f4 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -22,6 +22,8 @@ jobs: steps: - name: Checkout code uses: actions/checkout@v7 + with: + submodules: true - name: Setup pnpm uses: pnpm/action-setup@v6 diff --git a/.github/workflows/release-web.yml b/.github/workflows/release-web.yml index b458d2a2d..e3fc8b252 100644 --- a/.github/workflows/release-web.yml +++ b/.github/workflows/release-web.yml @@ -34,6 +34,7 @@ jobs: uses: actions/checkout@v7 with: ref: ${{ inputs.ref != '' && inputs.ref || github.ref }} + submodules: true - name: Setup pnpm uses: pnpm/action-setup@v6 diff --git a/.gitmodules b/.gitmodules index e69de29bb..c78ab77bc 100644 --- a/.gitmodules +++ b/.gitmodules @@ -0,0 +1,4 @@ +[submodule "packages/sdk-kmp/vendor/meshtastic-sdk"] + path = packages/sdk-kmp/vendor/meshtastic-sdk + url = https://github.com/danditomaso/meshtastic-sdk.git + branch = feat/js-target diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 32547c59b..f5b60173e 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -3,5 +3,5 @@ "useTabs": false, "tabWidth": 2, "printWidth": 80, - "ignorePatterns": ["*.md"] + "ignorePatterns": ["*.md", "packages/sdk-kmp/vendor/**"] } diff --git a/README.md b/README.md index 88860144b..3866e2208 100644 --- a/README.md +++ b/README.md @@ -94,13 +94,16 @@ Expected domain errors are returned as `Result` via [`better-result`](http the Kotlin meshtastic-sdk compiled to JavaScript that the web client connects through. `pnpm --filter meshtastic-web dev` builds it on first run (its `predev` hook); on macOS `brew install openjdk@21` and - `export JAVA_HOME=/opt/homebrew/opt/openjdk@21`. See - `packages/sdk-kmp/README.md` for how the SDK version is pinned. + `export JAVA_HOME=/opt/homebrew/opt/openjdk@21`. Until the SDK's `js` + artifacts are released, it compiles from the `packages/sdk-kmp/vendor/meshtastic-sdk` + git submodule (clone with `--recurse-submodules`, or let the build run + `git submodule update --init`). See `packages/sdk-kmp/README.md` for how + the SDK version is pinned and how to switch to the release. ### Setup ```bash -git clone https://github.com/meshtastic/web.git +git clone --recurse-submodules https://github.com/meshtastic/web.git cd web pnpm install ``` diff --git a/packages/sdk-kmp/README.md b/packages/sdk-kmp/README.md index 0a41f6586..e4fe1c4f3 100644 --- a/packages/sdk-kmp/README.md +++ b/packages/sdk-kmp/README.md @@ -41,8 +41,9 @@ fakes. - **JDK 21.** On macOS: `brew install openjdk@21` and `export JAVA_HOME=/opt/homebrew/opt/openjdk@21`. The Gradle wrapper is committed; Gradle itself is downloaded on first use. -- Node.js (already required by the workspace); the Kotlin build uses it for - its own tooling. +- Node.js on `PATH` (already required by the workspace); the Kotlin build and + the vendored SDK's `js` target use it for their own tooling. +- The `vendor/meshtastic-sdk` submodule (see "SDK version" below). ## Building @@ -66,8 +67,17 @@ meshtasticSdkVersion=0.2.1-spike-js-target-SNAPSHOT Until meshtastic-sdk publishes its `js` artifacts ([meshtastic/meshtastic-sdk#215](https://github.com/meshtastic/meshtastic-sdk/pull/215)), -`org.meshtastic:sdk-core-js` is resolved from `mavenLocal()`; publish it there -from a checkout of that PR with -`JAVA_HOME=/opt/homebrew/opt/openjdk@21 ./gradlew publishToMavenLocal`. -Switching to a Maven Central release is a one-line change to -`meshtasticSdkVersion`, plus dropping `mavenLocal()` from `settings.gradle.kts`. +the SDK compiles from source: `vendor/meshtastic-sdk` is a git submodule +pinned to that PR's head (`danditomaso/meshtastic-sdk`, branch +`feat/js-target`), and `settings.gradle.kts` includes it as a composite build, +substituting `org.meshtastic:sdk-core` and `sdk-testing` with the included +`:core` and `:testing` projects. No Maven repository, local or remote, serves +the SDK. `ensure-dist` and `build` run `git submodule update --init` when the +submodule is missing; a fresh clone can also use +`git clone --recurse-submodules`. CI checks it out with +`actions/checkout`'s `submodules: true`. + +Once #215 is released, the switch to Maven Central is: set +`meshtasticSdkVersion` to the release, delete the `includeBuild` block from +`settings.gradle.kts`, and remove the submodule +(`git rm vendor/meshtastic-sdk` and its `.gitmodules` entry). diff --git a/packages/sdk-kmp/gradle.properties b/packages/sdk-kmp/gradle.properties index d2cf4f359..3e6cb3374 100644 --- a/packages/sdk-kmp/gradle.properties +++ b/packages/sdk-kmp/gradle.properties @@ -2,6 +2,8 @@ org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8 org.gradle.caching=true org.gradle.configuration-cache=true kotlin.js.yarn=false -# Pinned meshtastic-sdk version. Switching to a Maven Central release is this one line -# (and dropping mavenLocal() from settings.gradle.kts). +# Pinned meshtastic-sdk version. Until meshtastic/meshtastic-sdk#215 is released the +# includeBuild in settings.gradle.kts substitutes it with the vendor/ submodule; after +# that, switching to the Maven Central release is this one line (plus deleting the +# submodule and the includeBuild block). meshtasticSdkVersion=0.2.1-spike-js-target-SNAPSHOT diff --git a/packages/sdk-kmp/scripts/build.mjs b/packages/sdk-kmp/scripts/build.mjs index c485af503..73228531a 100644 --- a/packages/sdk-kmp/scripts/build.mjs +++ b/packages/sdk-kmp/scripts/build.mjs @@ -13,6 +13,21 @@ if (process.argv.includes("--if-missing") && existsSync(entry)) { process.exit(0); } +const sdkSource = path.join(root, "vendor/meshtastic-sdk/settings.gradle.kts"); +if (!existsSync(sdkSource)) { + const submodule = spawnSync( + "git", + ["submodule", "update", "--init", "--", "vendor/meshtastic-sdk"], + { cwd: root, stdio: "inherit" }, + ); + if (submodule.error || submodule.status !== 0 || !existsSync(sdkSource)) { + console.error( + "@meshtastic/sdk-kmp: could not check out vendor/meshtastic-sdk; run `git submodule update --init` and retry.", + ); + process.exit(submodule.status ?? 1); + } +} + const env = { ...process.env }; const homebrewJdk = "/opt/homebrew/opt/openjdk@21"; if (!env.JAVA_HOME && existsSync(homebrewJdk)) { @@ -36,8 +51,8 @@ if (result.error || result.status !== 0) { [ "", "@meshtastic/sdk-kmp: the Gradle build failed.", - "It needs JDK 21 (set JAVA_HOME, e.g. /opt/homebrew/opt/openjdk@21 on macOS) and", - "org.meshtastic:sdk-core-js in a reachable Maven repository; see packages/sdk-kmp/README.md.", + "It needs JDK 21 (set JAVA_HOME, e.g. /opt/homebrew/opt/openjdk@21 on macOS), Node on", + "PATH and the vendor/meshtastic-sdk submodule checked out; see packages/sdk-kmp/README.md.", "", ].join("\n"), ); diff --git a/packages/sdk-kmp/settings.gradle.kts b/packages/sdk-kmp/settings.gradle.kts index 5b09248a4..0dc7bcb8f 100644 --- a/packages/sdk-kmp/settings.gradle.kts +++ b/packages/sdk-kmp/settings.gradle.kts @@ -12,10 +12,20 @@ dependencyResolutionManagement { repositories { mavenCentral() google() - // Until meshtastic-sdk publishes its js artifacts (meshtastic/meshtastic-sdk#215), - // sdk-core-js comes from `./gradlew publishToMavenLocal` in that repo. - mavenLocal() } } rootProject.name = "sdk-kmp" + +// Until meshtastic-sdk publishes its js artifacts (meshtastic/meshtastic-sdk#215), +// the SDK compiles from source out of the pinned submodule in vendor/. Once a release +// carries them, delete the submodule and this block, and resolve meshtasticSdkVersion +// from Maven Central. +includeBuild("vendor/meshtastic-sdk") { + dependencySubstitution { + substitute(module("org.meshtastic:sdk-core")).using(project(":core")) + substitute(module("org.meshtastic:sdk-core-js")).using(project(":core")) + substitute(module("org.meshtastic:sdk-testing")).using(project(":testing")) + substitute(module("org.meshtastic:sdk-testing-js")).using(project(":testing")) + } +} diff --git a/packages/sdk-kmp/vendor/meshtastic-sdk b/packages/sdk-kmp/vendor/meshtastic-sdk new file mode 160000 index 000000000..7d2128966 --- /dev/null +++ b/packages/sdk-kmp/vendor/meshtastic-sdk @@ -0,0 +1 @@ +Subproject commit 7d212896682d165ae227314cf6f01f9801ada42b From a725f7a23623b2312ee8eec74e100cf7d263ce2b Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 10:09:39 -0500 Subject: [PATCH 21/49] fix(web): connection lifecycle over the Kotlin SDK Connecting again on a connection whose client is still live, or on another connection while one is live, now disconnects that client first, so a serial port or HTTP poller is never held by a session the app no longer reads. A reconnect cycle that the SDK reports as a lost Local Network Access permission ends at once: denied is a terminal error with the site-info guidance, a dismissed prompt leaves the connection disconnected until the next click. The SDK's storage and the web's repositories now share one open outcome, so when the sqlocal database fails or times out both run in memory and the connect still goes through. A lockdown handshake cycle no longer races a user Disconnect: a closed session skips the reconnect half of the cycle and disconnect waits for the cycle to settle. --- .../src/core/connections/repositories.test.ts | 60 +++++++++ apps/web/src/core/connections/repositories.ts | 29 ++-- apps/web/src/core/kmp/fakeClient.ts | 14 ++ apps/web/src/core/kmp/session.test.ts | 17 +++ apps/web/src/core/kmp/session.ts | 38 +++--- .../Connections/useConnections.kmp.test.ts | 124 +++++++++++++++++- .../src/pages/Connections/useConnections.ts | 66 ++++++++-- 7 files changed, 297 insertions(+), 51 deletions(-) create mode 100644 apps/web/src/core/connections/repositories.test.ts diff --git a/apps/web/src/core/connections/repositories.test.ts b/apps/web/src/core/connections/repositories.test.ts new file mode 100644 index 000000000..a254f3987 --- /dev/null +++ b/apps/web/src/core/connections/repositories.test.ts @@ -0,0 +1,60 @@ +import { createMemoryDb } from "@core/storage/memoryDb.ts"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { openRepositories } from "./repositories.ts"; + +const storage = vi.hoisted( + (): { open?: () => Promise<{ db: unknown; persistent: boolean }> } => ({}), +); + +vi.mock("@core/sdkStorage.ts", () => ({ + getStorageDb: () => { + if (!storage.open) throw new Error("unscripted"); + return storage.open(); + }, + coordinator: undefined, +})); + +describe("openRepositories", () => { + afterEach(() => { + vi.useRealTimers(); + }); + + it("hands the SDK the same database the repositories use", async () => { + const db = await createMemoryDb(); + storage.open = async () => ({ db, persistent: true }); + + const opened = await openRepositories(42); + + expect(opened.persistent).toBe(true); + expect(opened.sdkStorage).toBeDefined(); + expect(opened.options.messages).toBeDefined(); + const activated = await opened.sdkStorage?.activate("http:radio"); + expect(activated).toBeDefined(); + }); + + it("leaves the SDK in memory when the open fails", async () => { + storage.open = async () => { + throw new Error("OPFS unavailable"); + }; + + const opened = await openRepositories(42); + + expect(opened).toEqual({ + persistent: false, + sdkStorage: undefined, + options: {}, + }); + }); + + it("leaves the SDK in memory when the open hangs past the timeout", async () => { + vi.useFakeTimers(); + storage.open = () => new Promise(() => {}); + + const pending = openRepositories(42); + await vi.advanceTimersByTimeAsync(5_000); + const opened = await pending; + + expect(opened.persistent).toBe(false); + expect(opened.sdkStorage).toBeUndefined(); + }); +}); diff --git a/apps/web/src/core/connections/repositories.ts b/apps/web/src/core/connections/repositories.ts index 5d22d7d5b..96dcb9f5d 100644 --- a/apps/web/src/core/connections/repositories.ts +++ b/apps/web/src/core/connections/repositories.ts @@ -28,28 +28,20 @@ const STORAGE_OPEN_TIMEOUT_MS = 5000; export const UNKNOWN_NODE_SCOPE = -1; /** - * The SDK's own storage (node DB, config bundle, channels, heartbeats) over - * the same DB and key. Opening fails loudly: the SDK then reports storage - * as degraded and runs the session in memory. - */ -export function sdkStorage(nodeNum?: number): StorageJs { - return sqlocalStorage( - async () => (await getStorageDb()).db, - nodeNum ?? UNKNOWN_NODE_SCOPE, - ); -} - -/** - * Opens the message, draft, node and telemetry repositories against the + * Opens the message, draft, node and telemetry repositories, and the SDK's + * own storage (node DB, config bundle, channels, heartbeats), against the * shared OPFS-backed SQLite DB, scoped to `nodeNum` (the node this * connection reached last time) so every connection to the same radio * shares one history. If sqlocal is unavailable, hangs longer than * `STORAGE_OPEN_TIMEOUT_MS`, or fails, the session runs without - * persistence and `persistent` is false. + * persistence, `persistent` is false and `sdkStorage` is undefined so the + * SDK keeps its state in memory too. */ -export async function openRepositories( - nodeNum?: number, -): Promise<{ options: SessionOptions; persistent: boolean }> { +export async function openRepositories(nodeNum?: number): Promise<{ + options: SessionOptions; + persistent: boolean; + sdkStorage: StorageJs | undefined; +}> { const scope = nodeNum ?? UNKNOWN_NODE_SCOPE; try { const t0 = Date.now(); @@ -73,6 +65,7 @@ export async function openRepositories( }); return { persistent, + sdkStorage: sqlocalStorage(async () => db, scope), options: { messages: new SqlocalMessageRepository(db, { deviceId: scope, @@ -90,6 +83,6 @@ export async function openRepositories( name: err instanceof Error ? err.name : undefined, message: err instanceof Error ? err.message : String(err), }); - return { persistent: false, options: {} }; + return { persistent: false, sdkStorage: undefined, options: {} }; } } diff --git a/apps/web/src/core/kmp/fakeClient.ts b/apps/web/src/core/kmp/fakeClient.ts index c99de1ba8..2e03ce062 100644 --- a/apps/web/src/core/kmp/fakeClient.ts +++ b/apps/web/src/core/kmp/fakeClient.ts @@ -78,6 +78,10 @@ export class FakeKmpClient implements MeshtasticClient { readonly packets: Uint8Array[] = []; readonly requests: Array<{ kind: string; nodeNum: number }> = []; readonly disconnects: number[] = []; + readonly connects: number[] = []; + /** When set, `disconnect` resolves only when `settleDisconnects` is called. */ + holdDisconnects = false; + private readonly pendingDisconnects: Array<() => void> = []; readonly admins = new Map(); /** Outcome every send resolves with; `settleSends` resolves the pending ones. */ sendOutcome: Omit = { ok: true, reason: null }; @@ -95,14 +99,24 @@ export class FakeKmpClient implements MeshtasticClient { private telemetryListeners = new Map>(); async connect(): Promise { + this.connects.push(Date.now()); this.setState(state("connected")); } async disconnect(): Promise { this.disconnects.push(Date.now()); + if (this.holdDisconnects) { + await new Promise((resolve) => + this.pendingDisconnects.push(resolve), + ); + } this.setState(state("disconnected")); } + settleDisconnects(): void { + for (const resolve of this.pendingDisconnects.splice(0)) resolve(); + } + onConnectionState(cb: (s: ConnectionStateJs) => void): () => void { this.stateListeners.add(cb); cb(this.connectionState); diff --git a/apps/web/src/core/kmp/session.test.ts b/apps/web/src/core/kmp/session.test.ts index 8f4a98c06..4cf56aed4 100644 --- a/apps/web/src/core/kmp/session.test.ts +++ b/apps/web/src/core/kmp/session.test.ts @@ -389,6 +389,23 @@ describe("MeshSession", () => { await Promise.resolve(); expect(kmp.disconnects).toHaveLength(1); }); + + it("does not reconnect when closed and disconnected during a handshake cycle", async () => { + const { kmp, session } = connected(); + kmp.holdDisconnects = true; + const cycle = session.rehandshake(); + expect(kmp.disconnects).toHaveLength(1); + + session.close(); + const closing = session.disconnect(); + kmp.holdDisconnects = false; + kmp.settleDisconnects(); + await cycle; + await closing; + + expect(kmp.connects).toHaveLength(0); + expect(kmp.connectionState.kind).toBe("disconnected"); + }); }); describe("validateIncomingNode", () => { diff --git a/apps/web/src/core/kmp/session.ts b/apps/web/src/core/kmp/session.ts index 40e85373a..699d3436c 100644 --- a/apps/web/src/core/kmp/session.ts +++ b/apps/web/src/core/kmp/session.ts @@ -137,7 +137,8 @@ export class MeshSession { }); private readonly regionUnset = signal(false); private readonly unsubscribes: Array<() => void> = []; - private rehandshaking = false; + private closed = false; + private rehandshaking: Promise | undefined; constructor( readonly kmp: MeshtasticClient, @@ -198,11 +199,6 @@ export class MeshSession { return this.device.myNodeNum.peek() ?? this.kmp.myNodeNum ?? 0; } - /** True while a deliberate disconnect/connect cycle is running. */ - get isRehandshaking(): boolean { - return this.rehandshaking; - } - sendAdmin( variant: AdminVariant, dest?: number, @@ -297,23 +293,31 @@ export class MeshSession { if (!outcome.ok) throw new Error(outcome.reason ?? "factory reset failed"); } - /** Runs the handshake again by cycling the SDK connection. */ - async rehandshake(): Promise { - this.rehandshaking = true; - try { - await this.kmp.disconnect(); - await this.kmp.connect(); - } finally { - this.rehandshaking = false; - } + /** + * Runs the handshake again by cycling the SDK connection. A session + * closed while the cycle is under way stays disconnected. + */ + rehandshake(): Promise { + this.rehandshaking ??= (async () => { + try { + await this.kmp.disconnect(); + if (!this.closed) await this.kmp.connect(); + } finally { + this.rehandshaking = undefined; + } + })(); + return this.rehandshaking; } - disconnect(): Promise { - return this.kmp.disconnect(); + /** Disconnects the SDK client once any handshake cycle has settled. */ + async disconnect(): Promise { + await this.rehandshaking?.catch(() => {}); + await this.kmp.disconnect(); } /** Stops feeding the session; the SDK client is left to its owner. */ close(): void { + this.closed = true; for (const off of this.unsubscribes.splice(0)) off(); } diff --git a/apps/web/src/pages/Connections/useConnections.kmp.test.ts b/apps/web/src/pages/Connections/useConnections.kmp.test.ts index abf52962f..9f97bbc6c 100644 --- a/apps/web/src/pages/Connections/useConnections.kmp.test.ts +++ b/apps/web/src/pages/Connections/useConnections.kmp.test.ts @@ -4,12 +4,18 @@ import type { Connection } from "@app/core/stores/deviceStore/types"; import { meshRegistry } from "@core/kmp/registry.ts"; import { useDeviceStore } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; +import type { StorageJs } from "@meshtastic/sdk-kmp"; import { act, renderHook } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { useConnections } from "./useConnections.ts"; const kmp = vi.hoisted( - (): { client?: FakeKmpClient; connectError?: Error } => ({}), + (): { + client?: FakeKmpClient; + clients: FakeKmpClient[]; + storages: Array; + connectError?: Error; + } => ({ clients: [], storages: [] }), ); vi.mock("@core/sdkStorage.ts", () => ({ @@ -22,7 +28,12 @@ vi.mock("@core/sdkStorage.ts", () => ({ vi.mock("@core/kmp/client.ts", async () => { const { FakeKmpClient } = await import("@core/kmp/fakeClient.ts"); return { - createHttpClient: async () => { + createHttpClient: async ( + _url: string, + _allowPrompt: boolean, + storage?: StorageJs, + ) => { + kmp.storages.push(storage); const client = new FakeKmpClient(); if (kmp.connectError) { const error = kmp.connectError; @@ -31,6 +42,7 @@ vi.mock("@core/kmp/client.ts", async () => { }; } kmp.client = client; + kmp.clients.push(client); return client; }, }; @@ -59,9 +71,22 @@ function named(name: string): Error { describe("useConnections over the Kotlin SDK (HTTP)", () => { beforeEach(() => { kmp.client = undefined; + kmp.clients = []; + kmp.storages = []; kmp.connectError = undefined; + useDeviceStore.setState({ savedConnections: [] }); }); + const addRadio = ( + result: { current: ReturnType }, + name = "Radio", + ) => + result.current.addConnection({ + type: "http", + name, + url: `http://192.168.1.${name.length}`, + }); + it("connects through the SDK and reads the handshake it ran", async () => { const { result } = renderHook(() => useConnections()); const conn = result.current.addConnection({ @@ -116,6 +141,101 @@ describe("useConnections over the Kotlin SDK (HTTP)", () => { }); }); + it("disconnects the old client before connecting the same connection again", async () => { + const { result } = renderHook(() => useConnections()); + const conn = addRadio(result); + await act(() => result.current.connect(conn.id)); + const first = kmp.clients[0]; + if (!first) throw new Error("no client created"); + + act(() => result.current.syncConnectionStatuses()); + act(() => + useDeviceStore + .getState() + .updateSavedConnection(conn.id, { status: "disconnected" }), + ); + await act(() => result.current.connect(conn.id)); + + expect(kmp.clients).toHaveLength(2); + expect(first.disconnects).toHaveLength(1); + expect(meshRegistry.get(conn.id)?.kmp).toBe(kmp.clients[1]); + }); + + it("tears down the session on another connection before connecting", async () => { + const { result } = renderHook(() => useConnections()); + const a = addRadio(result, "A"); + const b = addRadio(result, "Bee"); + await act(() => result.current.connect(a.id)); + const clientA = kmp.clients[0]; + if (!clientA) throw new Error("no client created"); + + await act(() => result.current.connect(b.id)); + + expect(clientA.disconnects).toHaveLength(1); + expect(saved(a.id)?.status).toBe("disconnected"); + expect(saved(b.id)?.status).toBe("configured"); + }); + + it("stops reconnecting when the local network permission is revoked", async () => { + const { result } = renderHook(() => useConnections()); + const conn = addRadio(result); + await act(() => result.current.connect(conn.id)); + const client = kmp.client; + if (!client) throw new Error("no client created"); + + await act(async () => { + client.setState( + state("reconnecting", { + attempt: 1, + error: "Local network access denied", + errorKind: "lna-denied", + }), + ); + }); + + expect(saved(conn.id)).toMatchObject({ + status: "error", + errorKind: "lna-denied", + reconnect: undefined, + }); + expect(client.disconnects).toHaveLength(1); + + await act(async () => { + client.setState(state("reconnecting", { attempt: 2 })); + client.setState(state("disconnected")); + }); + expect(saved(conn.id)?.status).toBe("error"); + expect(saved(conn.id)?.errorKind).toBe("lna-denied"); + }); + + it("stays disconnected when the local network prompt was dismissed mid-session", async () => { + const { result } = renderHook(() => useConnections()); + const conn = addRadio(result); + await act(() => result.current.connect(conn.id)); + const client = kmp.client; + if (!client) throw new Error("no client created"); + + await act(async () => { + client.setState( + state("reconnecting", { attempt: 1, errorKind: "lna-prompt" }), + ); + }); + + expect(saved(conn.id)).toMatchObject({ + status: "disconnected", + reconnect: undefined, + }); + expect(client.disconnects).toHaveLength(1); + }); + + it("runs the SDK in memory when the web's storage could not be opened", async () => { + const { result } = renderHook(() => useConnections()); + const conn = addRadio(result); + await act(() => result.current.connect(conn.id)); + + expect(kmp.storages).toEqual([undefined]); + }); + it("marks a denied Local Network Access permission as a terminal error", async () => { kmp.connectError = named("lna-denied"); const { result } = renderHook(() => useConnections()); diff --git a/apps/web/src/pages/Connections/useConnections.ts b/apps/web/src/pages/Connections/useConnections.ts index 602742f84..4819f740f 100644 --- a/apps/web/src/pages/Connections/useConnections.ts +++ b/apps/web/src/pages/Connections/useConnections.ts @@ -10,7 +10,6 @@ import { } from "@app/core/connections/browserDevices.ts"; import { openRepositories, - sdkStorage, UNKNOWN_NODE_SCOPE, } from "@app/core/connections/repositories.ts"; import type { @@ -28,6 +27,7 @@ import { createSerialClient, type MeshtasticClient, type SerialTarget, + type StorageJs, } from "@core/kmp/client.ts"; import { editorFor } from "@core/kmp/configEditorIo.ts"; import { @@ -205,9 +205,15 @@ export function useConnections() { * this connection reached last time. */ const connectThroughKmp = useCallback( - async (id: ConnectionId, makeClient: () => Promise) => { - const client = await makeClient(); + async ( + id: ConnectionId, + makeClient: (storage?: StorageJs) => Promise, + ) => { const conn = savedConnection(id); + const { options, persistent, sdkStorage } = await openRepositories( + conn?.nodeNum, + ); + const client = await makeClient(sdkStorage); let deviceId = conn?.meshDeviceId; if (deviceId && !useDeviceStore.getState().getDevice(deviceId)) { deviceId = undefined; @@ -215,7 +221,6 @@ export function useConnections() { deviceId = deviceId ?? randId(); const device = addDevice(deviceId); - const { options, persistent } = await openRepositories(conn?.nodeNum); if (!persistent) { toast({ title: t("toasts.storageUnavailable", { ns: "connections" }), @@ -228,9 +233,9 @@ export function useConnections() { const session = new MeshSession(client, options); // Replace any session left from an earlier attempt, so the app reads - // this session's state rather than the dead one's. - sessionTeardowns.get(id)?.(); - meshRegistry.get(id)?.close(); + // this session's state rather than the dead one's, and its client + // releases the port before this one opens it. + await teardown(id); meshRegistry.unregister(id); meshRegistry.register(id, session); meshRegistry.setActive(id); @@ -249,6 +254,21 @@ export function useConnections() { session.events.onConnectionState.subscribe((state) => { if (!savedConnection(id)) return; const reconnect = reconnectAttempt(state); + if ( + reconnect && + (state.errorKind === "lna-denied" || + state.errorKind === "lna-prompt") + ) { + log.warn("kmp: local network access lost", { id, ...reconnect }); + void teardown(id); + const cause = new Error(state.error ?? ""); + cause.name = state.errorKind; + updateSavedConnection(id, { + ...connectFailure(cause), + reconnect: undefined, + }); + return; + } if (reconnect) { reconnecting = true; log.warn("kmp: reconnecting", { id, ...reconnect }); @@ -339,6 +359,7 @@ export function useConnections() { addDevice, setSelectedDevice, setActiveConnectionId, + teardown, updateSavedConnection, updateStatus, ], @@ -365,23 +386,40 @@ export function useConnections() { allowPrompt: !!opts?.allowPrompt, }); updateStatus(id, "connecting"); + // The app follows one radio at a time: a session still live on + // another connection would keep its port and poller to itself. + for (const other of [...sessionTeardowns.keys()]) { + if (other === id) continue; + await teardown(other); + const otherDevice = savedConnection(other)?.meshDeviceId; + if (otherDevice) { + useDeviceStore + .getState() + .getDevice(otherDevice) + ?.setConnectionId(null); + } + updateSavedConnection(other, { + status: "disconnected", + error: undefined, + }); + } const allowPrompt = opts?.allowPrompt ?? false; try { switch (conn.type) { case "http": - return await connectThroughKmp(id, () => - createHttpClient(conn.url, allowPrompt, sdkStorage(conn.nodeNum)), + return await connectThroughKmp(id, (storage) => + createHttpClient(conn.url, allowPrompt, storage), ); case "serial": { const target = await serialTarget(conn, allowPrompt); - return await connectThroughKmp(id, () => - createSerialClient(target, sdkStorage(conn.nodeNum)), + return await connectThroughKmp(id, (storage) => + createSerialClient(target, storage), ); } case "bluetooth": { const target = await bluetoothTarget(conn, allowPrompt); - return await connectThroughKmp(id, () => - createBluetoothClient(target, sdkStorage(conn.nodeNum)), + return await connectThroughKmp(id, (storage) => + createBluetoothClient(target, storage), ); } } @@ -395,7 +433,7 @@ export function useConnections() { return false; } }, - [updateStatus, updateSavedConnection, connectThroughKmp], + [updateStatus, updateSavedConnection, connectThroughKmp, teardown], ); const disconnect = useCallback( From ca516000528f4535bb2f9576f24db7dea2d23ec2 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 10:10:56 -0500 Subject: [PATCH 22/49] fix(sdk-kmp): transport hygiene for reconnects A poll failure with the Local Network Access permission revoked is a non-recoverable transport error, so the SDK stops instead of retrying ten times against a permission only the user can restore. The serial transport removes its navigator.serial listeners on disconnect and on a failed connect; each connect used to add a pair for the page's lifetime. Every transport discards the frames the old link queued when it disconnects, so a reconnect's handshake starts clean. Bluetooth reads and writes take turns behind one mutex, because Chrome rejects overlapping GATT operations on a device. --- .../org/meshtastic/sdk/js/HttpTransport.kt | 10 ++- .../sdk/js/WebBluetoothTransport.kt | 25 ++++-- .../meshtastic/sdk/js/WebSerialTransport.kt | 20 ++++- .../meshtastic/sdk/js/HttpTransportTest.kt | 76 +++++++++++++++++++ .../sdk/js/WebBluetoothTransportTest.kt | 53 ++++++++++++- .../sdk/js/WebSerialTransportTest.kt | 41 +++++++++- 6 files changed, 210 insertions(+), 15 deletions(-) create mode 100644 packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/HttpTransportTest.kt diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/HttpTransport.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/HttpTransport.kt index b4b4cf1c8..be7daaa3d 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/HttpTransport.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/HttpTransport.kt @@ -55,7 +55,8 @@ internal class HttpTransport( } catch (e: CancellationException) { throw e } catch (e: Throwable) { - _state.value = TransportState.Error(Lna.classify(baseUrl, e), recoverable = true) + val cause = Lna.classify(baseUrl, e) + _state.value = TransportState.Error(cause, recoverable = cause.kind() != Lna.DENIED) return@launch } delay(pollMillis) @@ -76,6 +77,7 @@ internal class HttpTransport( override suspend fun disconnect() { scope?.cancel() scope = null + discardQueued() _state.value = TransportState.Disconnected } @@ -88,6 +90,12 @@ internal class HttpTransport( override fun frames(): Flow = inbound.receiveAsFlow() + /** Frames the old link queued after the engine stopped reading must not reach the next handshake. */ + private fun discardQueued() { + while (inbound.tryReceive().isSuccess) { + } + } + private suspend fun request(url: String, method: String): dynamic { val response = fetch(url, Lna.requestInit(baseUrl, method)).await() if (response.ok != true) throw ClientException("transport", "$method ${response.status}") diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebBluetoothTransport.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebBluetoothTransport.kt index fc91989f4..ca8a5a896 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebBluetoothTransport.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebBluetoothTransport.kt @@ -13,6 +13,8 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import org.khronos.webgl.ArrayBuffer import org.khronos.webgl.Uint8Array import org.meshtastic.sdk.Frame @@ -45,6 +47,8 @@ internal class WebBluetoothTransport( private var fromRadio: dynamic = null private var fromNum: dynamic = null private var closing = false + /** Chrome rejects overlapping GATT operations on one device, so reads and writes take turns. */ + private val gatt = Mutex() private var draining = false private var drainWanted = false @@ -99,6 +103,7 @@ internal class WebBluetoothTransport( scope?.cancel() scope = null release() + discardQueued() _state.value = TransportState.Disconnected } @@ -107,12 +112,14 @@ internal class WebBluetoothTransport( val payload = payloadOf(frame).toUint8Array() val buffer: ArrayBuffer = payload.buffer.slice(payload.byteOffset, payload.byteOffset + payload.length) try { - val write = if (characteristic.writeValueWithResponse != null) { - characteristic.writeValueWithResponse(buffer) - } else { - characteristic.writeValue(buffer) + gatt.withLock { + val write = if (characteristic.writeValueWithResponse != null) { + characteristic.writeValueWithResponse(buffer) + } else { + characteristic.writeValue(buffer) + } + (write as Promise).await() } - (write as Promise).await() } catch (e: Throwable) { dropped(e.message ?: "Bluetooth write failed") throw ClientException("transport", e.message ?: "Bluetooth write failed") @@ -122,6 +129,12 @@ internal class WebBluetoothTransport( override fun frames(): Flow = inbound.receiveAsFlow() + /** Frames the old link queued after the engine stopped reading must not reach the next handshake. */ + private fun discardQueued() { + while (inbound.tryReceive().isSuccess) { + } + } + private suspend fun findDevice(bluetooth: dynamic): dynamic { val id = wantedId ?: return null if (bluetooth.getDevices == null) return null @@ -160,7 +173,7 @@ internal class WebBluetoothTransport( drainWanted = false while (!closing) { val characteristic = fromRadio ?: return - val value = (characteristic.readValue() as Promise).await() + val value = gatt.withLock { (characteristic.readValue() as Promise).await() } if (value.byteLength == 0) break val bytes = Uint8Array(value.buffer as ArrayBuffer, value.byteOffset as Int, value.byteLength as Int) inbound.trySend(Frame(framed(bytes.toByteArray()))) diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebSerialTransport.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebSerialTransport.kt index f43fcf710..a60e897fb 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebSerialTransport.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebSerialTransport.kt @@ -73,10 +73,8 @@ internal class WebSerialTransport( serial.addEventListener("connect", onOsConnect) listening = true } - } catch (e: CancellationException) { - _state.value = TransportState.Disconnected - throw e } catch (e: Throwable) { + stopListening() _state.value = TransportState.Disconnected throw e } @@ -88,10 +86,20 @@ internal class WebSerialTransport( closing = true scope?.cancel() scope = null + stopListening() release() + discardQueued() _state.value = TransportState.Disconnected } + private fun stopListening() { + if (!listening) return + listening = false + val serial = serialApi() ?: return + serial.removeEventListener("disconnect", onOsDisconnect) + serial.removeEventListener("connect", onOsConnect) + } + override suspend fun send(frame: Frame) { val w = writer ?: throw ClientException("transport", "Serial port is not open") try { @@ -104,6 +112,12 @@ internal class WebSerialTransport( override fun frames(): Flow = inbound.receiveAsFlow() + /** Frames the old link queued after the engine stopped reading must not reach the next handshake. */ + private fun discardQueued() { + while (inbound.tryReceive().isSuccess) { + } + } + private fun matches(candidate: dynamic): Boolean { if (usbVendorId == null || usbProductId == null) return false val info = try { diff --git a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/HttpTransportTest.kt b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/HttpTransportTest.kt new file mode 100644 index 000000000..a46b7d198 --- /dev/null +++ b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/HttpTransportTest.kt @@ -0,0 +1,76 @@ +package org.meshtastic.sdk.js + +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.promise +import kotlinx.coroutines.withTimeout +import org.meshtastic.sdk.TransportState +import kotlin.js.Promise +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Drives the transport over a scripted `fetch` on an https page, with the + * Local Network Access permission answered by a scripted `navigator`. + */ +class HttpTransportTest { + @AfterTest + fun restore() { + js("delete globalThis.navigator; delete globalThis.window; delete globalThis.fetch; delete globalThis.isSecureContext") + } + + private fun installPage(permission: () -> String) { + val navigator = js("({ permissions: {} })") + navigator.permissions.query = { _: dynamic -> + val status = js("({})") + status.state = permission() + Promise.resolve(status) + } + js("Object.defineProperty(globalThis, 'navigator', { value: navigator, configurable: true, writable: true })") + js("globalThis.window = { location: { protocol: 'https:' } }; globalThis.isSecureContext = true") + } + + private fun installFetch(pollFails: Boolean) { + val fetch: (String, dynamic) -> Promise = { url, init -> + if (init.method == "GET" && pollFails) { + Promise.reject(js("new TypeError('Failed to fetch')")) + } else { + val response = js("({ ok: true, status: 200 })") + response.arrayBuffer = { Promise.resolve(js("new ArrayBuffer(0)")) } + Promise.resolve(response) + } + } + js("globalThis.fetch = fetch") + } + + private suspend fun pollErrorWith(permissionAfterFailure: String): TransportState.Error { + var polled = false + installPage { if (polled) permissionAfterFailure else "granted" } + installFetch(pollFails = true) + val transport = HttpTransport("http://192.168.1.10", allowPrompt = false, pollMillis = 10) + transport.connect() + polled = true + val error = withTimeout(1_000) { transport.state.first { it is TransportState.Error } } as TransportState.Error + transport.disconnect() + return error + } + + @Test + fun a_poll_failure_with_the_permission_revoked_is_not_recoverable() = GlobalScope.promise { + val error = pollErrorWith("denied") + + assertEquals(Lna.DENIED, error.cause.kind()) + assertFalse(error.recoverable) + } + + @Test + fun a_poll_failure_with_the_permission_granted_is_recoverable() = GlobalScope.promise { + val error = pollErrorWith("granted") + + assertEquals("transport", error.cause.kind()) + assertTrue(error.recoverable) + } +} diff --git a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebBluetoothTransportTest.kt b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebBluetoothTransportTest.kt index ac8a04e5f..9c1891fe4 100644 --- a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebBluetoothTransportTest.kt +++ b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebBluetoothTransportTest.kt @@ -1,6 +1,8 @@ package org.meshtastic.sdk.js import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.withTimeoutOrNull import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.take import kotlinx.coroutines.flow.toList @@ -42,10 +44,18 @@ class WebBluetoothTransportTest { return bluetooth } - private fun fakeDevice(id: String, hasService: Boolean = true): dynamic { + private fun fakeDevice(id: String, hasService: Boolean = true, gattMillis: Int = 0): dynamic { val device = js( """({ - listeners: {}, queued: [], written: [], connects: 0, notifying: false, + listeners: {}, queued: [], written: [], connects: 0, notifying: false, busy: 0, overlaps: 0, + gatt_: function (work) { + var self = this; + if (self.busy > 0) self.overlaps++; + self.busy++; + return new Promise(function (resolve) { + setTimeout(function () { self.busy--; resolve(work()); }, self.gattMillis); + }); + }, addEventListener: function (type, cb) { (this.listeners[type] = this.listeners[type] || []).push(cb); }, removeEventListener: function () {}, dispatch: function (type) { (this.listeners[type] || []).forEach(function (cb) { cb({}); }); }, @@ -53,12 +63,13 @@ class WebBluetoothTransportTest { })""", ) device.id = id + device.gattMillis = gattMillis val chars = js("({})") chars.fromradio = js( - """({ readValue: function () { var next = device.queued.shift(); return Promise.resolve(new DataView(next ? next.buffer : new ArrayBuffer(0))); } })""", + """({ readValue: function () { return device.gatt_(function () { var next = device.queued.shift(); return new DataView(next ? next.buffer : new ArrayBuffer(0)); }); } })""", ) chars.toradio = js( - """({ writeValueWithResponse: function (buffer) { device.written.push(new Uint8Array(buffer)); return Promise.resolve(); } })""", + """({ writeValueWithResponse: function (buffer) { return device.gatt_(function () { device.written.push(new Uint8Array(buffer)); }); } })""", ) chars.fromnum = js( """({ @@ -184,6 +195,40 @@ class WebBluetoothTransportTest { transport.disconnect() } + @Test + fun a_send_during_a_drain_waits_for_the_read_in_flight() = GlobalScope.promise { + val radio = fakeDevice("radio-1", gattMillis = 20) + installBluetooth(arrayOf(radio)) + val transport = WebBluetoothTransport(null, "radio-1") + transport.connect() + + radio.queue(byteArrayOf(0x08, 0x01).toUint8Array()) + radio.dispatch("characteristicvaluechanged") + transport.send(Frame(framed(byteArrayOf(0x10)))) + withTimeout(1_000) { transport.frames().first() } + + assertEquals(1, radio.written.length as Int) + assertEquals(0, radio.overlaps as Int) + transport.disconnect() + } + + @Test + fun frames_queued_by_the_old_link_do_not_reach_the_next_connect() = GlobalScope.promise { + val radio = fakeDevice("radio-1") + installBluetooth(arrayOf(radio)) + val transport = WebBluetoothTransport(null, "radio-1") + transport.connect() + radio.queue(byteArrayOf(0x08, 0x01).toUint8Array()) + radio.dispatch("characteristicvaluechanged") + delay(50) + + transport.disconnect() + transport.connect() + + assertEquals(null, withTimeoutOrNull(100) { transport.frames().first() }) + transport.disconnect() + } + @Test fun a_gatt_disconnect_is_a_recoverable_error_and_the_same_device_reconnects() = GlobalScope.promise { val radio = fakeDevice("radio-1") diff --git a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebSerialTransportTest.kt b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebSerialTransportTest.kt index 72abd8c2f..5825fe2f2 100644 --- a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebSerialTransportTest.kt +++ b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebSerialTransportTest.kt @@ -2,6 +2,8 @@ package org.meshtastic.sdk.js import kotlinx.coroutines.flow.first import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.withTimeoutOrNull import kotlinx.coroutines.promise import kotlinx.coroutines.withTimeout import org.meshtastic.sdk.Frame @@ -34,7 +36,8 @@ class WebSerialTransportTest { requested: 0, listeners: {}, addEventListener: function (type, cb) { (this.listeners[type] = this.listeners[type] || []).push(cb); }, - removeEventListener: function () {}, + removeEventListener: function (type, cb) { this.listeners[type] = (this.listeners[type] || []).filter(function (l) { return l !== cb; }); }, + listenerCount: function () { var n = 0; for (var k in this.listeners) n += this.listeners[k].length; return n; }, dispatch: function (type, port) { (this.listeners[type] || []).forEach(function (cb) { cb({ target: port }); }); }, requestPort: function () { this.requested++; return Promise.reject(new Error('prompted')); } })""", @@ -173,6 +176,42 @@ class WebSerialTransportTest { transport.disconnect() } + @Test + fun releases_its_serial_listeners_on_disconnect_and_on_a_failed_connect() = GlobalScope.promise { + val radio = fakePort(0x303a, 0x1001) + val serial = installSerial(arrayOf(radio)) + val transport = WebSerialTransport(null, 0x303a, 0x1001) + + transport.connect() + assertEquals(2, serial.listenerCount() as Int) + transport.disconnect() + assertEquals(0, serial.listenerCount() as Int) + + transport.connect() + transport.disconnect() + assertEquals(0, serial.listenerCount() as Int) + + serial.ports = arrayOf() + assertFailsWith { WebSerialTransport(null, 0x303a, 0x1001).connect() } + assertEquals(0, serial.listenerCount() as Int) + } + + @Test + fun frames_read_by_the_old_link_do_not_reach_the_next_connect() = GlobalScope.promise { + val radio = fakePort(0x303a, 0x1001) + installSerial(arrayOf(radio)) + val transport = WebSerialTransport(null, 0x303a, 0x1001) + transport.connect() + radio.push(framed(byteArrayOf(0x08, 0x01)).toByteArray().toUint8Array()) + delay(50) + + transport.disconnect() + transport.connect() + + assertEquals(null, withTimeoutOrNull(100) { transport.frames().first() }) + transport.disconnect() + } + @Test fun a_port_left_open_is_closed_before_reopening() = GlobalScope.promise { val radio = fakePort(0x303a, 0x1001) From b4d85d17131d39f33c7dcae545d069765ecd9dda Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 10:15:57 -0500 Subject: [PATCH 23/49] refactor(web): drawer and facade cleanup after the SDK review A drop the SDK does not retry is reported by its cause rather than as ten exhausted attempts. A click on a saved serial or Bluetooth connection with no held handle opens the picker first, filtered to the saved ids, so the gesture is still live; automatic paths keep getPorts/getDevices. The node repository upserts in one multi-row statement per chunk, and the web no longer writes node rows the SDK's storage already writes (removals and resets remain). The connection probe skips a local HTTP target while the Local Network Access permission is still prompt, so opening the drawer never prompts. Dead code is gone: MeshRegistry.has, SqlocalDeviceStorage.currentScope, createSqlocalDb, and the facade's sendRaw, nodes, configBundle, channels, onConfigBundle and onChannels, mirrored in FakeKmpClient. --- .../core/connections/browserDevices.test.ts | 39 +++++++++++++++- .../src/core/connections/browserDevices.ts | 14 +++++- apps/web/src/core/connections/lna.ts | 37 +++++++++++++++ apps/web/src/core/kmp/fakeClient.ts | 46 ------------------- apps/web/src/core/kmp/nodes.ts | 6 +-- apps/web/src/core/kmp/registry.ts | 4 -- apps/web/src/core/storage/db.ts | 7 --- .../src/core/storage/deviceStorage.test.ts | 1 - apps/web/src/core/storage/deviceStorage.ts | 4 -- apps/web/src/core/storage/nodes.test.ts | 13 +++++- apps/web/src/core/storage/nodes.ts | 29 +++++++----- .../useConnections.devices.test.ts | 19 +++++--- .../Connections/useConnections.kmp.test.ts | 27 ++++++++++- .../src/pages/Connections/useConnections.ts | 38 ++++++++++----- .../kotlin/org/meshtastic/sdk/js/Client.kt | 26 ----------- 15 files changed, 185 insertions(+), 125 deletions(-) diff --git a/apps/web/src/core/connections/browserDevices.test.ts b/apps/web/src/core/connections/browserDevices.test.ts index a202c1a37..7295114e6 100644 --- a/apps/web/src/core/connections/browserDevices.test.ts +++ b/apps/web/src/core/connections/browserDevices.test.ts @@ -6,7 +6,7 @@ import { installSerial as installFakeSerial, uninstallBrowserDevices, } from "@app/tests/fakeBrowserDevices.ts"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { type BluetoothConnection, MESHTASTIC_BLE_SERVICE, @@ -59,6 +59,7 @@ function installBluetooth(ids: string[]) { afterEach(() => { uninstallBrowserDevices(); + vi.unstubAllGlobals(); }); describe("permittedSerialPort", () => { @@ -118,6 +119,42 @@ describe("pickers", () => { }); describe("probeConnection", () => { + const savedHttp: Connection = { + id: 3, + type: "http", + name: "Radio", + url: "http://192.168.1.10", + status: "disconnected", + createdAt: 0, + }; + + function installLocalNetworkPermission(state: string) { + vi.stubGlobal("location", { protocol: "https:" }); + vi.stubGlobal("isSecureContext", true); + vi.stubGlobal("navigator", { + permissions: { query: vi.fn().mockResolvedValue({ state }) }, + }); + const fetch = vi.fn().mockResolvedValue({ ok: true }); + vi.stubGlobal("fetch", fetch); + return fetch; + } + + it("does not fetch a local target while the local network permission would prompt", async () => { + const fetch = installLocalNetworkPermission("prompt"); + await expect(probeConnection(savedHttp)).resolves.toEqual({ + status: "disconnected", + }); + expect(fetch).not.toHaveBeenCalled(); + }); + + it("probes a local target once the permission is granted", async () => { + const fetch = installLocalNetworkPermission("granted"); + await expect(probeConnection(savedHttp)).resolves.toEqual({ + status: "online", + }); + expect(fetch).toHaveBeenCalledTimes(1); + }); + it("reports a permitted serial port as online", async () => { installSerial([fakePort(ids)]); await expect(probeConnection(savedSerial)).resolves.toEqual({ diff --git a/apps/web/src/core/connections/browserDevices.ts b/apps/web/src/core/connections/browserDevices.ts index 614ab871c..4df1a1451 100644 --- a/apps/web/src/core/connections/browserDevices.ts +++ b/apps/web/src/core/connections/browserDevices.ts @@ -1,3 +1,7 @@ +import { + needsLocalNetworkAccess, + queryLocalNetworkAccess, +} from "@core/connections/lna.ts"; import type { Connection } from "@core/stores/deviceStore/types"; import { httpErrorMessage, testHttpReachable } from "@pages/Connections/utils"; @@ -115,11 +119,19 @@ export type ProbeResult = { /** * Probes a saved connection for reachability or permission without opening - * it, for the saved-connection status badges. + * it, for the saved-connection status badges. A local target whose Local + * Network Access permission is still `prompt` is left alone: only a click + * may trigger that prompt. */ export async function probeConnection(conn: Connection): Promise { switch (conn.type) { case "http": { + if ( + needsLocalNetworkAccess(conn.url) && + (await queryLocalNetworkAccess()) === "prompt" + ) { + return { status: "disconnected" }; + } const { reachable, certError } = await testHttpReachable(conn.url); if (reachable) { return { status: "online" }; diff --git a/apps/web/src/core/connections/lna.ts b/apps/web/src/core/connections/lna.ts index 29b9d3131..8fa4b28dc 100644 --- a/apps/web/src/core/connections/lna.ts +++ b/apps/web/src/core/connections/lna.ts @@ -19,6 +19,43 @@ export function withLocalNetworkTarget( return { ...init, targetAddressSpace: "local" }; } +/** True for a plain-HTTP local target from an HTTPS page, which Chrome gates behind Local Network Access. */ +export function needsLocalNetworkAccess(url: string): boolean { + return ( + url.startsWith("http:") && + globalThis.location?.protocol === "https:" && + !isLoopback(url) + ); +} + +export type LocalNetworkPermission = + | "granted" + | "denied" + | "prompt" + | "unsupported"; + +/** + * The page's Local Network Access permission, by the current name and the + * alias Chromium still accepts, or `unsupported` where the API is absent. + */ +export async function queryLocalNetworkAccess(): Promise { + const permissions: PermissionsByName | undefined = + globalThis.navigator?.permissions; + if (!globalThis.isSecureContext || !permissions) return "unsupported"; + for (const name of ["local-network", "local-network-access"]) { + try { + const { state } = await permissions.query({ name }); + return state; + } catch {} + } + return "unsupported"; +} + +/** `Permissions.query` for names newer than the DOM lib's `PermissionName`. */ +interface PermissionsByName { + query(descriptor: { name: string }): Promise; +} + function isLoopback(url: string): boolean { let host: string; try { diff --git a/apps/web/src/core/kmp/fakeClient.ts b/apps/web/src/core/kmp/fakeClient.ts index 2e03ce062..364e0ba4d 100644 --- a/apps/web/src/core/kmp/fakeClient.ts +++ b/apps/web/src/core/kmp/fakeClient.ts @@ -1,7 +1,6 @@ import type { AdminJs, AdminResultJs, - ConfigBundleJs, ConnectionStateJs, MeshtasticClient, NodeChangeJs, @@ -65,10 +64,6 @@ export class FakeAdmin implements AdminJs { export class FakeKmpClient implements MeshtasticClient { connectionState: ConnectionStateJs = state("disconnected"); myNodeNum: number | null = null; - configBundle: ConfigBundleJs | null = null; - channels: Uint8Array[] | null = null; - nodeList: Uint8Array[] = []; - readonly sent: Uint8Array[] = []; readonly texts: Array<{ text: string; to: number; @@ -92,8 +87,6 @@ export class FakeKmpClient implements MeshtasticClient { adminResult: AdminResultJs = adminOk(); private frameListeners: Listeners = new Set(); private stateListeners: Listeners = new Set(); - private bundleListeners: Listeners = new Set(); - private channelListeners: Listeners = new Set(); private nodeListeners: Listeners = new Set(); private packetListeners: Listeners = new Set(); private telemetryListeners = new Map>(); @@ -123,18 +116,6 @@ export class FakeKmpClient implements MeshtasticClient { return () => this.stateListeners.delete(cb); } - onConfigBundle(cb: (bundle: ConfigBundleJs | null) => void): () => void { - this.bundleListeners.add(cb); - cb(this.configBundle); - return () => this.bundleListeners.delete(cb); - } - - onChannels(cb: (channels: Uint8Array[] | null) => void): () => void { - this.channelListeners.add(cb); - cb(this.channels); - return () => this.channelListeners.delete(cb); - } - onNodeChange(cb: (change: NodeChangeJs) => void): () => void { this.nodeListeners.add(cb); return () => this.nodeListeners.delete(cb); @@ -157,10 +138,6 @@ export class FakeKmpClient implements MeshtasticClient { return () => this.frameListeners.delete(cb); } - async nodes(): Promise { - return this.nodeList; - } - admin(dest = 0): FakeAdmin { const existing = this.admins.get(dest); if (existing) return existing; @@ -223,15 +200,6 @@ export class FakeKmpClient implements MeshtasticClient { return this.adminResult; } - sendRaw(toRadio: Uint8Array): void { - if (this.connectionState.kind !== "connected") { - const error = new Error("Client not connected"); - error.name = "not-connected"; - throw error; - } - this.sent.push(toRadio); - } - emitFrame(bytes: Uint8Array): void { for (const cb of this.frameListeners) { cb(bytes); @@ -256,20 +224,6 @@ export class FakeKmpClient implements MeshtasticClient { } } - setConfigBundle(bundle: ConfigBundleJs | null): void { - this.configBundle = bundle; - for (const cb of this.bundleListeners) { - cb(bundle); - } - } - - setChannels(channels: Uint8Array[] | null): void { - this.channels = channels; - for (const cb of this.channelListeners) { - cb(channels); - } - } - setState(next: ConnectionStateJs): void { this.connectionState = next; for (const cb of this.stateListeners) { diff --git a/apps/web/src/core/kmp/nodes.ts b/apps/web/src/core/kmp/nodes.ts index 2657217e7..6a3c40c05 100644 --- a/apps/web/src/core/kmp/nodes.ts +++ b/apps/web/src/core/kmp/nodes.ts @@ -92,7 +92,9 @@ export interface NodesAdmin { /** * The device's node DB as the SDK reports it, plus the per-node errors the * web tracks (PKI collisions and routing failures) and the stored snapshot - * shown until the handshake's node DB arrives. + * shown until the handshake's node DB arrives. The SDK's storage writes + * every node column this reads, so nothing is written back here except + * removals and resets. */ export class NodesClient { private readonly nodes = signal>(new Map()); @@ -123,7 +125,6 @@ export class NodesClient { ); } this.nodes.value = next; - void this.repository?.upsertBatch([...next.values()]).catch(() => {}); return; } case "added": @@ -210,7 +211,6 @@ export class NodesClient { const next = new Map(this.nodes.peek()); next.set(node.num, node); this.nodes.value = next; - void this.repository?.upsert(node).catch(() => {}); } private delete(nodeNum: number): void { diff --git a/apps/web/src/core/kmp/registry.ts b/apps/web/src/core/kmp/registry.ts index c69b3a634..751e3915a 100644 --- a/apps/web/src/core/kmp/registry.ts +++ b/apps/web/src/core/kmp/registry.ts @@ -23,10 +23,6 @@ export class MeshRegistry { } } - has(id: number): boolean { - return this.sessions.has(id); - } - get(id: number): MeshSession | undefined { return this.sessions.get(id); } diff --git a/apps/web/src/core/storage/db.ts b/apps/web/src/core/storage/db.ts index cbf15b26a..40d53346b 100644 --- a/apps/web/src/core/storage/db.ts +++ b/apps/web/src/core/storage/db.ts @@ -50,13 +50,6 @@ export async function openSqlocalDb( return { db, storageType, persistent: storageType === "opfs" }; } -/** {@link openSqlocalDb} for callers that only need the Drizzle client. */ -export async function createSqlocalDb( - options: CreateSqlocalDbOptions = {}, -): Promise { - return (await openSqlocalDb(options)).db; -} - type RawSql = ( query: TemplateStringsArray, ...values: ReadonlyArray diff --git a/apps/web/src/core/storage/deviceStorage.test.ts b/apps/web/src/core/storage/deviceStorage.test.ts index 08ccdaeaa..c1013aaae 100644 --- a/apps/web/src/core/storage/deviceStorage.test.ts +++ b/apps/web/src/core/storage/deviceStorage.test.ts @@ -120,7 +120,6 @@ describe("SqlocalDeviceStorage", () => { await storage.saveNode(nodeInfo(1, "known")); expect(await unknown.loadNodes()).toEqual([]); await unknown.recordOwnNode(NODE, "2.8.3"); - expect(unknown.currentScope).toBe(NODE); expect((await unknown.loadNodes()).length).toBe(1); await unknown.clear(); diff --git a/apps/web/src/core/storage/deviceStorage.ts b/apps/web/src/core/storage/deviceStorage.ts index 05ebfe060..f1ffb8cd5 100644 --- a/apps/web/src/core/storage/deviceStorage.ts +++ b/apps/web/src/core/storage/deviceStorage.ts @@ -35,10 +35,6 @@ export class SqlocalDeviceStorage implements DeviceStorageJs { this.scope = scope; } - get currentScope(): number { - return this.scope; - } - async loadNodes(): Promise { const rows = await this.db .select() diff --git a/apps/web/src/core/storage/nodes.test.ts b/apps/web/src/core/storage/nodes.test.ts index 62abff359..231ff6f97 100644 --- a/apps/web/src/core/storage/nodes.test.ts +++ b/apps/web/src/core/storage/nodes.test.ts @@ -1,6 +1,6 @@ import { create } from "@bufbuild/protobuf"; import { Protobuf } from "@core/protobuf.ts"; -import { beforeEach, describe, expect, it } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import type { SqlocalDb } from "./db.ts"; import { createMemoryDb } from "./memoryDb.ts"; import { SqlocalNodesRepository } from "./nodes.ts"; @@ -61,6 +61,17 @@ describe("SqlocalNodesRepository", () => { expect(await repo.get(9)).toBeUndefined(); }); + it("upsertBatch writes every node in one statement", async () => { + await repo.upsert(node(2, { snr: 1 })); + const insert = vi.spyOn(db, "insert"); + + await repo.upsertBatch([node(1), node(2, { snr: 9 }), node(3)]); + + expect(insert).toHaveBeenCalledTimes(1); + expect((await repo.loadAll()).map((n) => n.num).sort()).toEqual([1, 2, 3]); + expect((await repo.get(2))?.snr).toBe(9); + }); + it("clear wipes all rows for the scoped device", async () => { await repo.upsertBatch([node(1), node(2), node(3)]); await repo.clear(); diff --git a/apps/web/src/core/storage/nodes.ts b/apps/web/src/core/storage/nodes.ts index f7c6d67a4..0de24fbd2 100644 --- a/apps/web/src/core/storage/nodes.ts +++ b/apps/web/src/core/storage/nodes.ts @@ -1,6 +1,6 @@ import { fromBinary, toBinary } from "@bufbuild/protobuf"; import { Protobuf } from "@core/protobuf.ts"; -import { and, eq } from "drizzle-orm"; +import { and, eq, sql } from "drizzle-orm"; import type { SqlocalDb } from "./db.ts"; import { nodes } from "./schema.ts"; import { @@ -14,6 +14,9 @@ export interface SqlocalNodesRepositoryOptions { deviceId: number; } +/** Rows per INSERT: 9 bound values each, well inside SQLite's variable limit. */ +const UPSERT_CHUNK = 500; + /** * Persists the snapshot of the device's NodeDB. user/position/metrics are * stored as base64-encoded protobuf bytes — round-trip safe across schema @@ -57,23 +60,25 @@ export class SqlocalNodesRepository implements NodesRepository { await this.upsertBatch([node]); } + /** One multi-row statement per chunk, so a large node DB is a few worker round trips, not one per node. */ async upsertBatch(input: ReadonlyArray): Promise { - if (input.length === 0) return; - for (const node of input) { - const row = nodeToRow(this.deviceId, node); + for (let i = 0; i < input.length; i += UPSERT_CHUNK) { + const rows = input + .slice(i, i + UPSERT_CHUNK) + .map((node) => nodeToRow(this.deviceId, node)); await this.db .insert(nodes) - .values(row) + .values(rows) .onConflictDoUpdate({ target: [nodes.deviceId, nodes.num], set: { - lastHeard: row.lastHeard, - snr: row.snr, - isFavorite: row.isFavorite, - isIgnored: row.isIgnored, - userJson: row.userJson, - positionJson: row.positionJson, - metricsJson: row.metricsJson, + lastHeard: sql`excluded.last_heard`, + snr: sql`excluded.snr`, + isFavorite: sql`excluded.is_favorite`, + isIgnored: sql`excluded.is_ignored`, + userJson: sql`excluded.user_json`, + positionJson: sql`excluded.position_json`, + metricsJson: sql`excluded.metrics_json`, }, }); } diff --git a/apps/web/src/pages/Connections/useConnections.devices.test.ts b/apps/web/src/pages/Connections/useConnections.devices.test.ts index 10501992c..6a8fa59cb 100644 --- a/apps/web/src/pages/Connections/useConnections.devices.test.ts +++ b/apps/web/src/pages/Connections/useConnections.devices.test.ts @@ -97,9 +97,10 @@ describe("useConnections over the Kotlin SDK (Serial and Bluetooth)", () => { await act(() => result.current.disconnect(conn.id)); }); - it("hands a click's permitted port to the SDK without prompting", async () => { + it("shows the picker first on a click, filtered to the saved ids, even when a port is permitted", async () => { const radio = fakePort(ids); - const requestPort = installSerial([radio]); + const requestPort = installSerial([radio], radio); + const getPorts = vi.spyOn(navigator.serial, "getPorts"); const { result } = renderHook(() => useConnections()); const conn = result.current.addConnection({ type: "serial", @@ -109,12 +110,13 @@ describe("useConnections over the Kotlin SDK (Serial and Bluetooth)", () => { await act(() => result.current.connect(conn.id, { allowPrompt: true })); - expect(requestPort).not.toHaveBeenCalled(); + expect(requestPort).toHaveBeenCalledWith({ filters: [ids] }); + expect(getPorts).not.toHaveBeenCalled(); expect(kmp.serialTargets).toEqual([{ port: radio, ...ids }]); await act(() => result.current.disconnect(conn.id)); }); - it("shows the port picker on a click only when no permitted port matches, and saves the picked ids", async () => { + it("shows the port picker on a click and saves the picked ids", async () => { const newIds = { usbVendorId: 0x10c4, usbProductId: 0xea60 }; const picked = fakePort(newIds); const requestPort = installSerial([], picked); @@ -177,9 +179,13 @@ describe("useConnections over the Kotlin SDK (Serial and Bluetooth)", () => { await act(() => result.current.disconnect(conn.id)); }); - it("shows the device picker on a click only when the device is unknown, and saves the picked device", async () => { + it("shows the device picker on a click without consulting getDevices, and saves the picked device", async () => { const picked = new FakeBluetoothDevice("radio-2", "Meshtastic_abcd"); - const requestDevice = installBluetooth([], picked); + const requestDevice = installBluetooth( + [new FakeBluetoothDevice("radio-1")], + picked, + ); + const getDevices = vi.spyOn(navigator.bluetooth, "getDevices"); const { result } = renderHook(() => useConnections()); const conn = result.current.addConnection({ type: "bluetooth", @@ -190,6 +196,7 @@ describe("useConnections over the Kotlin SDK (Serial and Bluetooth)", () => { await act(() => result.current.connect(conn.id, { allowPrompt: true })); expect(requestDevice).toHaveBeenCalledTimes(1); + expect(getDevices).not.toHaveBeenCalled(); expect(kmp.bluetoothTargets).toEqual([ { device: picked, deviceId: "radio-2" }, ]); diff --git a/apps/web/src/pages/Connections/useConnections.kmp.test.ts b/apps/web/src/pages/Connections/useConnections.kmp.test.ts index 9f97bbc6c..a513a84ce 100644 --- a/apps/web/src/pages/Connections/useConnections.kmp.test.ts +++ b/apps/web/src/pages/Connections/useConnections.kmp.test.ts @@ -132,7 +132,7 @@ describe("useConnections over the Kotlin SDK (HTTP)", () => { reconnect: undefined, }); - act(() => client.setState(state("reconnecting", { attempt: 1 }))); + act(() => client.setState(state("reconnecting", { attempt: 3 }))); act(() => client.setState(state("disconnected"))); expect(saved(conn.id)).toMatchObject({ status: "error", @@ -141,6 +141,31 @@ describe("useConnections over the Kotlin SDK (HTTP)", () => { }); }); + it("reports the cause when the SDK drops without retrying", async () => { + const { result } = renderHook(() => useConnections()); + const conn = addRadio(result); + await act(() => result.current.connect(conn.id)); + const client = kmp.client; + if (!client) throw new Error("no client created"); + + act(() => + client.setState( + state("reconnecting", { + attempt: 1, + error: "Firmware 2.3.0 is older than the minimum 2.6.0", + errorKind: "firmware-too-old", + }), + ), + ); + act(() => client.setState(state("disconnected"))); + + expect(saved(conn.id)).toMatchObject({ + status: "error", + error: "Firmware 2.3.0 is older than the minimum 2.6.0", + reconnect: undefined, + }); + }); + it("disconnects the old client before connecting the same connection again", async () => { const { result } = renderHook(() => useConnections()); const conn = addRadio(result); diff --git a/apps/web/src/pages/Connections/useConnections.ts b/apps/web/src/pages/Connections/useConnections.ts index 4819f740f..e21423507 100644 --- a/apps/web/src/pages/Connections/useConnections.ts +++ b/apps/web/src/pages/Connections/useConnections.ts @@ -1,8 +1,6 @@ import { type BluetoothConnection, type ConnectionHandle, - knownBluetoothDevice, - permittedSerialPort, pickBluetoothDevice, pickSerialPort, probeConnection, @@ -22,6 +20,7 @@ import { createConnectionFromInput } from "@app/pages/Connections/utils"; import { toast } from "@core/hooks/useToast.ts"; import { type BluetoothTarget, + type ConnectionStateJs, createBluetoothClient, createHttpClient, createSerialClient, @@ -58,8 +57,9 @@ const sessionTeardowns = new Map void>(); /** * What the SDK opens for a serial connection. Automatic connects pass only * the saved USB ids and the SDK reopens the permitted port itself; a click - * (`allowPrompt`) may show the port picker when no permitted port matches, - * and hands the chosen port over. + * (`allowPrompt`) without a held port shows the picker, filtered to the + * saved ids, straight away so the gesture is still live, and hands the + * chosen port over. */ async function serialTarget( conn: SerialConnection, @@ -76,8 +76,7 @@ async function serialTarget( if (!allowPrompt) { return ids; } - const port = - (await permittedSerialPort(conn)) ?? (await pickSerialPort(conn)); + const port = await pickSerialPort(conn); heldSerialPorts.set(conn.id, port); const info = port.getInfo(); if ( @@ -107,8 +106,7 @@ async function bluetoothTarget( if (!allowPrompt) { return { deviceId: conn.deviceId }; } - const device = - (await knownBluetoothDevice(conn)) ?? (await pickBluetoothDevice()); + const device = await pickBluetoothDevice(); heldBluetoothDevices.set(conn.id, device); if (device.id !== conn.deviceId) { useDeviceStore.getState().updateSavedConnection(conn.id, { @@ -247,7 +245,7 @@ export function useConnections() { device.setConnectionId(id); updateSavedConnection(id, { meshDeviceId: deviceId }); - let reconnecting = false; + let reconnecting: ConnectionStateJs | undefined; let firmwareChecked = false; const unsubscribes = [ unsubscribeStore, @@ -270,7 +268,7 @@ export function useConnections() { return; } if (reconnect) { - reconnecting = true; + reconnecting = state; log.warn("kmp: reconnecting", { id, ...reconnect }); updateSavedConnection(id, { status: "connecting", @@ -282,7 +280,23 @@ export function useConnections() { } if (state.kind === "disconnected") { if (!reconnecting) return; - reconnecting = false; + const last = reconnecting; + reconnecting = undefined; + // The SDK gives up before its first attempt on a drop it + // cannot retry; that cause is the error, not the attempt cap. + if (last.attempt === 1 && last.error) { + log.error("kmp: dropped without retrying", { + id, + errorKind: last.errorKind, + }); + const cause = new Error(last.error); + cause.name = last.errorKind ?? "transport"; + updateSavedConnection(id, { + ...connectFailure(cause), + reconnect: undefined, + }); + return; + } log.error("kmp: reconnect attempts exhausted", { id }); updateSavedConnection(id, { status: "error", @@ -294,7 +308,7 @@ export function useConnections() { }); return; } - reconnecting = false; + reconnecting = undefined; updateSavedConnection(id, { status: toConnectionStatus(state), reconnect: undefined, diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt index 91888363c..f2d386abd 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt @@ -23,7 +23,6 @@ import org.meshtastic.proto.PortNum import org.meshtastic.proto.PowerMetrics import org.meshtastic.proto.RouteDiscovery import org.meshtastic.proto.Telemetry -import org.meshtastic.proto.ToRadio import org.meshtastic.proto.TrafficManagementStats import org.meshtastic.sdk.AutoReconnectConfig import org.meshtastic.sdk.ChannelIndex @@ -65,21 +64,9 @@ class MeshtasticClient internal constructor( val myNodeNum: Int? get() = client.ownNode.value?.num - /** The handshake's config bundle, or null before the device has delivered one. */ - val configBundle: ConfigBundleJs? get() = client.configBundle.value?.toJs() - - /** The device's channels as encoded `Channel`s, or null before the handshake delivers them. */ - val channels: Array? get() = client.channels.value?.toJs() - fun onConnectionState(cb: (ConnectionStateJs) -> Unit): () -> Unit = client.connection.onEach { cb(it.toJs(maxAttempts)) }.subscribe() - fun onConfigBundle(cb: (ConfigBundleJs?) -> Unit): () -> Unit = - client.configBundle.onEach { cb(it?.toJs()) }.subscribe() - - fun onChannels(cb: (Array?) -> Unit): () -> Unit = - client.channels.onEach { cb(it?.toJs()) }.subscribe() - fun onNodeChange(cb: (NodeChangeJs) -> Unit): () -> Unit = client.nodes.onEach { cb(it.toJs()) }.subscribe() @@ -95,11 +82,6 @@ class MeshtasticClient internal constructor( return { frameListeners.remove(cb) } } - /** Every `NodeInfo` the SDK holds, encoded. */ - fun nodes(): Promise> = scope.promise { - client.nodeSnapshot().values.map { it.encodeJs() }.toTypedArray() - } - /** Admin messages for the local node, or for `dest` when given. */ fun admin(dest: Int = 0): AdminJs = AdminJs(if (dest == 0) client.admin else client.admin.forNode(NodeId(dest)), scope) @@ -154,14 +136,6 @@ class MeshtasticClient internal constructor( } } - fun sendRaw(toRadio: Uint8Array) { - try { - client.sendRaw(ToRadio.ADAPTER.decode(toRadio.toByteArray())) - } catch (e: Throwable) { - throw e.toJsError().unsafeCast() - } - } - private fun sending(send: () -> MessageHandle): SendHandleJs { val handle = try { send() From dcffadde9380924b1633238d3b2e4c1ef708c301 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 10:18:59 -0500 Subject: [PATCH 24/49] fix(web): reuse the permitted port or device found on drawer refresh The drawer's status probe already resolves the one permitted serial port or the known Bluetooth device for each saved connection. Hand that handle to the click path so Connect after a reload opens it directly instead of showing the picker for a device the browser already allows. --- .../core/connections/browserDevices.test.ts | 17 ++++++-- .../src/core/connections/browserDevices.ts | 20 +++++++--- .../useConnections.devices.test.ts | 40 +++++++++++++++++++ .../src/pages/Connections/useConnections.ts | 9 ++++- 4 files changed, 76 insertions(+), 10 deletions(-) diff --git a/apps/web/src/core/connections/browserDevices.test.ts b/apps/web/src/core/connections/browserDevices.test.ts index 7295114e6..1327318c5 100644 --- a/apps/web/src/core/connections/browserDevices.test.ts +++ b/apps/web/src/core/connections/browserDevices.test.ts @@ -156,17 +156,26 @@ describe("probeConnection", () => { }); it("reports a permitted serial port as online", async () => { - installSerial([fakePort(ids)]); + const radio = fakePort(ids); + installSerial([radio]); await expect(probeConnection(savedSerial)).resolves.toEqual({ status: "online", + port: radio, }); }); - it("reports a known Bluetooth device as online and an unknown one as disconnected", async () => { - installBluetooth(["radio-1"]); - await expect(probeConnection(savedBluetooth)).resolves.toEqual({ + it("hands over no port when several permitted ports share the saved ids", async () => { + installSerial([fakePort(ids), fakePort(ids)]); + await expect(probeConnection(savedSerial)).resolves.toEqual({ status: "online", }); + }); + + it("reports a known Bluetooth device as online and an unknown one as disconnected", async () => { + installBluetooth(["radio-1"]); + const probed = await probeConnection(savedBluetooth); + expect(probed.status).toBe("online"); + expect(probed.device?.id).toBe("radio-1"); const other: Connection = { ...savedBluetooth, deviceId: "radio-2" }; await expect(probeConnection(other)).resolves.toEqual({ status: "disconnected", diff --git a/apps/web/src/core/connections/browserDevices.ts b/apps/web/src/core/connections/browserDevices.ts index 4df1a1451..dbf9c1d3b 100644 --- a/apps/web/src/core/connections/browserDevices.ts +++ b/apps/web/src/core/connections/browserDevices.ts @@ -115,6 +115,8 @@ export type ProbeResult = { status: "online" | "configured" | "disconnected" | "error"; error?: string; errorKind?: Connection["errorKind"]; + port?: SerialPort; + device?: BluetoothDevice; }; /** @@ -144,8 +146,10 @@ export async function probeConnection(conn: Connection): Promise { } case "bluetooth": { try { - const known = await knownBluetoothDevice(conn); - return { status: known ? "online" : "disconnected" }; + const device = await knownBluetoothDevice(conn); + return device + ? { status: "online", device } + : { status: "disconnected" }; } catch { return { status: "disconnected" }; } @@ -156,9 +160,15 @@ export async function probeConnection(conn: Connection): Promise { return { status: "disconnected" }; } try { - const ports = await serial.getPorts(); - const permitted = ports.some((port) => matchesSavedPort(port, conn)); - return { status: permitted ? "online" : "disconnected" }; + const matching = (await serial.getPorts()).filter((port) => + matchesSavedPort(port, conn), + ); + if (matching.length === 0) { + return { status: "disconnected" }; + } + return matching.length === 1 + ? { status: "online", port: matching[0] } + : { status: "online" }; } catch { return { status: "disconnected" }; } diff --git a/apps/web/src/pages/Connections/useConnections.devices.test.ts b/apps/web/src/pages/Connections/useConnections.devices.test.ts index 6a8fa59cb..12339c9a1 100644 --- a/apps/web/src/pages/Connections/useConnections.devices.test.ts +++ b/apps/web/src/pages/Connections/useConnections.devices.test.ts @@ -116,6 +116,46 @@ describe("useConnections over the Kotlin SDK (Serial and Bluetooth)", () => { await act(() => result.current.disconnect(conn.id)); }); + it("connects a click through the port found when the drawer refreshed, without the picker", async () => { + const radio = fakePort(ids); + const requestPort = installSerial([radio], radio); + const { result, rerender } = renderHook(() => useConnections()); + const conn = result.current.addConnection({ + type: "serial", + name: "Serial", + ...ids, + }); + rerender(); + + await act(() => result.current.refreshStatuses()); + await act(() => result.current.connect(conn.id, { allowPrompt: true })); + + expect(requestPort).not.toHaveBeenCalled(); + expect(kmp.serialTargets).toEqual([{ port: radio, ...ids }]); + await act(() => result.current.disconnect(conn.id)); + }); + + it("connects a click through the Bluetooth device found when the drawer refreshed, without the picker", async () => { + const radio = new FakeBluetoothDevice("radio-1"); + const requestDevice = installBluetooth([radio], radio); + const { result, rerender } = renderHook(() => useConnections()); + const conn = result.current.addConnection({ + type: "bluetooth", + name: "Radio", + deviceId: "radio-1", + }); + rerender(); + + await act(() => result.current.refreshStatuses()); + await act(() => result.current.connect(conn.id, { allowPrompt: true })); + + expect(requestDevice).not.toHaveBeenCalled(); + expect(kmp.bluetoothTargets).toEqual([ + { device: radio, deviceId: "radio-1" }, + ]); + await act(() => result.current.disconnect(conn.id)); + }); + it("shows the port picker on a click and saves the picked ids", async () => { const newIds = { usbVendorId: 0x10c4, usbProductId: 0xea60 }; const picked = fakePort(newIds); diff --git a/apps/web/src/pages/Connections/useConnections.ts b/apps/web/src/pages/Connections/useConnections.ts index e21423507..803da9c29 100644 --- a/apps/web/src/pages/Connections/useConnections.ts +++ b/apps/web/src/pages/Connections/useConnections.ts @@ -502,7 +502,14 @@ export function useConnections() { ); await Promise.all( candidates.map(async (c) => { - const { status, error, errorKind } = await probeConnection(c); + const { status, error, errorKind, port, device } = + await probeConnection(c); + if (port) { + heldSerialPorts.set(c.id, port); + } + if (device) { + heldBluetoothDevices.set(c.id, device); + } updateSavedConnection(c.id, { status, error, errorKind }); }), ); From 5819b23373ef04f981487e6607bcd8c84cac3f31 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 10:26:53 -0500 Subject: [PATCH 25/49] fix(web): drop dead device handles and pick before switching radios A held serial port or Bluetooth device is forgotten when the drawer probe no longer finds it or the SDK reports it unavailable, so the next Connect click reaches the picker again. Connecting resolves the picker before tearing down the live radio, keeping the click's activation for the prompt. --- apps/web/src/core/kmp/fakeClient.ts | 4 + .../useConnections.devices.test.ts | 84 ++++++++++++++++++ .../src/pages/Connections/useConnections.ts | 88 +++++++++++-------- 3 files changed, 139 insertions(+), 37 deletions(-) diff --git a/apps/web/src/core/kmp/fakeClient.ts b/apps/web/src/core/kmp/fakeClient.ts index 364e0ba4d..fb88ef8bd 100644 --- a/apps/web/src/core/kmp/fakeClient.ts +++ b/apps/web/src/core/kmp/fakeClient.ts @@ -91,8 +91,12 @@ export class FakeKmpClient implements MeshtasticClient { private packetListeners: Listeners = new Set(); private telemetryListeners = new Map>(); + /** When set, `connect` rejects with it. */ + connectError: Error | undefined; + async connect(): Promise { this.connects.push(Date.now()); + if (this.connectError) throw this.connectError; this.setState(state("connected")); } diff --git a/apps/web/src/pages/Connections/useConnections.devices.test.ts b/apps/web/src/pages/Connections/useConnections.devices.test.ts index 12339c9a1..53dbff31d 100644 --- a/apps/web/src/pages/Connections/useConnections.devices.test.ts +++ b/apps/web/src/pages/Connections/useConnections.devices.test.ts @@ -16,6 +16,7 @@ import { useConnections } from "./useConnections.ts"; const kmp = vi.hoisted( (): { client?: FakeKmpClient; + connectError?: Error; serialTargets: SerialTarget[]; bluetoothTargets: BluetoothTarget[]; } => ({ serialTargets: [], bluetoothTargets: [] }), @@ -34,6 +35,7 @@ vi.mock("@core/kmp/client.ts", async () => { createSerialClient: async (target: SerialTarget) => { kmp.serialTargets.push(target); kmp.client = new FakeKmpClient(); + kmp.client.connectError = kmp.connectError; return kmp.client; }, createBluetoothClient: async (target: BluetoothTarget) => { @@ -71,6 +73,7 @@ function installBluetooth( describe("useConnections over the Kotlin SDK (Serial and Bluetooth)", () => { beforeEach(() => { kmp.client = undefined; + kmp.connectError = undefined; kmp.serialTargets.length = 0; kmp.bluetoothTargets.length = 0; }); @@ -156,6 +159,87 @@ describe("useConnections over the Kotlin SDK (Serial and Bluetooth)", () => { await act(() => result.current.disconnect(conn.id)); }); + it("forgets a port whose permission is gone, so the next click shows the picker", async () => { + const radio = fakePort(ids); + const serial = installFakeSerial([radio]); + serial.requestPort.mockResolvedValue(radio); + const { result, rerender } = renderHook(() => useConnections()); + const conn = result.current.addConnection({ + type: "serial", + name: "Serial", + ...ids, + }); + rerender(); + await act(() => result.current.refreshStatuses()); + + serial.ports = []; + await act(() => result.current.refreshStatuses()); + await act(() => result.current.connect(conn.id, { allowPrompt: true })); + + expect(serial.requestPort).toHaveBeenCalledTimes(1); + await act(() => result.current.disconnect(conn.id)); + }); + + it("forgets a held port the SDK could not open, so the next click shows the picker", async () => { + const radio = fakePort(ids); + const requestPort = installSerial([radio], radio); + const { result, rerender } = renderHook(() => useConnections()); + const conn = result.current.addConnection({ + type: "serial", + name: "Serial", + ...ids, + }); + rerender(); + await act(() => result.current.refreshStatuses()); + kmp.connectError = Object.assign(new Error("port gone"), { + name: "serial-unavailable", + }); + + const first = await act(() => + result.current.connect(conn.id, { allowPrompt: true }), + ); + kmp.connectError = undefined; + await act(() => result.current.connect(conn.id, { allowPrompt: true })); + + expect(first).toBe(false); + expect(requestPort).toHaveBeenCalledTimes(1); + await act(() => result.current.disconnect(conn.id)); + }); + + it("shows the picker for a new radio before disconnecting the live one", async () => { + const order: string[] = []; + installSerial([fakePort(ids)]); + const picked = new FakeBluetoothDevice("radio-1"); + const requestDevice = installBluetooth([], picked); + requestDevice.mockImplementation(async () => { + order.push("picker"); + return picked; + }); + const { result } = renderHook(() => useConnections()); + const serial = result.current.addConnection({ + type: "serial", + name: "Serial", + ...ids, + }); + await act(() => result.current.connect(serial.id)); + const live = kmp.client; + if (!live) throw new Error("no serial client"); + const disconnect = live.disconnect.bind(live); + vi.spyOn(live, "disconnect").mockImplementation(async () => { + order.push("disconnect"); + await disconnect(); + }); + const radio = result.current.addConnection({ + type: "bluetooth", + name: "Radio", + }); + + await act(() => result.current.connect(radio.id, { allowPrompt: true })); + + expect(order).toEqual(["picker", "disconnect"]); + await act(() => result.current.disconnect(radio.id)); + }); + it("shows the port picker on a click and saves the picked ids", async () => { const newIds = { usbVendorId: 0x10c4, usbProductId: 0xea60 }; const picked = fakePort(newIds); diff --git a/apps/web/src/pages/Connections/useConnections.ts b/apps/web/src/pages/Connections/useConnections.ts index 803da9c29..68455ee90 100644 --- a/apps/web/src/pages/Connections/useConnections.ts +++ b/apps/web/src/pages/Connections/useConnections.ts @@ -117,6 +117,26 @@ async function bluetoothTarget( return { device, deviceId: device.id }; } +type ClientFactory = (storage?: StorageJs) => Promise; + +async function clientFactory( + conn: Connection, + allowPrompt: boolean, +): Promise { + switch (conn.type) { + case "http": + return (storage) => createHttpClient(conn.url, allowPrompt, storage); + case "serial": { + const target = await serialTarget(conn, allowPrompt); + return (storage) => createSerialClient(target, storage); + } + case "bluetooth": { + const target = await bluetoothTarget(conn, allowPrompt); + return (storage) => createBluetoothClient(target, storage); + } + } +} + const savedConnection = (id: ConnectionId): Connection | undefined => useDeviceStore.getState().savedConnections.find((c) => c.id === id); @@ -203,10 +223,7 @@ export function useConnections() { * this connection reached last time. */ const connectThroughKmp = useCallback( - async ( - id: ConnectionId, - makeClient: (storage?: StorageJs) => Promise, - ) => { + async (id: ConnectionId, makeClient: ClientFactory) => { const conn = savedConnection(id); const { options, persistent, sdkStorage } = await openRepositories( conn?.nodeNum, @@ -365,6 +382,14 @@ export function useConnections() { }); sessionTeardowns.get(id)?.(); sessionTeardowns.delete(id); + if ( + error instanceof Error && + (error.name === "serial-unavailable" || + error.name === "bluetooth-unavailable") + ) { + heldSerialPorts.delete(id); + heldBluetoothDevices.delete(id); + } updateSavedConnection(id, connectFailure(error)); return false; } @@ -400,43 +425,28 @@ export function useConnections() { allowPrompt: !!opts?.allowPrompt, }); updateStatus(id, "connecting"); - // The app follows one radio at a time: a session still live on - // another connection would keep its port and poller to itself. - for (const other of [...sessionTeardowns.keys()]) { - if (other === id) continue; - await teardown(other); - const otherDevice = savedConnection(other)?.meshDeviceId; - if (otherDevice) { - useDeviceStore - .getState() - .getDevice(otherDevice) - ?.setConnectionId(null); - } - updateSavedConnection(other, { - status: "disconnected", - error: undefined, - }); - } const allowPrompt = opts?.allowPrompt ?? false; try { - switch (conn.type) { - case "http": - return await connectThroughKmp(id, (storage) => - createHttpClient(conn.url, allowPrompt, storage), - ); - case "serial": { - const target = await serialTarget(conn, allowPrompt); - return await connectThroughKmp(id, (storage) => - createSerialClient(target, storage), - ); - } - case "bluetooth": { - const target = await bluetoothTarget(conn, allowPrompt); - return await connectThroughKmp(id, (storage) => - createBluetoothClient(target, storage), - ); + // The picker runs first, while the click's activation is still live. + const makeClient = await clientFactory(conn, allowPrompt); + // The app follows one radio at a time: a session still live on + // another connection would keep its port and poller to itself. + for (const other of [...sessionTeardowns.keys()]) { + if (other === id) continue; + await teardown(other); + const otherDevice = savedConnection(other)?.meshDeviceId; + if (otherDevice) { + useDeviceStore + .getState() + .getDevice(otherDevice) + ?.setConnectionId(null); } + updateSavedConnection(other, { + status: "disconnected", + error: undefined, + }); } + return await connectThroughKmp(id, makeClient); } catch (error) { log.error("connect: no device to connect to", { id, @@ -510,6 +520,10 @@ export function useConnections() { if (device) { heldBluetoothDevices.set(c.id, device); } + if (status === "disconnected") { + heldSerialPorts.delete(c.id); + heldBluetoothDevices.delete(c.id); + } updateSavedConnection(c.id, { status, error, errorKind }); }), ); From ec7168f4978562193ec32a0b9e6aca296531caa5 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 12:05:38 -0500 Subject: [PATCH 26/49] fix(kmp): keep reconnecting after a serial drop and surface the SDK's logs A failed write on a lost USB link made the Web Serial and Web Bluetooth transports report a recoverable Error and then throw. The engine treats a throwing send as fatal: it queues Disconnect ahead of the state change, cancels the session without retrying and ends in `disconnected`. The web subscriber ignored a `disconnected` that no `reconnecting` preceded, so the UI stayed on "Connected" with nothing logged. The same silent path serves the engine's 60 s liveness timeout. - Transports report link loss only through state; send() no longer throws. - The OS disconnect handler releases the lost port before forgetting it. - A `disconnected` the SDK initiated marks the connection as an error with a message and an error log line. - `setSdkLogger` routes the SDK's LogSink and the facade's connection-state transitions into the web's tslog "sdk" logger. - The serial fakes follow Chromium: the same SerialPort object survives an unplug, both streams fail with a NetworkError, open() fails until the replug, close() on a closed port throws InvalidStateError. --- .../public/i18n/locales/en/connections.json | 3 +- apps/web/src/core/kmp/client.ts | 30 +++++- apps/web/src/core/kmp/serialClient.test.ts | 96 +++++++++++++++---- .../Connections/useConnections.kmp.test.ts | 18 ++++ .../src/pages/Connections/useConnections.ts | 11 ++- apps/web/src/tests/fakeBrowserDevices.ts | 51 +++++++++- .../kotlin/org/meshtastic/sdk/js/Client.kt | 8 ++ .../kotlin/org/meshtastic/sdk/js/Logging.kt | 34 +++++++ .../sdk/js/WebBluetoothTransport.kt | 4 +- .../meshtastic/sdk/js/WebSerialTransport.kt | 15 ++- .../sdk/js/WebSerialTransportTest.kt | 35 ++++++- 11 files changed, 272 insertions(+), 33 deletions(-) create mode 100644 packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Logging.kt diff --git a/apps/web/public/i18n/locales/en/connections.json b/apps/web/public/i18n/locales/en/connections.json index b0c5b028e..71a74a7c2 100644 --- a/apps/web/public/i18n/locales/en/connections.json +++ b/apps/web/public/i18n/locales/en/connections.json @@ -97,7 +97,8 @@ "localNetworkDenied": "Chrome blocked local network access for this site. Click the site-info icon in the address bar, allow Local network, then Connect.", "localNetworkPrompt": "Chrome needs your permission to reach the local network. Click Connect to allow it.", "handshakeTimeout": "The radio stopped responding during the handshake. It may be in CLI or bootloader mode, or its firmware isn't answering config requests.", - "reconnectFailed": "Could not reconnect after {{attempts}} attempts." + "reconnectFailed": "Could not reconnect after {{attempts}} attempts.", + "connectionLost": "The connection to the radio was lost." }, "httpTest": { "certNotTrusted": "Certificate not trusted. <0>Open in new tab and accept the warning, then test again." diff --git a/apps/web/src/core/kmp/client.ts b/apps/web/src/core/kmp/client.ts index 72d2d011c..838b84bc9 100644 --- a/apps/web/src/core/kmp/client.ts +++ b/apps/web/src/core/kmp/client.ts @@ -1,3 +1,4 @@ +import { createLogger } from "@core/log.ts"; import type { MeshtasticClient, StorageJs } from "@meshtastic/sdk-kmp"; export type { @@ -13,12 +14,39 @@ type KmpModule = typeof import("@meshtastic/sdk-kmp"); let loading: Promise | undefined; +const sdkLog = createLogger("sdk"); + +/** Routes the SDK's own log lines into the web logger, prefixed with their tag. */ +function routeSdkLogs(kmp: KmpModule): KmpModule { + kmp.setSdkLogger((level, tag, message, error) => { + const args: unknown[] = error ? [{ error }] : []; + const line = `${tag}: ${message}`; + switch (level) { + case "verbose": + sdkLog.trace(line, ...args); + return; + case "debug": + sdkLog.debug(line, ...args); + return; + case "warn": + sdkLog.warn(line, ...args); + return; + case "error": + sdkLog.error(line, ...args); + return; + default: + sdkLog.info(line, ...args); + } + }); + return kmp; +} + /** * The Kotlin SDK is ~240 KB gzipped, so it is loaded on first connect * rather than with the app shell. */ export function loadKmp(): Promise { - loading ??= import("@meshtastic/sdk-kmp"); + loading ??= import("@meshtastic/sdk-kmp").then(routeSdkLogs); return loading; } diff --git a/apps/web/src/core/kmp/serialClient.test.ts b/apps/web/src/core/kmp/serialClient.test.ts index 4f027670c..8a5b6062d 100644 --- a/apps/web/src/core/kmp/serialClient.test.ts +++ b/apps/web/src/core/kmp/serialClient.test.ts @@ -7,7 +7,11 @@ import { uninstallBrowserDevices, } from "@app/tests/fakeBrowserDevices.ts"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { createSerialClient, type MeshtasticClient } from "./client.ts"; +import { + createSerialClient, + loadKmp, + type MeshtasticClient, +} from "./client.ts"; const ids = { usbVendorId: 0x303a, usbProductId: 0x1001 }; @@ -92,10 +96,73 @@ describe("createSerialClient (Kotlin facade over a fake navigator.serial)", () = }); }); - it("reconnects through the SDK after an unplug, and reopens the replugged port", async () => { + for (const order of ["read error first", "disconnect event first"]) { + it(`reconnects after Chrome's unplug sequence (${order}) and reopens the same port once it is back`, async () => { + const radio = new FakeRadio(); + const port = new FakeSerialPort(ids, radio); + const serial = installSerial([port]); + const client = await createSerialClient(ids); + clients.push(client); + const states: ConnectionStateJs[] = []; + client.onConnectionState((state) => states.push(state)); + const lines: string[] = []; + (await loadKmp()).setSdkLogger((level, tag, message) => + lines.push(`${level} ${tag}: ${message}`), + ); + await client.connect(); + await connected(client); + + if (order === "disconnect event first") { + serial.dispatch("disconnect", port); + await new Promise((resolve) => setTimeout(resolve, 0)); + port.unplug(); + } else { + port.unplug(); + await new Promise((resolve) => setTimeout(resolve, 0)); + serial.dispatch("disconnect", port); + } + + await vi.waitFor( + () => expect(client.connectionState.kind).toBe("reconnecting"), + { timeout: 2_000, interval: 10 }, + ); + expect(client.connectionState).toMatchObject({ + attempt: 1, + maxAttempts: 10, + errorKind: "serial-disconnected", + }); + + await new Promise((resolve) => setTimeout(resolve, 1_500)); + port.replug(); + serial.dispatch("connect", port); + + await connected(client); + expect(port.opens).toBe(2); + expect(serial.requestPort).not.toHaveBeenCalled(); + expect(states.map((s) => s.kind)).toEqual( + expect.arrayContaining(["connected", "reconnecting", "connected"]), + ); + expect(lines).toEqual( + expect.arrayContaining([ + expect.stringMatching( + /^warn MeshEngine: Transport error: (Serial device disconnected|The device has been lost\.)$/, + ), + expect.stringMatching( + /^info MeshEngine: Auto-reconnect attempt 1 scheduled in \d+ ms$/, + ), + expect.stringMatching( + /^info Client: Connection state: reconnecting \(attempt 1\): /, + ), + "info MeshEngine: Auto-reconnect attempt 1 succeeded", + ]), + ); + }, 15_000); + } + + it("reconnects when a write fails before the OS reports the loss", async () => { const radio = new FakeRadio(); const port = new FakeSerialPort(ids, radio); - const serial = installSerial([port]); + installSerial([port]); const client = await createSerialClient(ids); clients.push(client); const states: ConnectionStateJs[] = []; @@ -103,28 +170,19 @@ describe("createSerialClient (Kotlin facade over a fake navigator.serial)", () = await client.connect(); await connected(client); - port.unplug(); - serial.dispatch("disconnect", port); + port.failWrites(); + const outcome = await client.sendText("hi", 0xffffffff, 0).outcome; + expect(outcome.ok).toBe(false); await vi.waitFor( () => expect(client.connectionState.kind).toBe("reconnecting"), { timeout: 2_000, interval: 10 }, ); - expect(client.connectionState).toMatchObject({ - attempt: 1, - maxAttempts: 10, - errorKind: "serial-disconnected", - }); - - const replugged = new FakeSerialPort(ids, radio); - serial.ports = [replugged]; - serial.dispatch("connect", replugged); - await connected(client); - expect(replugged.opens).toBe(1); - expect(serial.requestPort).not.toHaveBeenCalled(); - expect(states.map((s) => s.kind)).toEqual( - expect.arrayContaining(["connected", "reconnecting", "connected"]), + expect(port.opens).toBe(2); + const kinds = states.map((s) => s.kind); + expect(kinds.slice(kinds.indexOf("connected"))).not.toContain( + "disconnected", ); }, 15_000); }); diff --git a/apps/web/src/pages/Connections/useConnections.kmp.test.ts b/apps/web/src/pages/Connections/useConnections.kmp.test.ts index a513a84ce..2cba3df4f 100644 --- a/apps/web/src/pages/Connections/useConnections.kmp.test.ts +++ b/apps/web/src/pages/Connections/useConnections.kmp.test.ts @@ -166,6 +166,24 @@ describe("useConnections over the Kotlin SDK (HTTP)", () => { }); }); + it("reports a drop the SDK gave up on without any reconnect attempt", async () => { + const { result } = renderHook(() => useConnections()); + const conn = addRadio(result); + await act(() => result.current.connect(conn.id)); + const client = kmp.client; + if (!client) throw new Error("no client created"); + expect(saved(conn.id)?.status).toBe("configured"); + + act(() => client.setState(state("disconnected"))); + + expect(saved(conn.id)).toMatchObject({ + status: "error", + error: "The connection to the radio was lost.", + errorKind: "network", + reconnect: undefined, + }); + }); + it("disconnects the old client before connecting the same connection again", async () => { const { result } = renderHook(() => useConnections()); const conn = addRadio(result); diff --git a/apps/web/src/pages/Connections/useConnections.ts b/apps/web/src/pages/Connections/useConnections.ts index 68455ee90..8a16ded64 100644 --- a/apps/web/src/pages/Connections/useConnections.ts +++ b/apps/web/src/pages/Connections/useConnections.ts @@ -296,7 +296,16 @@ export function useConnections() { return; } if (state.kind === "disconnected") { - if (!reconnecting) return; + if (!reconnecting) { + log.error("kmp: dropped without retrying", { id }); + updateSavedConnection(id, { + status: "error", + reconnect: undefined, + error: t("connections:errors.connectionLost"), + errorKind: "network", + }); + return; + } const last = reconnecting; reconnecting = undefined; // The SDK gives up before its first attempt on a drop it diff --git a/apps/web/src/tests/fakeBrowserDevices.ts b/apps/web/src/tests/fakeBrowserDevices.ts index 380ea0347..2bd6095db 100644 --- a/apps/web/src/tests/fakeBrowserDevices.ts +++ b/apps/web/src/tests/fakeBrowserDevices.ts @@ -165,6 +165,7 @@ export class FakeSerialPort extends EventTarget implements SerialPort { closes = 0; readonly written: Uint8Array[] = []; private reader?: ReadableStreamDefaultController; + private writer?: WritableStreamDefaultController; private readonly splitter = new FrameSplitter(); constructor( @@ -178,7 +179,15 @@ export class FakeSerialPort extends EventTarget implements SerialPort { return this.info; } - async open(): Promise { + open(): Promise { + if (this.readable || this.writable) { + throw new DOMException("The port is already open.", "InvalidStateError"); + } + if (!this.connected) { + return Promise.reject( + new DOMException("Failed to open serial port.", "NetworkError"), + ); + } this.opens += 1; this.readable = new ReadableStream({ start: (controller) => { @@ -186,6 +195,9 @@ export class FakeSerialPort extends EventTarget implements SerialPort { }, }); this.writable = new WritableStream({ + start: (controller) => { + this.writer = controller; + }, write: (chunk) => { this.written.push(chunk); for (const payload of this.splitter.feed(chunk)) { @@ -195,15 +207,23 @@ export class FakeSerialPort extends EventTarget implements SerialPort { } }, }); + return Promise.resolve(); } - async close(): Promise { + close(): Promise { + if (!this.readable && !this.writable) { + throw new DOMException( + "The port is already closed.", + "InvalidStateError", + ); + } this.closes += 1; try { this.reader?.close(); } catch {} this.readable = null; this.writable = null; + return Promise.resolve(); } async forget(): Promise {} @@ -218,14 +238,37 @@ export class FakeSerialPort extends EventTarget implements SerialPort { this.reader?.enqueue(bytes); } - /** The OS lost the device: the read stream errors, as Chrome's does. */ + /** + * The OS lost the device. As in Chromium, the port stays permitted and + * keeps its identity, `connected` flips, both streams error with a + * NetworkError and the getters go null; a later `open()` fails until + * `replug()`. + */ unplug(): void { + this.connected = false; + const lost = new DOMException("The device has been lost.", "NetworkError"); + try { + this.reader?.error(lost); + } catch {} try { - this.reader?.error(new Error("The device has been lost.")); + this.writer?.error(lost); } catch {} this.readable = null; this.writable = null; } + + replug(): void { + this.connected = true; + } + + /** The device is gone but the OS has not said so yet: only writes fail. */ + failWrites(): void { + try { + this.writer?.error( + new DOMException("The device has been lost.", "NetworkError"), + ); + } catch {} + } } export class FakeSerial extends EventTarget { diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt index f2d386abd..2208fe654 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt @@ -27,6 +27,7 @@ import org.meshtastic.proto.TrafficManagementStats import org.meshtastic.sdk.AutoReconnectConfig import org.meshtastic.sdk.ChannelIndex import org.meshtastic.sdk.InMemoryStorageProvider +import org.meshtastic.sdk.LogLevel import org.meshtastic.sdk.MessageHandle import org.meshtastic.sdk.NodeId import org.meshtastic.sdk.RadioClient @@ -48,6 +49,13 @@ class MeshtasticClient internal constructor( transport(TappingTransport(transport) { bytes -> frameListeners.toList().forEach { it(bytes.toUint8Array()) } }) storage(if (storage == null) InMemoryStorageProvider() else JsStorageProvider(storage)) autoReconnect(AutoReconnectConfig(maxAttempts = maxAttempts)) + logger(JsLogSink) + } + + init { + client.connection + .onEach { JsLogSink.log(LogLevel.INFO, "Client", "Connection state: ${it.describe()}", null) } + .launchIn(scope) } fun connect(): Promise = scope.promise { diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Logging.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Logging.kt new file mode 100644 index 000000000..966d1a7c7 --- /dev/null +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Logging.kt @@ -0,0 +1,34 @@ +@file:OptIn(ExperimentalJsExport::class) + +package org.meshtastic.sdk.js + +import org.meshtastic.sdk.ConnectionState +import org.meshtastic.sdk.LogLevel +import org.meshtastic.sdk.LogSink +import kotlin.js.ExperimentalJsExport +import kotlin.js.JsExport + +/** Receives every SDK and facade log line; `level` is `verbose`, `debug`, `info`, `warn` or `error`. */ +typealias LogListener = (level: String, tag: String, message: String, error: String?) -> Unit + +private var listener: LogListener? = null + +/** Routes the SDK's logger to `cb`, or back to silence with null. Applies to every client. */ +@JsExport +fun setSdkLogger(cb: LogListener?) { + listener = cb +} + +internal object JsLogSink : LogSink { + override fun log(level: LogLevel, tag: String, message: String, cause: Throwable?) { + listener?.invoke(level.name.lowercase(), tag, message, cause?.message) + } +} + +internal fun ConnectionState.describe(): String = when (this) { + ConnectionState.Disconnected -> "disconnected" + is ConnectionState.Connecting -> "connecting (attempt $attempt)" + is ConnectionState.Configuring -> "configuring ${phase.name}" + ConnectionState.Connected -> "connected" + is ConnectionState.Reconnecting -> "reconnecting (attempt $attempt): ${cause.message}" +} diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebBluetoothTransport.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebBluetoothTransport.kt index ca8a5a896..1644968d1 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebBluetoothTransport.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebBluetoothTransport.kt @@ -120,9 +120,11 @@ internal class WebBluetoothTransport( } (write as Promise).await() } + } catch (e: CancellationException) { + throw e } catch (e: Throwable) { dropped(e.message ?: "Bluetooth write failed") - throw ClientException("transport", e.message ?: "Bluetooth write failed") + return } wakeDrain() } diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebSerialTransport.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebSerialTransport.kt index a60e897fb..2b79441de 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebSerialTransport.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebSerialTransport.kt @@ -25,6 +25,10 @@ import kotlin.js.Promise * the host obtained from `navigator.serial.requestPort()` inside a user * gesture, or null, in which case every connect (first or reconnect) reopens * the one permitted port whose USB ids match through `getPorts()`. + * + * A lost link is reported through [state] as a recoverable + * [TransportState.Error] and never thrown from [send]: the engine treats a + * throwing send as fatal and tears the session down instead of reconnecting. */ internal class WebSerialTransport( private var port: dynamic, @@ -46,8 +50,8 @@ internal class WebSerialTransport( private val onOsDisconnect: (dynamic) -> Unit = { event -> val gone = event.target ?: event.port if (gone != null && gone === port) { - port = null dropped("Serial device disconnected") + port = null } } @@ -104,9 +108,10 @@ internal class WebSerialTransport( val w = writer ?: throw ClientException("transport", "Serial port is not open") try { (w.write(frame.bytes.toByteArray().toUint8Array()) as Promise).await() + } catch (e: CancellationException) { + throw e } catch (e: Throwable) { dropped(e.message ?: "Serial write failed") - throw ClientException("transport", e.message ?: "Serial write failed") } } @@ -201,11 +206,11 @@ internal class WebSerialTransport( private fun dropped(reason: String) { if (closing || _state.value !is TransportState.Connected) return _state.value = TransportState.Error(ClientException(DISCONNECTED, reason), recoverable = true) - scope?.launch { release() } + val p = port + scope?.launch { release(p) } } - private suspend fun release() { - val p = port + private suspend fun release(p: dynamic = port) { try { (reader?.cancel() as? Promise)?.await() } catch (_: Throwable) { diff --git a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebSerialTransportTest.kt b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebSerialTransportTest.kt index 5825fe2f2..94d14950d 100644 --- a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebSerialTransportTest.kt +++ b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebSerialTransportTest.kt @@ -58,7 +58,7 @@ class WebSerialTransportTest { var self = this; self.opens++; self.readable = new ReadableStream({ start: function (c) { self.reader = c; } }); - self.writable = new WritableStream({ write: function (chunk) { self.written.push(chunk); } }); + self.writable = new WritableStream({ start: function (c) { self.writer = c; }, write: function (chunk) { self.written.push(chunk); } }); return Promise.resolve(); }, close: function () { this.closes++; this.readable = null; this.writable = null; return Promise.resolve(); }, @@ -176,6 +176,39 @@ class WebSerialTransportTest { transport.disconnect() } + @Test + fun a_failed_write_is_a_recoverable_error_and_does_not_throw() = GlobalScope.promise { + val radio = fakePort(0x303a, 0x1001) + installSerial(arrayOf(radio)) + val transport = WebSerialTransport(null, 0x303a, 0x1001) + transport.connect() + radio.writer.error(js("new DOMException('The device has been lost.', 'NetworkError')")) + + transport.send(Frame(framed(byteArrayOf(0x10)))) + + val error = transport.state.value as TransportState.Error + assertTrue(error.recoverable) + assertEquals("serial-disconnected", (error.cause as ClientException).kind) + transport.disconnect() + } + + @Test + fun an_os_disconnect_closes_the_lost_port_and_forgets_it() = GlobalScope.promise { + val radio = fakePort(0x303a, 0x1001) + val serial = installSerial(arrayOf(radio)) + val transport = WebSerialTransport(radio, 0x303a, 0x1001) + transport.connect() + + serial.dispatch("disconnect", radio) + withTimeout(1_000) { transport.state.first { it is TransportState.Error } } + delay(10) + + assertEquals(1, radio.closes) + serial.ports = arrayOf() + assertFailsWith { transport.connect() } + transport.disconnect() + } + @Test fun releases_its_serial_listeners_on_disconnect_and_on_a_failed_connect() = GlobalScope.promise { val radio = fakePort(0x303a, 0x1001) From 80f8d01bb03c2ec350e7ca4337e60053d64fe2e2 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 12:30:47 -0500 Subject: [PATCH 27/49] fix(web): keep the live session through an SDK reconnect MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While the SDK reconnected, the drawer's refresh probed the connection and overwrote its "connecting" status with the probe's "online", so the row offered Connect instead of "Reconnecting… n of 10". A click then started a second client against the same port: the live session was torn down and the new one, whose connect fails on the busy port, stayed registered as the active session. The app then read a session that never saw a handshake: no own node, no channels, only the persisted node list. - refreshStatuses leaves connections with a live session alone. - connect() is a no-op while that connection's session is reconnecting. - A session whose connect failed is unregistered, not left as the active one. - The session's own handshake cycle (after an unlock) no longer reports its planned disconnect as a drop. - The facade e2e asserts the session's own node and channels survive an auto-reconnect; the fake radio can report extra nodes and channels. --- apps/web/src/core/kmp/serialClient.test.ts | 36 +++++ apps/web/src/core/kmp/session.ts | 26 ++-- ...est.ts => useConnections.devices.test.tsx} | 124 ++++++++++++++++++ .../Connections/useConnections.kmp.test.ts | 21 +++ .../src/pages/Connections/useConnections.ts | 7 + apps/web/src/tests/fakeBrowserDevices.ts | 31 ++++- 6 files changed, 236 insertions(+), 9 deletions(-) rename apps/web/src/pages/Connections/{useConnections.devices.test.ts => useConnections.devices.test.tsx} (76%) diff --git a/apps/web/src/core/kmp/serialClient.test.ts b/apps/web/src/core/kmp/serialClient.test.ts index 8a5b6062d..62f7d24e5 100644 --- a/apps/web/src/core/kmp/serialClient.test.ts +++ b/apps/web/src/core/kmp/serialClient.test.ts @@ -12,6 +12,7 @@ import { loadKmp, type MeshtasticClient, } from "./client.ts"; +import { MeshSession } from "./session.ts"; const ids = { usbVendorId: 0x303a, usbProductId: 0x1001 }; @@ -159,6 +160,41 @@ describe("createSerialClient (Kotlin facade over a fake navigator.serial)", () = }, 15_000); } + it("hands the session its own node and channels again after an auto-reconnect", async () => { + const radio = new FakeRadio(0x0a0b0c0d, { nodes: 3, channels: 2 }); + const port = new FakeSerialPort(ids, radio); + const serial = installSerial([port]); + const client = await createSerialClient(ids); + clients.push(client); + const session = new MeshSession(client); + await client.connect(); + await connected(client); + const mine = () => + session.nodes.list.peek().some((n) => n.num === session.myNodeNum); + expect(session.device.myNodeNum.peek()).toBe(0x0a0b0c0d); + expect(mine()).toBe(true); + expect(session.channels.list.peek()).toHaveLength(2); + + port.unplug(); + serial.dispatch("disconnect", port); + await vi.waitFor( + () => expect(client.connectionState.kind).toBe("reconnecting"), + { timeout: 2_000, interval: 10 }, + ); + port.replug(); + serial.dispatch("connect", port); + await connected(client); + await vi.waitFor(() => + expect(session.progress.peek()).toMatchObject({ phase: "configured" }), + ); + + expect(session.device.myNodeNum.peek()).toBe(0x0a0b0c0d); + expect(session.nodes.list.peek()).toHaveLength(4); + expect(mine()).toBe(true); + expect(session.channels.list.peek()).toHaveLength(2); + session.close(); + }, 15_000); + it("reconnects when a write fails before the OS reports the loss", async () => { const radio = new FakeRadio(); const port = new FakeSerialPort(ids, radio); diff --git a/apps/web/src/core/kmp/session.ts b/apps/web/src/core/kmp/session.ts index 699d3436c..40919f9b1 100644 --- a/apps/web/src/core/kmp/session.ts +++ b/apps/web/src/core/kmp/session.ts @@ -139,6 +139,7 @@ export class MeshSession { private readonly unsubscribes: Array<() => void> = []; private closed = false; private rehandshaking: Promise | undefined; + private cycling = false; constructor( readonly kmp: MeshtasticClient, @@ -298,17 +299,26 @@ export class MeshSession { * closed while the cycle is under way stays disconnected. */ rehandshake(): Promise { - this.rehandshaking ??= (async () => { - try { - await this.kmp.disconnect(); - if (!this.closed) await this.kmp.connect(); - } finally { - this.rehandshaking = undefined; - } - })(); + this.rehandshaking ??= this.cycleConnection(); return this.rehandshaking; } + private async cycleConnection(): Promise { + this.cycling = true; + try { + await this.kmp.disconnect(); + if (!this.closed) await this.kmp.connect(); + } finally { + this.cycling = false; + this.rehandshaking = undefined; + } + } + + /** True while `rehandshake` is cycling the SDK connection. */ + get isRehandshaking(): boolean { + return this.cycling; + } + /** Disconnects the SDK client once any handshake cycle has settled. */ async disconnect(): Promise { await this.rehandshaking?.catch(() => {}); diff --git a/apps/web/src/pages/Connections/useConnections.devices.test.ts b/apps/web/src/pages/Connections/useConnections.devices.test.tsx similarity index 76% rename from apps/web/src/pages/Connections/useConnections.devices.test.ts rename to apps/web/src/pages/Connections/useConnections.devices.test.tsx index 53dbff31d..a7465e60a 100644 --- a/apps/web/src/pages/Connections/useConnections.devices.test.ts +++ b/apps/web/src/pages/Connections/useConnections.devices.test.tsx @@ -9,7 +9,13 @@ import { installSerial as installFakeSerial, uninstallBrowserDevices, } from "@app/tests/fakeBrowserDevices.ts"; +import { create, toBinary } from "@bufbuild/protobuf"; +import { useMyNodeAsProto } from "@core/hooks/useNodesAsProto.ts"; +import { MeshRegistryProvider, useChannels } from "@core/kmp/hooks"; +import { meshRegistry } from "@core/kmp/registry.ts"; +import { Protobuf } from "@core/protobuf.ts"; import { act, renderHook } from "@testing-library/react"; +import type { ReactNode } from "react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { useConnections } from "./useConnections.ts"; @@ -55,6 +61,61 @@ function fakePort(info: SerialPortInfo): SerialPort { return new FakeSerialPort(info); } +const MY_NODE = 0x0a0b0c0d; + +const fromRadio = ( + payloadVariant: Protobuf.Mesh.FromRadio["payloadVariant"], +): Uint8Array => + toBinary( + Protobuf.Mesh.FromRadioSchema, + create(Protobuf.Mesh.FromRadioSchema, { payloadVariant }), + ); + +/** The frames and node snapshot a handshake hands the session. */ +function handshake(client: FakeKmpClient): void { + act(() => + client.emitFrame( + fromRadio({ + case: "myInfo", + value: create(Protobuf.Mesh.MyNodeInfoSchema, { myNodeNum: MY_NODE }), + }), + ), + ); + act(() => + client.emitFrame( + fromRadio({ + case: "channel", + value: create(Protobuf.Channel.ChannelSchema, { + index: 0, + role: Protobuf.Channel.Channel_Role.PRIMARY, + }), + }), + ), + ); + act(() => + client.emitNodeChange({ + kind: "snapshot", + nodes: [ + toBinary( + Protobuf.Mesh.NodeInfoSchema, + create(Protobuf.Mesh.NodeInfoSchema, { + num: MY_NODE, + user: { longName: "Me" }, + }), + ), + ], + node: null, + nodeNum: 0, + }), + ); +} + +const withRegistry = ({ children }: { children: ReactNode }) => ( + + {children} + +); + function installSerial(ports: SerialPort[], picked?: SerialPort) { const serial = installFakeSerial(ports); if (picked) serial.requestPort.mockResolvedValue(picked); @@ -348,6 +409,69 @@ describe("useConnections over the Kotlin SDK (Serial and Bluetooth)", () => { await act(() => result.current.disconnect(conn.id)); }); + it("keeps the live session through an SDK reconnect while the drawer refreshes and Connect is clicked", async () => { + installSerial([fakePort(ids)]); + const { result } = renderHook(() => useConnections()); + const conn = result.current.addConnection({ + type: "serial", + name: "Serial", + ...ids, + }); + await act(() => result.current.connect(conn.id)); + const client = kmp.client; + if (!client) throw new Error("no client created"); + handshake(client); + const view = renderHook( + () => ({ me: useMyNodeAsProto(), channels: useChannels() }), + { wrapper: withRegistry }, + ); + expect(view.result.current.me?.num).toBe(MY_NODE); + expect(view.result.current.channels).toHaveLength(1); + + act(() => + client.setState( + state("reconnecting", { attempt: 2, errorKind: "serial-unavailable" }), + ), + ); + await act(() => result.current.refreshStatuses()); + expect(saved(conn.id)).toMatchObject({ + status: "connecting", + reconnect: { attempt: 2, maxAttempts: 10 }, + }); + + await act(() => result.current.connect(conn.id, { allowPrompt: true })); + expect(kmp.client).toBe(client); + expect(client.disconnects).toHaveLength(0); + + act(() => client.setState(state("configuring", { phase: "Stage1" }))); + handshake(client); + act(() => client.setState(state("connected"))); + expect(saved(conn.id)?.status).toBe("configured"); + expect(meshRegistry.active.value?.kmp).toBe(client); + expect(view.result.current.me?.num).toBe(MY_NODE); + expect(view.result.current.channels).toHaveLength(1); + await act(() => result.current.disconnect(conn.id)); + }); + + it("drops the session of a connect that failed, so the app does not read a dead one", async () => { + installSerial([fakePort(ids)]); + kmp.connectError = Object.assign(new Error("busy"), { + name: "serial-busy", + }); + const { result } = renderHook(() => useConnections()); + const conn = result.current.addConnection({ + type: "serial", + name: "Serial", + ...ids, + }); + + expect(await act(() => result.current.connect(conn.id))).toBe(false); + + expect(meshRegistry.get(conn.id)).toBeUndefined(); + expect(meshRegistry.active.value).toBeUndefined(); + expect(saved(conn.id)?.status).toBe("error"); + }); + it("shows the SDK's reconnect attempts after the device drops", async () => { installSerial([fakePort(ids)]); const { result } = renderHook(() => useConnections()); diff --git a/apps/web/src/pages/Connections/useConnections.kmp.test.ts b/apps/web/src/pages/Connections/useConnections.kmp.test.ts index 2cba3df4f..d833d7f9c 100644 --- a/apps/web/src/pages/Connections/useConnections.kmp.test.ts +++ b/apps/web/src/pages/Connections/useConnections.kmp.test.ts @@ -184,6 +184,27 @@ describe("useConnections over the Kotlin SDK (HTTP)", () => { }); }); + it("keeps the connection while the session runs its own handshake again", async () => { + const { result } = renderHook(() => useConnections()); + const conn = addRadio(result); + await act(() => result.current.connect(conn.id)); + const client = kmp.client; + if (!client) throw new Error("no client created"); + const statuses: string[] = []; + const off = useDeviceStore.subscribe(() => { + const status = saved(conn.id)?.status; + if (status && statuses.at(-1) !== status) statuses.push(status); + }); + + await act(() => meshRegistry.get(conn.id)?.rehandshake()); + + off(); + expect(statuses).not.toContain("error"); + expect(saved(conn.id)?.status).toBe("configured"); + expect(client.disconnects).toHaveLength(1); + expect(client.connects).toHaveLength(2); + }); + it("disconnects the old client before connecting the same connection again", async () => { const { result } = renderHook(() => useConnections()); const conn = addRadio(result); diff --git a/apps/web/src/pages/Connections/useConnections.ts b/apps/web/src/pages/Connections/useConnections.ts index 8a16ded64..69ee89a78 100644 --- a/apps/web/src/pages/Connections/useConnections.ts +++ b/apps/web/src/pages/Connections/useConnections.ts @@ -297,6 +297,7 @@ export function useConnections() { } if (state.kind === "disconnected") { if (!reconnecting) { + if (session.isRehandshaking) return; log.error("kmp: dropped without retrying", { id }); updateSavedConnection(id, { status: "error", @@ -391,6 +392,7 @@ export function useConnections() { }); sessionTeardowns.get(id)?.(); sessionTeardowns.delete(id); + meshRegistry.unregister(id); if ( error instanceof Error && (error.name === "serial-unavailable" || @@ -427,6 +429,10 @@ export function useConnections() { log.debug("connect: already connected", { id, status: conn.status }); return true; } + if (conn.status === "connecting" && sessionTeardowns.has(id)) { + log.debug("connect: already connecting", { id, ...conn.reconnect }); + return true; + } log.info("connect: enter", { id, @@ -515,6 +521,7 @@ export function useConnections() { const refreshStatuses = useCallback(async () => { const candidates = connections.filter( (c) => + !sessionTeardowns.has(c.id) && c.status !== "connected" && c.status !== "configured" && c.status !== "configuring", diff --git a/apps/web/src/tests/fakeBrowserDevices.ts b/apps/web/src/tests/fakeBrowserDevices.ts index 2bd6095db..f696ede11 100644 --- a/apps/web/src/tests/fakeBrowserDevices.ts +++ b/apps/web/src/tests/fakeBrowserDevices.ts @@ -59,7 +59,10 @@ export class FrameSplitter { export class FakeRadio { readonly received: Protobuf.Mesh.ToRadio[] = []; - constructor(readonly myNodeNum = 0x0a0b0c0d) {} + constructor( + readonly myNodeNum = 0x0a0b0c0d, + readonly mesh: { nodes?: number; channels?: number } = {}, + ) {} respond(toRadio: Uint8Array): Uint8Array[] { const message = fromBinary(Protobuf.Mesh.ToRadioSchema, toRadio); @@ -67,6 +70,30 @@ export class FakeRadio { switch (message.payloadVariant.case) { case "wantConfigId": { const nonce = message.payloadVariant.value; + const others = Array.from({ length: this.mesh.nodes ?? 0 }, (_, i) => + fromRadio({ + case: "nodeInfo", + value: create(Protobuf.Mesh.NodeInfoSchema, { + num: 0x1000 + i, + user: { longName: `Node ${i}`, shortName: `N${i}` }, + }), + }), + ); + const channels = Array.from( + { length: this.mesh.channels ?? 0 }, + (_, index) => + fromRadio({ + case: "channel", + value: create(Protobuf.Channel.ChannelSchema, { + index, + role: + index === 0 + ? Protobuf.Channel.Channel_Role.PRIMARY + : Protobuf.Channel.Channel_Role.SECONDARY, + settings: { name: `ch${index}` }, + }), + }), + ); return [ fromRadio({ case: "myInfo", @@ -81,6 +108,8 @@ export class FakeRadio { user: { longName: "Fake radio", shortName: "FAKE" }, }), }), + ...channels, + ...others, fromRadio({ case: "configCompleteId", value: nonce }), ]; } From 86aa1108a6c34e08f82d64b7f9a0c927156cf485 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 12:35:21 -0500 Subject: [PATCH 28/49] feat(web): allow only one tab to run the app The second tab shows an overlay instead of mounting; Use here asks the owner to disconnect and release the app lock, stealing it after 3s. --- apps/web/public/i18n/locales/en/ui.json | 6 + apps/web/src/components/TabLockGate.test.tsx | 105 +++++++++ apps/web/src/components/TabLockGate.tsx | 20 ++ apps/web/src/components/TabLockOverlay.tsx | 50 +++++ apps/web/src/core/hooks/useTabLock.ts | 10 + apps/web/src/core/tabLock.test.ts | 206 ++++++++++++++++++ apps/web/src/core/tabLock.ts | 184 ++++++++++++++++ apps/web/src/index.tsx | 11 +- .../Connections/useConnections.kmp.test.ts | 15 +- .../src/pages/Connections/useConnections.ts | 76 ++++--- apps/web/src/tests/fakeTabEnvironment.ts | 144 ++++++++++++ 11 files changed, 792 insertions(+), 35 deletions(-) create mode 100644 apps/web/src/components/TabLockGate.test.tsx create mode 100644 apps/web/src/components/TabLockGate.tsx create mode 100644 apps/web/src/components/TabLockOverlay.tsx create mode 100644 apps/web/src/core/hooks/useTabLock.ts create mode 100644 apps/web/src/core/tabLock.test.ts create mode 100644 apps/web/src/core/tabLock.ts create mode 100644 apps/web/src/tests/fakeTabEnvironment.ts diff --git a/apps/web/public/i18n/locales/en/ui.json b/apps/web/public/i18n/locales/en/ui.json index 802a113e8..9892da8e8 100644 --- a/apps/web/public/i18n/locales/en/ui.json +++ b/apps/web/public/i18n/locales/en/ui.json @@ -368,5 +368,11 @@ "copyright": "Meshtastic® Copyright Meshtastic LLC", "licenseNotice": "Free software under the GNU General Public License v3, with no warranty. You may redistribute it under the same license." } + }, + "tabLock": { + "title": "Meshtastic is open in another tab", + "description": "Only one tab can use your radio and saved data at a time. Use it here to move Meshtastic to this tab and disconnect the other one.", + "useHere": "Use here", + "claiming": "Switching to this tab…" } } diff --git a/apps/web/src/components/TabLockGate.test.tsx b/apps/web/src/components/TabLockGate.test.tsx new file mode 100644 index 000000000..cecdd7989 --- /dev/null +++ b/apps/web/src/components/TabLockGate.test.tsx @@ -0,0 +1,105 @@ +import { TabLockGate } from "@components/TabLockGate.tsx"; +import { + createFakeChannelHub, + createFakeLocks, +} from "@app/tests/fakeTabEnvironment.ts"; +import { createTabLock } from "@core/tabLock.ts"; +import { render, screen, waitFor, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { useEffect } from "react"; +import { describe, expect, it, vi } from "vitest"; + +function environment() { + const locks = createFakeLocks(); + const hub = createFakeChannelHub(); + const mounts = { storage: vi.fn(), connect: vi.fn() }; + const tab = () => { + const disconnectAll = vi.fn(async () => {}); + const lock = createTabLock({ + locks, + openChannel: (name) => hub.open(name), + onRelinquish: disconnectAll, + }); + lock.start(); + return { lock, disconnectAll }; + }; + function App() { + useEffect(() => { + mounts.storage(); + mounts.connect(); + }, []); + return

app

; + } + return { tab, mounts, App }; +} + +describe("TabLockGate", () => { + it("mounts the app in the first tab", async () => { + const { tab, mounts, App } = environment(); + const a = tab(); + render( + + + , + ); + expect(await screen.findByText("app")).toBeTruthy(); + expect(mounts.connect).toHaveBeenCalledTimes(1); + expect(screen.queryByRole("dialog")).toBeNull(); + }); + + it("shows the overlay in a second tab and mounts nothing", async () => { + const { tab, mounts, App } = environment(); + const a = tab(); + render( + + + , + ); + await screen.findByText("app"); + mounts.connect.mockClear(); + mounts.storage.mockClear(); + + const b = tab(); + render( + + + , + ); + const dialog = await screen.findByRole("dialog", { + name: "Meshtastic is open in another tab", + }); + expect(dialog.getAttribute("aria-modal")).toBe("true"); + expect(document.activeElement).toBe( + screen.getByRole("button", { name: "Use here" }), + ); + expect(mounts.connect).not.toHaveBeenCalled(); + expect(mounts.storage).not.toHaveBeenCalled(); + }); + + it("moves the app to the tab whose Use here was pressed", async () => { + const { tab, App } = environment(); + const a = tab(); + const b = tab(); + const first = render( + +

owner A

+
, + ); + await screen.findByText("owner A"); + const second = render( + + + , + ); + await userEvent.click( + await within(second.container).findByRole("button", { name: "Use here" }), + ); + + await waitFor(() => + expect(within(second.container).getByText("app")).toBeTruthy(), + ); + expect(a.disconnectAll).toHaveBeenCalledTimes(1); + expect(await within(first.container).findByRole("dialog")).toBeTruthy(); + expect(within(first.container).queryByText("owner A")).toBeNull(); + }); +}); diff --git a/apps/web/src/components/TabLockGate.tsx b/apps/web/src/components/TabLockGate.tsx new file mode 100644 index 000000000..40509ed9b --- /dev/null +++ b/apps/web/src/components/TabLockGate.tsx @@ -0,0 +1,20 @@ +import { TabLockOverlay } from "@components/TabLockOverlay.tsx"; +import { useTabLock } from "@core/hooks/useTabLock.ts"; +import type { TabLock } from "@core/tabLock.ts"; +import type { ReactNode } from "react"; + +export interface TabLockGateProps { + lock: TabLock; + children: ReactNode; +} + +/** Mounts the app only in the tab that owns the app lock. */ +export function TabLockGate({ lock, children }: TabLockGateProps) { + const { status, takeOver } = useTabLock(lock); + + if (status === "owner") return children; + if (status === "pending") return null; + return ( + + ); +} diff --git a/apps/web/src/components/TabLockOverlay.tsx b/apps/web/src/components/TabLockOverlay.tsx new file mode 100644 index 000000000..90a7954bd --- /dev/null +++ b/apps/web/src/components/TabLockOverlay.tsx @@ -0,0 +1,50 @@ +import { useEffect, useRef } from "react"; +import { useTranslation } from "react-i18next"; + +export interface TabLockOverlayProps { + claiming: boolean; + onUseHere: () => void; +} + +export function TabLockOverlay({ claiming, onUseHere }: TabLockOverlayProps) { + const { t } = useTranslation("ui"); + const buttonRef = useRef(null); + + useEffect(() => { + buttonRef.current?.focus(); + }, []); + + return ( +
+
+

+ {t("tabLock.title")} +

+

+ {t("tabLock.description")} +

+ +
+
+ ); +} diff --git a/apps/web/src/core/hooks/useTabLock.ts b/apps/web/src/core/hooks/useTabLock.ts new file mode 100644 index 000000000..df86be404 --- /dev/null +++ b/apps/web/src/core/hooks/useTabLock.ts @@ -0,0 +1,10 @@ +import type { TabLock, TabLockStatus } from "@core/tabLock.ts"; +import { useSyncExternalStore } from "react"; + +export function useTabLock(lock: TabLock): { + status: TabLockStatus; + takeOver: () => void; +} { + const status = useSyncExternalStore(lock.subscribe, lock.getStatus); + return { status, takeOver: lock.takeOver }; +} diff --git a/apps/web/src/core/tabLock.test.ts b/apps/web/src/core/tabLock.test.ts new file mode 100644 index 000000000..3f98a89a8 --- /dev/null +++ b/apps/web/src/core/tabLock.test.ts @@ -0,0 +1,206 @@ +import { + createFakeChannelHub, + createFakeLocks, +} from "@app/tests/fakeTabEnvironment.ts"; +import { + APP_LOCK_NAME, + createTabLock, + STEAL_AFTER_MS, + TAB_CHANNEL_NAME, +} from "@core/tabLock.ts"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const flush = async () => { + for (let i = 0; i < 30; i++) await Promise.resolve(); +}; + +function setup() { + const locks = createFakeLocks(); + const hub = createFakeChannelHub(); + const tab = (relinquish: () => Promise = async () => {}) => { + const onRelinquish = vi.fn(relinquish); + const lock = createTabLock({ + locks, + openChannel: (name) => hub.open(name), + onRelinquish, + }); + return { lock, onRelinquish }; + }; + return { locks, tab }; +} + +describe("tabLock", () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + afterEach(() => { + vi.useRealTimers(); + }); + + it("makes the first tab the owner", async () => { + const { locks, tab } = setup(); + const a = tab(); + expect(a.lock.getStatus()).toBe("pending"); + a.lock.start(); + await flush(); + expect(a.lock.getStatus()).toBe("owner"); + expect(locks.isHeld(APP_LOCK_NAME)).toBe(true); + }); + + it("leaves a second tab waiting and quiet", async () => { + const { tab } = setup(); + const a = tab(); + const b = tab(); + a.lock.start(); + await flush(); + b.lock.start(); + await flush(); + expect(b.lock.getStatus()).toBe("other"); + expect(a.lock.getStatus()).toBe("owner"); + expect(a.onRelinquish).not.toHaveBeenCalled(); + expect(b.onRelinquish).not.toHaveBeenCalled(); + }); + + it("hands the app over when the second tab takes over", async () => { + const { locks, tab } = setup(); + const a = tab(); + const b = tab(); + a.lock.start(); + await flush(); + b.lock.start(); + await flush(); + + b.lock.takeOver(); + expect(b.lock.getStatus()).toBe("claiming"); + await flush(); + + expect(a.onRelinquish).toHaveBeenCalledTimes(1); + expect(a.lock.getStatus()).toBe("other"); + expect(b.lock.getStatus()).toBe("owner"); + expect(locks.isHeld(APP_LOCK_NAME)).toBe(true); + expect(b.onRelinquish).not.toHaveBeenCalled(); + }); + + it("lets the old owner take the app back", async () => { + const { tab } = setup(); + const a = tab(); + const b = tab(); + a.lock.start(); + await flush(); + b.lock.start(); + await flush(); + b.lock.takeOver(); + await flush(); + + a.lock.takeOver(); + await flush(); + + expect(b.onRelinquish).toHaveBeenCalledTimes(1); + expect(a.lock.getStatus()).toBe("owner"); + expect(b.lock.getStatus()).toBe("other"); + }); + + it("takes the lock once the owner finishes releasing, without stealing", async () => { + const { tab } = setup(); + let finish: () => void = () => {}; + const a = tab(() => new Promise((resolve) => (finish = resolve))); + const b = tab(); + a.lock.start(); + await flush(); + b.lock.start(); + await flush(); + + b.lock.takeOver(); + await vi.advanceTimersByTimeAsync(STEAL_AFTER_MS - 1); + expect(b.lock.getStatus()).toBe("claiming"); + expect(a.lock.getStatus()).toBe("owner"); + + finish(); + await flush(); + expect(b.lock.getStatus()).toBe("owner"); + expect(a.lock.getStatus()).toBe("other"); + await vi.advanceTimersByTimeAsync(STEAL_AFTER_MS); + expect(a.onRelinquish).toHaveBeenCalledTimes(1); + }); + + it("steals the lock from an owner that does not answer", async () => { + const { tab } = setup(); + const a = tab(() => new Promise(() => {})); + const b = tab(); + a.lock.start(); + await flush(); + b.lock.start(); + await flush(); + + b.lock.takeOver(); + await vi.advanceTimersByTimeAsync(STEAL_AFTER_MS - 1); + expect(b.lock.getStatus()).toBe("claiming"); + + await vi.advanceTimersByTimeAsync(1); + expect(b.lock.getStatus()).toBe("owner"); + expect(a.lock.getStatus()).toBe("other"); + expect(a.onRelinquish).toHaveBeenCalledTimes(1); + }); + + it("tears down an owner whose lock was stolen", async () => { + const { locks, tab } = setup(); + const a = tab(); + a.lock.start(); + await flush(); + + void locks + .request(APP_LOCK_NAME, { steal: true }, () => new Promise(() => {})) + .catch(() => {}); + await flush(); + + expect(a.onRelinquish).toHaveBeenCalledTimes(1); + expect(a.lock.getStatus()).toBe("other"); + }); + + it("ignores takeover requests while not the owner", async () => { + const { tab } = setup(); + const a = tab(); + const b = tab(); + const c = tab(); + a.lock.start(); + await flush(); + b.lock.start(); + c.lock.start(); + await flush(); + + b.lock.takeOver(); + await flush(); + + expect(c.onRelinquish).not.toHaveBeenCalled(); + expect(c.lock.getStatus()).toBe("other"); + }); + + it("is the owner when navigator.locks is missing", async () => { + const hub = createFakeChannelHub(); + const openChannel = vi.fn((name: string) => hub.open(name)); + const lock = createTabLock({ + locks: undefined, + openChannel, + onRelinquish: async () => {}, + }); + lock.start(); + expect(lock.getStatus()).toBe("owner"); + expect(openChannel).not.toHaveBeenCalled(); + }); + + it("listens on the shared tab channel and notifies subscribers", async () => { + const hub = createFakeChannelHub(); + const open = vi.spyOn(hub, "open"); + const lock = createTabLock({ + locks: createFakeLocks(), + openChannel: (name) => hub.open(name), + onRelinquish: async () => {}, + }); + const seen: string[] = []; + lock.subscribe(() => seen.push(lock.getStatus())); + lock.start(); + await flush(); + expect(open).toHaveBeenCalledWith(TAB_CHANNEL_NAME); + expect(seen).toEqual(["owner"]); + }); +}); diff --git a/apps/web/src/core/tabLock.ts b/apps/web/src/core/tabLock.ts new file mode 100644 index 000000000..266ad043b --- /dev/null +++ b/apps/web/src/core/tabLock.ts @@ -0,0 +1,184 @@ +import { createLogger } from "@core/log.ts"; + +const log = createLogger("tabLock"); + +export const APP_LOCK_NAME = "meshtastic:web:app"; +export const TAB_CHANNEL_NAME = "meshtastic:web:tab"; +export const STEAL_AFTER_MS = 3000; + +/** + * - `pending`: the lock has not been asked for yet. + * - `owner`: this tab holds the lock and runs the app. + * - `other`: another tab runs the app. + * - `claiming`: this tab asked the owner to let go and waits for the lock. + */ +export type TabLockStatus = "pending" | "owner" | "other" | "claiming"; + +export interface AppLockManager { + request( + name: string, + options: LockOptions, + callback: (lock: Lock | null) => Promise, + ): Promise; +} + +export interface TabChannel { + onmessage: ((event: MessageEvent) => void) | null; + postMessage(message: unknown): void; + close(): void; +} + +export interface TabLockEnvironment { + /** Absent where `navigator.locks` is missing; the tab then owns the app. */ + locks: AppLockManager | undefined; + openChannel: (name: string) => TabChannel; + /** Disconnects every live session before the lock is given up. */ + onRelinquish: () => Promise; +} + +export interface TabLock { + start(): void; + takeOver(): void; + getStatus(): TabLockStatus; + subscribe(listener: () => void): () => void; +} + +function isTakeover(data: unknown): boolean { + return ( + typeof data === "object" && + data !== null && + "type" in data && + data.type === "takeover" + ); +} + +/** + * One tab at a time runs the app: the owner holds a Web Lock for its + * lifetime and the browser frees it when the tab closes or crashes. Another + * tab asks the owner to let go over a BroadcastChannel and, if the owner + * does not release within `STEAL_AFTER_MS`, steals the lock. + */ +export function createTabLock(env: TabLockEnvironment): TabLock { + const listeners = new Set<() => void>(); + let status: TabLockStatus = "pending"; + let started = false; + let release: (() => void) | undefined; + let relinquishing = false; + let channel: TabChannel | undefined; + + const setStatus = (next: TabLockStatus) => { + if (status === next) return; + status = next; + for (const listener of listeners) listener(); + }; + + const teardown = async () => { + relinquishing = true; + try { + await env.onRelinquish(); + } catch (error) { + log.warn("relinquish: disconnect threw", { + message: error instanceof Error ? error.message : String(error), + }); + } finally { + relinquishing = false; + } + }; + + const onGranted = async (lock: Lock | null): Promise => { + if (!lock) { + log.info("another tab owns the app"); + setStatus("other"); + return; + } + log.info("this tab owns the app"); + const held = new Promise((resolve) => { + release = resolve; + }); + setStatus("owner"); + return held; + }; + + const watch = (request: Promise) => { + request.then( + () => {}, + (error) => { + if (status !== "owner") return; + log.warn("lock lost", { + message: error instanceof Error ? error.message : String(error), + }); + release = undefined; + setStatus("other"); + if (!relinquishing) void teardown(); + }, + ); + }; + + const relinquish = async () => { + if (relinquishing) return; + const held = release; + log.info("another tab asked for the app"); + await teardown(); + if (release !== held || status !== "owner") return; + release = undefined; + setStatus("other"); + held?.(); + }; + + return { + start() { + if (started) return; + started = true; + const { locks } = env; + if (!locks) { + log.info("navigator.locks missing, this tab owns the app"); + setStatus("owner"); + return; + } + const opened = env.openChannel(TAB_CHANNEL_NAME); + opened.onmessage = (event) => { + if (isTakeover(event.data) && status === "owner") void relinquish(); + }; + channel = opened; + watch(locks.request(APP_LOCK_NAME, { ifAvailable: true }, onGranted)); + }, + takeOver() { + const { locks } = env; + if (!locks || status === "owner" || status === "claiming") return; + setStatus("claiming"); + channel?.postMessage({ type: "takeover" }); + const waiting = new AbortController(); + const stealTimer = setTimeout(() => { + log.warn("owner did not release, stealing the lock"); + waiting.abort(); + watch(locks.request(APP_LOCK_NAME, { steal: true }, onGranted)); + }, STEAL_AFTER_MS); + watch( + locks.request(APP_LOCK_NAME, { signal: waiting.signal }, (lock) => { + clearTimeout(stealTimer); + return onGranted(lock); + }), + ); + }, + getStatus: () => status, + subscribe(listener) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + }; +} + +export function createBrowserTabLock( + onRelinquish: () => Promise, +): TabLock { + return createTabLock({ + locks: + typeof navigator !== "undefined" && "locks" in navigator + ? navigator.locks + : undefined, + openChannel: (name) => new BroadcastChannel(name), + onRelinquish, + }); +} diff --git a/apps/web/src/index.tsx b/apps/web/src/index.tsx index fba49ab48..3cf225be3 100644 --- a/apps/web/src/index.tsx +++ b/apps/web/src/index.tsx @@ -9,8 +9,11 @@ import { Suspense } from "react"; import { createRoot } from "react-dom/client"; import "./i18n-config.ts"; import { router } from "@app/routes.tsx"; +import { TabLockGate } from "@components/TabLockGate.tsx"; import { meshRegistry } from "@core/kmp/registry.ts"; import { useAppStore } from "@core/stores"; +import { createBrowserTabLock } from "@core/tabLock.ts"; +import { disconnectAllConnections } from "@app/pages/Connections/useConnections.ts"; import { MeshRegistryProvider } from "@core/kmp/hooks"; import { type createRouter, RouterProvider } from "@tanstack/react-router"; import { useTranslation } from "react-i18next"; @@ -22,6 +25,8 @@ declare module "@tanstack/react-router" { } const container = document.getElementById("root") as HTMLElement; const root = createRoot(container); +const tabLock = createBrowserTabLock(disconnectAllConnections); +tabLock.start(); function IndexPage() { enableMapSet(); @@ -49,4 +54,8 @@ function IndexPage() { ); } -root.render(); +root.render( + + + , +); diff --git a/apps/web/src/pages/Connections/useConnections.kmp.test.ts b/apps/web/src/pages/Connections/useConnections.kmp.test.ts index d833d7f9c..ddfbcb79e 100644 --- a/apps/web/src/pages/Connections/useConnections.kmp.test.ts +++ b/apps/web/src/pages/Connections/useConnections.kmp.test.ts @@ -7,7 +7,7 @@ import { Protobuf } from "@core/protobuf.ts"; import type { StorageJs } from "@meshtastic/sdk-kmp"; import { act, renderHook } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import { useConnections } from "./useConnections.ts"; +import { disconnectAllConnections, useConnections } from "./useConnections.ts"; const kmp = vi.hoisted( (): { @@ -109,6 +109,19 @@ describe("useConnections over the Kotlin SDK (HTTP)", () => { expect(saved(conn.id)?.status).toBe("disconnected"); }); + it("disconnects every live session through the drawer's teardown", async () => { + const { result } = renderHook(() => useConnections()); + const conn = addRadio(result); + await act(() => result.current.connect(conn.id)); + const client = kmp.client; + if (!client) throw new Error("no client created"); + + await act(() => disconnectAllConnections()); + expect(client.disconnects).toHaveLength(1); + expect(saved(conn.id)?.status).toBe("disconnected"); + expect(meshRegistry.get(conn.id)?.kmp).toBe(client); + }); + it("shows the SDK's reconnect attempts and reports when they run out", async () => { const { result } = renderHook(() => useConnections()); const conn = result.current.addConnection({ diff --git a/apps/web/src/pages/Connections/useConnections.ts b/apps/web/src/pages/Connections/useConnections.ts index 69ee89a78..d0d1a29c1 100644 --- a/apps/web/src/pages/Connections/useConnections.ts +++ b/apps/web/src/pages/Connections/useConnections.ts @@ -140,6 +140,46 @@ async function clientFactory( const savedConnection = (id: ConnectionId): Connection | undefined => useDeviceStore.getState().savedConnections.find((c) => c.id === id); +async function teardownSession(id: ConnectionId): Promise { + log.debug("teardown: enter", { id }); + sessionTeardowns.get(id)?.(); + sessionTeardowns.delete(id); + try { + await meshRegistry.get(id)?.disconnect(); + } catch (e) { + log.warn("teardown: disconnect threw", { + name: e instanceof Error ? e.name : undefined, + message: e instanceof Error ? e.message : String(e), + }); + } + log.debug("teardown: done", { id }); +} + +async function disconnectConnection(id: ConnectionId): Promise { + const conn = savedConnection(id); + if (!conn) return; + try { + await teardownSession(id); + if (conn.meshDeviceId) { + useDeviceStore + .getState() + .getDevice(conn.meshDeviceId) + ?.setConnectionId(null); + } + } finally { + useDeviceStore + .getState() + .updateSavedConnection(id, { status: "disconnected", error: undefined }); + } +} + +/** Disconnects every live session, as the drawer's Disconnect does. */ +export async function disconnectAllConnections(): Promise { + for (const id of [...sessionTeardowns.keys()]) { + await disconnectConnection(id); + } +} + export function useConnections() { const connections = useDeviceStore((s) => s.savedConnections); const addSavedConnection = useDeviceStore((s) => s.addSavedConnection); @@ -169,20 +209,7 @@ export function useConnections() { [updateSavedConnection], ); - const teardown = useCallback(async (id: ConnectionId) => { - log.debug("teardown: enter", { id }); - sessionTeardowns.get(id)?.(); - sessionTeardowns.delete(id); - try { - await meshRegistry.get(id)?.disconnect(); - } catch (e) { - log.warn("teardown: disconnect threw", { - name: e instanceof Error ? e.name : undefined, - message: e instanceof Error ? e.message : String(e), - }); - } - log.debug("teardown: done", { id }); - }, []); + const teardown = teardownSession; const removeConnection = useCallback( async (id: ConnectionId) => { @@ -472,27 +499,10 @@ export function useConnections() { return false; } }, - [updateStatus, updateSavedConnection, connectThroughKmp, teardown], + [updateStatus, updateSavedConnection, connectThroughKmp], ); - const disconnect = useCallback( - async (id: ConnectionId) => { - const conn = connections.find((c) => c.id === id); - if (!conn) return; - try { - await teardown(id); - if (conn.meshDeviceId) { - useDeviceStore - .getState() - .getDevice(conn.meshDeviceId) - ?.setConnectionId(null); - } - } finally { - updateSavedConnection(id, { status: "disconnected", error: undefined }); - } - }, - [connections, updateSavedConnection, teardown], - ); + const disconnect = disconnectConnection; const addConnection = useCallback( (input: NewConnection) => { diff --git a/apps/web/src/tests/fakeTabEnvironment.ts b/apps/web/src/tests/fakeTabEnvironment.ts new file mode 100644 index 000000000..359cb0c12 --- /dev/null +++ b/apps/web/src/tests/fakeTabEnvironment.ts @@ -0,0 +1,144 @@ +import type { AppLockManager, TabChannel } from "@core/tabLock.ts"; + +type Granted = (lock: Lock | null) => Promise; + +interface Pending { + callback: Granted; + options: LockOptions; + resolve: (value: unknown) => void; + reject: (reason: unknown) => void; +} + +interface Holder { + steal: () => void; +} + +const abortError = (message: string) => new DOMException(message, "AbortError"); + +export interface FakeLocks extends AppLockManager { + isHeld(name: string): boolean; + pendingCount(name: string): number; +} + +export function createFakeLocks(): FakeLocks { + const holders = new Map(); + const queues = new Map(); + + const queueFor = (name: string): Pending[] => { + let queue = queues.get(name); + if (!queue) { + queue = []; + queues.set(name, queue); + } + return queue; + }; + + const grant = (name: string, pending: Pending): void => { + let stolen: (reason: unknown) => void = () => {}; + const stolenPromise = new Promise((_, reject) => { + stolen = reject; + }); + const holder: Holder = { + steal: () => + stolen(abortError("The lock was stolen by another request.")), + }; + holders.set(name, holder); + const lock: Lock = { name, mode: "exclusive" }; + const finish = () => { + if (holders.get(name) === holder) { + holders.delete(name); + grantNext(name); + } + }; + Promise.race([ + Promise.resolve().then(() => pending.callback(lock)), + stolenPromise, + ]).then( + (value) => { + finish(); + pending.resolve(value); + }, + (reason) => { + finish(); + pending.reject(reason); + }, + ); + }; + + const grantNext = (name: string): void => { + const next = queueFor(name).shift(); + if (next) grant(name, next); + }; + + return { + isHeld: (name) => holders.has(name), + pendingCount: (name) => queueFor(name).length, + request(name, options, callback) { + return new Promise((resolve, reject) => { + const pending: Pending = { callback, options, resolve, reject }; + const held = holders.get(name); + if (options.steal) { + held?.steal(); + grant(name, pending); + return; + } + if (!held) { + grant(name, pending); + return; + } + if (options.ifAvailable) { + Promise.resolve() + .then(() => callback(null)) + .then(resolve, reject); + return; + } + if (options.signal?.aborted) { + reject(abortError("The request was aborted.")); + return; + } + queueFor(name).push(pending); + options.signal?.addEventListener("abort", () => { + const queue = queueFor(name); + const index = queue.indexOf(pending); + if (index === -1) return; + queue.splice(index, 1); + reject(abortError("The request was aborted.")); + }); + }); + }, + }; +} + +export interface FakeChannelHub { + open(name: string): TabChannel; +} + +export function createFakeChannelHub(): FakeChannelHub { + const channels = new Map>(); + return { + open(name) { + let peers = channels.get(name); + if (!peers) { + peers = new Set(); + channels.set(name, peers); + } + const members = peers; + const channel: TabChannel = { + onmessage: null, + postMessage(message) { + for (const peer of members) { + if (peer === channel) continue; + queueMicrotask(() => { + peer.onmessage?.(new MessageEvent("message", { data: message })); + }); + } + }, + close() { + members.delete(channel); + }, + }; + members.add(channel); + return channel; + }, + }; +} From 7f31adb6d13531de5eb59af7e185276a8eda40bd Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 12:48:44 -0500 Subject: [PATCH 29/49] fix(web): take the own node from the SDK when its handshake frame was lost MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fresh serial connects log "undecodable FromRadio frame" during Stage 1 and sometimes leave the sidebar on "Loading…": the own node never resolves. The facade's frame hand-off is a copy at offset 0 (copyOfRange slices, the Uint8Array view is over that copy), so the web and the engine decode the same bytes; a frame that fails in the web fails in the engine too and the engine recovers through its retries while the web kept a single-frame dependency for its own node. - The facade exposes `myNodeNum` from the handshake's my_info (unsigned) and `ownNode` as the SDK holds it. - On `connected` the session adopts both when the frame stream left them unset, and fills the own node's user from the get_owner response the SDK fetches at Ready. - Tests feed frames as views into a larger buffer, several per chunk and split across chunks, and assert the bytes reaching JS decode. --- apps/web/src/core/kmp/device.ts | 7 +++ apps/web/src/core/kmp/fakeClient.ts | 1 + apps/web/src/core/kmp/serialClient.test.ts | 51 ++++++++++++++++++ apps/web/src/core/kmp/session.test.ts | 52 +++++++++++++++++++ apps/web/src/core/kmp/session.ts | 31 +++++++++-- .../kotlin/org/meshtastic/sdk/js/Client.kt | 10 +++- .../meshtastic/sdk/js/FrameAssemblerTest.kt | 21 ++++++++ 7 files changed, 168 insertions(+), 5 deletions(-) diff --git a/apps/web/src/core/kmp/device.ts b/apps/web/src/core/kmp/device.ts index d01a55e52..5662b27ca 100644 --- a/apps/web/src/core/kmp/device.ts +++ b/apps/web/src/core/kmp/device.ts @@ -125,6 +125,13 @@ export class DeviceClient { } } + /** Names the local node from the SDK's state when no `my_info` frame did. */ + applyMyNodeNum(myNodeNum: number): void { + if (this.myNodeNumStore.peek() === undefined) { + this.myNodeNumStore.value = myNodeNum; + } + } + applyMyNodeInfo(info: Protobuf.Mesh.MyNodeInfo): void { this.myNodeInfoStore.value = info; this.myNodeNumStore.value = info.myNodeNum; diff --git a/apps/web/src/core/kmp/fakeClient.ts b/apps/web/src/core/kmp/fakeClient.ts index fb88ef8bd..e04a7bba6 100644 --- a/apps/web/src/core/kmp/fakeClient.ts +++ b/apps/web/src/core/kmp/fakeClient.ts @@ -64,6 +64,7 @@ export class FakeAdmin implements AdminJs { export class FakeKmpClient implements MeshtasticClient { connectionState: ConnectionStateJs = state("disconnected"); myNodeNum: number | null = null; + ownNode: Uint8Array | null = null; readonly texts: Array<{ text: string; to: number; diff --git a/apps/web/src/core/kmp/serialClient.test.ts b/apps/web/src/core/kmp/serialClient.test.ts index 62f7d24e5..f257be747 100644 --- a/apps/web/src/core/kmp/serialClient.test.ts +++ b/apps/web/src/core/kmp/serialClient.test.ts @@ -1,8 +1,11 @@ // @vitest-environment node +import { create, toBinary } from "@bufbuild/protobuf"; +import { Protobuf } from "@core/protobuf.ts"; import type { ConnectionStateJs } from "@meshtastic/sdk-kmp"; import { FakeRadio, FakeSerialPort, + framed, installSerial, uninstallBrowserDevices, } from "@app/tests/fakeBrowserDevices.ts"; @@ -160,6 +163,54 @@ describe("createSerialClient (Kotlin facade over a fake navigator.serial)", () = }, 15_000); } + it("decodes frames the port delivers as views into a larger buffer, several per chunk and split", async () => { + const radio = new FakeRadio(); + const port = new FakeSerialPort(ids, radio); + installSerial([port]); + const client = await createSerialClient(ids); + clients.push(client); + const session = new MeshSession(client); + const seen: string[] = []; + session.events.onFromRadio.subscribe((frame) => { + seen.push(frame.payloadVariant.case ?? "none"); + }); + await client.connect(); + await connected(client); + seen.length = 0; + + const first = toBinary( + Protobuf.Mesh.FromRadioSchema, + create(Protobuf.Mesh.FromRadioSchema, { + payloadVariant: { + case: "nodeInfo", + value: create(Protobuf.Mesh.NodeInfoSchema, { + num: 0x2000, + user: { longName: "x".repeat(200) }, + }), + }, + }), + ); + const second = toBinary( + Protobuf.Mesh.FromRadioSchema, + create(Protobuf.Mesh.FromRadioSchema, { + payloadVariant: { case: "configCompleteId", value: 5 }, + }), + ); + const wire = new Uint8Array([...framed(first), ...framed(second)]); + const padded = new Uint8Array(wire.length + 32); + padded.set(wire, 16); + const view = padded.subarray(16, 16 + wire.length); + port.push(view.subarray(0, 100)); + port.push(view.subarray(100, wire.length - 3)); + port.push(view.subarray(wire.length - 3)); + + await vi.waitFor(() => + expect(seen).toEqual(["nodeInfo", "configCompleteId"]), + ); + expect(session.nodes.byNum(0x2000)?.user?.longName).toBe("x".repeat(200)); + session.close(); + }, 15_000); + it("hands the session its own node and channels again after an auto-reconnect", async () => { const radio = new FakeRadio(0x0a0b0c0d, { nodes: 3, channels: 2 }); const port = new FakeSerialPort(ids, radio); diff --git a/apps/web/src/core/kmp/session.test.ts b/apps/web/src/core/kmp/session.test.ts index 4cf56aed4..a7c9fa731 100644 --- a/apps/web/src/core/kmp/session.test.ts +++ b/apps/web/src/core/kmp/session.test.ts @@ -104,6 +104,58 @@ function connected(): { kmp: FakeKmpClient; session: MeshSession } { } describe("MeshSession", () => { + it("resolves the own node from the SDK's state when its handshake frames did not reach the web", () => { + const kmp = new FakeKmpClient(); + const session = new MeshSession(kmp); + kmp.myNodeNum = ME; + kmp.ownNode = toBinary( + Protobuf.Mesh.NodeInfoSchema, + create(Protobuf.Mesh.NodeInfoSchema, { + num: ME, + user: { longName: "Me", shortName: "ME" }, + }), + ); + kmp.setState(state("configuring")); + + kmp.setState(state("connected")); + + expect(session.device.myNodeNum.peek()).toBe(ME); + expect(session.nodes.byNum(ME)?.user?.longName).toBe("Me"); + }); + + it("fills in the own node's user from the owner the SDK fetched at Ready", () => { + const { kmp, session } = connected(); + const owner = create(Protobuf.Admin.AdminMessageSchema, { + payloadVariant: { + case: "getOwnerResponse", + value: create(Protobuf.Mesh.UserSchema, { + id: "!0a0b0c0d", + longName: "Owner", + shortName: "OWN", + }), + }, + }); + kmp.emitPacket( + toBinary( + Protobuf.Mesh.MeshPacketSchema, + create(Protobuf.Mesh.MeshPacketSchema, { + from: ME, + to: ME, + id: 7, + payloadVariant: { + case: "decoded", + value: create(Protobuf.Mesh.DataSchema, { + portnum: Protobuf.Portnums.PortNum.ADMIN_APP, + payload: toBinary(Protobuf.Admin.AdminMessageSchema, owner), + }), + }, + }), + ), + ); + + expect(session.nodes.byNum(ME)?.user?.longName).toBe("Owner"); + }); + it("reads the handshake into the device view and the progress counters", () => { const kmp = new FakeKmpClient(); const session = new MeshSession(kmp); diff --git a/apps/web/src/core/kmp/session.ts b/apps/web/src/core/kmp/session.ts index 40919f9b1..d43697cba 100644 --- a/apps/web/src/core/kmp/session.ts +++ b/apps/web/src/core/kmp/session.ts @@ -362,6 +362,7 @@ export class MeshSession { received: current.phase === "idle" ? { ...EMPTY_COUNTERS } : current.received, }; + this.adoptSdkIdentity(); return; } default: @@ -383,6 +384,27 @@ export class MeshSession { }; } + /** + * The SDK keeps the handshake's own-node state itself; a `my_info` or own + * `node_info` frame the web failed to decode must not leave the session + * without its node. + */ + private adoptSdkIdentity(): void { + const myNodeNum = this.kmp.myNodeNum; + if (!myNodeNum || myNodeNum <= 0) return; + this.device.applyMyNodeNum(myNodeNum); + if (this.nodes.byNum(myNodeNum)) return; + const own = this.kmp.ownNode; + if (own) { + this.nodes.applyChange({ + kind: "added", + node: own, + nodes: null, + nodeNum: myNodeNum, + }); + } + } + private handleFromRadio(bytes: Uint8Array): void { let frame: Protobuf.Mesh.FromRadio; try { @@ -550,10 +572,11 @@ export class MeshSession { data.payload, ); const response = admin.payloadVariant; - if ( - response.case === "getDeviceMetadataResponse" && - (meta.from === 0 || meta.from === this.myNodeNum) - ) { + const fromSelf = meta.from === 0 || meta.from === this.myNodeNum; + if (response.case === "getOwnerResponse" && fromSelf) { + this.nodes.patch(this.myNodeNum, { user: response.value }); + } + if (response.case === "getDeviceMetadataResponse" && fromSelf) { this.device.applyMetadata(response.value); this.events.onDeviceMetadataPacket.dispatch({ from: meta.from, diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt index 2208fe654..04a1a19e2 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt @@ -70,7 +70,15 @@ class MeshtasticClient internal constructor( val connectionState: ConnectionStateJs get() = client.connection.value.toJs(maxAttempts) - val myNodeNum: Int? get() = client.ownNode.value?.num + /** The local node number as an unsigned value, from the handshake's `my_info` or the own node. */ + val myNodeNum: Double? + get() { + val num = client.configBundle.value?.myInfo?.my_node_num?.takeIf { it != 0 } ?: client.ownNode.value?.num + return num?.toUInt()?.toDouble() + } + + /** The local node's `NodeInfo` as the SDK holds it, encoded; null before the handshake names it. */ + val ownNode: Uint8Array? get() = client.ownNode.value?.encodeJs() fun onConnectionState(cb: (ConnectionStateJs) -> Unit): () -> Unit = client.connection.onEach { cb(it.toJs(maxAttempts)) }.subscribe() diff --git a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/FrameAssemblerTest.kt b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/FrameAssemblerTest.kt index d1606a115..d4412b067 100644 --- a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/FrameAssemblerTest.kt +++ b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/FrameAssemblerTest.kt @@ -1,5 +1,6 @@ package org.meshtastic.sdk.js +import org.khronos.webgl.Uint8Array import org.meshtastic.sdk.Frame import kotlin.test.Test import kotlin.test.assertEquals @@ -48,4 +49,24 @@ class FrameAssemblerTest { assertEquals(516, frame.bytes.size) assertEquals(payload.toList(), payloadOf(frame).toList()) } + + @Test + fun payloads_handed_to_js_are_exact_copies_whatever_the_chunk_view_offsets() { + val first = ByteArray(300) { (it * 7).toByte() } + val second = byteArrayOf(0x94.toByte(), 0xC3.toByte(), 0x1A, 0x02, 0x08, 0x01) + val wire = framed(first).toByteArray() + framed(second).toByteArray() + val padded = Uint8Array(wire.size + 16) + for (i in wire.indices) padded.asDynamic()[i + 8] = wire[i] + val view = padded.subarray(8, 8 + wire.size) + val chunks = listOf(view.subarray(0, 150), view.subarray(150, 310), view.subarray(310, view.length)) + + for (chunk in chunks) assembler.feed(chunk.toByteArray()) + + assertEquals(2, frames.size) + val payloads = frames.map { payloadOf(it).toUint8Array() } + assertEquals(first.toList(), payloads[0].toByteArray().toList()) + assertEquals(second.toList(), payloads[1].toByteArray().toList()) + assertEquals(0, payloads[1].byteOffset) + assertEquals(second.size, payloads[1].buffer.byteLength) + } } From 1cfdb04a7836444522b309b11674213c340b5d8e Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 12:48:45 -0500 Subject: [PATCH 30/49] fix(web): enable immer Map support before the device store rehydrates Gating the app behind the tab lock moved enableMapSet() from the first render to whenever the lock is granted. The device store's IndexedDB rehydration ran before that in a second tab (and in any tab that gets the lock late), produce() threw on the devices Map, the persisted devices were never rebuilt through deviceFactory, and the first Connect hit a method-less device: "device.setConnectionId is not a function", then DialogManager reading dialog.QR of undefined. The store enables Map support itself when it loads. The tab-lock gate also applies the stored theme before its first paint, so the overlay in a fresh second tab follows the user's theme. --- apps/web/src/components/TabLockGate.test.tsx | 23 +++++++++++++++ apps/web/src/components/TabLockGate.tsx | 4 ++- apps/web/src/core/hooks/useTheme.ts | 29 +++++++++++++------ apps/web/src/core/stores/deviceStore/index.ts | 4 ++- .../core/stores/deviceStore/mapSet.test.ts | 22 ++++++++++++++ apps/web/src/index.tsx | 2 -- 6 files changed, 71 insertions(+), 13 deletions(-) create mode 100644 apps/web/src/core/stores/deviceStore/mapSet.test.ts diff --git a/apps/web/src/components/TabLockGate.test.tsx b/apps/web/src/components/TabLockGate.test.tsx index cecdd7989..dcff4226f 100644 --- a/apps/web/src/components/TabLockGate.test.tsx +++ b/apps/web/src/components/TabLockGate.test.tsx @@ -102,4 +102,27 @@ describe("TabLockGate", () => { expect(await within(first.container).findByRole("dialog")).toBeTruthy(); expect(within(first.container).queryByText("owner A")).toBeNull(); }); + + it("paints the overlay in the stored theme before the app mounts", async () => { + localStorage.setItem("theme", "dark"); + document.documentElement.removeAttribute("data-theme"); + const { tab, App } = environment(); + const a = tab(); + render( + + + , + ); + await screen.findByText("app"); + const b = tab(); + render( + + + , + ); + await screen.findByRole("dialog"); + + expect(document.documentElement.getAttribute("data-theme")).toBe("dark"); + localStorage.removeItem("theme"); + }); }); diff --git a/apps/web/src/components/TabLockGate.tsx b/apps/web/src/components/TabLockGate.tsx index 40509ed9b..dbf057e50 100644 --- a/apps/web/src/components/TabLockGate.tsx +++ b/apps/web/src/components/TabLockGate.tsx @@ -1,7 +1,8 @@ import { TabLockOverlay } from "@components/TabLockOverlay.tsx"; import { useTabLock } from "@core/hooks/useTabLock.ts"; +import { applyStoredTheme } from "@core/hooks/useTheme.ts"; import type { TabLock } from "@core/tabLock.ts"; -import type { ReactNode } from "react"; +import { type ReactNode, useLayoutEffect } from "react"; export interface TabLockGateProps { lock: TabLock; @@ -11,6 +12,7 @@ export interface TabLockGateProps { /** Mounts the app only in the tab that owns the app lock. */ export function TabLockGate({ lock, children }: TabLockGateProps) { const { status, takeOver } = useTabLock(lock); + useLayoutEffect(applyStoredTheme, []); if (status === "owner") return children; if (status === "pending") return null; diff --git a/apps/web/src/core/hooks/useTheme.ts b/apps/web/src/core/hooks/useTheme.ts index fddaea192..f116e1395 100644 --- a/apps/web/src/core/hooks/useTheme.ts +++ b/apps/web/src/core/hooks/useTheme.ts @@ -4,16 +4,27 @@ type Theme = "light" | "dark" | "system"; const THEME_CHANGE_EVENT = "meshtastic:theme-change"; -export function useTheme() { - const getSystemTheme = () => - globalThis.matchMedia("(prefers-color-scheme: dark)").matches - ? "dark" - : "light"; - - const getStoredPreference = useCallback( - (): Theme => (localStorage.getItem("theme") as Theme) || "system", - [], +const getSystemTheme = (): Theme => + globalThis.matchMedia("(prefers-color-scheme: dark)").matches + ? "dark" + : "light"; + +const readStoredPreference = (): Theme => { + const stored = localStorage.getItem("theme"); + return stored === "light" || stored === "dark" ? stored : "system"; +}; + +/** Puts the stored (or system) theme on the document, for anything painted before `useTheme` runs. */ +export function applyStoredTheme(): void { + const preference = readStoredPreference(); + document.documentElement.setAttribute( + "data-theme", + preference === "system" ? getSystemTheme() : preference, ); +} + +export function useTheme() { + const getStoredPreference = useCallback(readStoredPreference, []); const [preference, setPreference] = useState(() => typeof window !== "undefined" ? getStoredPreference() : "light", diff --git a/apps/web/src/core/stores/deviceStore/index.ts b/apps/web/src/core/stores/deviceStore/index.ts index 775df55ef..6034d220c 100644 --- a/apps/web/src/core/stores/deviceStore/index.ts +++ b/apps/web/src/core/stores/deviceStore/index.ts @@ -3,7 +3,7 @@ import { meshRegistry } from "@core/kmp/registry.ts"; import { evictOldestEntries } from "@core/stores/utils/evictOldestEntries.ts"; import { createStorage } from "@core/stores/utils/indexDB.ts"; import { Protobuf, Types } from "@core/protobuf.ts"; -import { type Draft, produce } from "immer"; +import { enableMapSet, produce, type Draft } from "immer"; import { create as createStore, type StateCreator } from "zustand"; import { type PersistOptions, @@ -20,6 +20,8 @@ import type { WaypointWithMetadata, } from "./types.ts"; +enableMapSet(); + const IDB_KEY_NAME = "meshtastic-device-store"; const CURRENT_STORE_VERSION = 0; const DEVICESTORE_RETENTION_NUM = 10; diff --git a/apps/web/src/core/stores/deviceStore/mapSet.test.ts b/apps/web/src/core/stores/deviceStore/mapSet.test.ts new file mode 100644 index 000000000..1d3f65df8 --- /dev/null +++ b/apps/web/src/core/stores/deviceStore/mapSet.test.ts @@ -0,0 +1,22 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const immer = vi.hoisted(() => ({ enableMapSet: vi.fn() })); + +vi.mock("immer", async () => { + const actual = await vi.importActual("immer"); + immer.enableMapSet.mockImplementation(actual.enableMapSet); + return { ...actual, enableMapSet: immer.enableMapSet }; +}); + +describe("device store and immer's Map support", () => { + beforeEach(() => { + vi.resetModules(); + immer.enableMapSet.mockClear(); + }); + + it("enables Map support itself, before its persisted devices can rehydrate", async () => { + await import("./index.ts"); + + expect(immer.enableMapSet).toHaveBeenCalled(); + }); +}); diff --git a/apps/web/src/index.tsx b/apps/web/src/index.tsx index 3cf225be3..72baee51f 100644 --- a/apps/web/src/index.tsx +++ b/apps/web/src/index.tsx @@ -3,7 +3,6 @@ import "@app/index.css"; // Import feature flags and dev overrides import "@core/services/dev-overrides.ts"; -import { enableMapSet } from "immer"; import "maplibre-gl/dist/maplibre-gl.css"; import { Suspense } from "react"; import { createRoot } from "react-dom/client"; @@ -29,7 +28,6 @@ const tabLock = createBrowserTabLock(disconnectAllConnections); tabLock.start(); function IndexPage() { - enableMapSet(); const appStore = useAppStore(); const translation = useTranslation(); From 835653ea3c35f51eb88bde453a358e4acb8a7339 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 12:56:38 -0500 Subject: [PATCH 31/49] fix(web): release the database on tab takeover and bound SDK storage calls After "Use here" the old owner disconnected its sessions and released the app lock but kept the sqlocal worker, so its OPFS handle stayed with that tab. The new owner's Connect then stalled on storage the SDK touches during connect, and nothing bounded those calls. - disconnectAllConnections closes the sqlocal database after the sessions end and forgets the singleton, so the handle moves with the lock and this tab reopens cleanly if it takes the app back. - The SDK's storage adapter answers every call within 5 s: a read falls back to its empty value, a write counts as done, each with a warning. - Tests: takeover closes the storage; a database that never answers still lets connect proceed. --- apps/web/src/core/sdkStorage.test.ts | 49 +++++++++++ apps/web/src/core/sdkStorage.ts | 21 +++++ apps/web/src/core/storage/db.ts | 9 +- .../src/core/storage/deviceStorage.test.ts | 54 +++++++++++- apps/web/src/core/storage/deviceStorage.ts | 85 ++++++++++++++++++- .../Connections/useConnections.kmp.test.ts | 5 ++ .../src/pages/Connections/useConnections.ts | 2 + 7 files changed, 221 insertions(+), 4 deletions(-) create mode 100644 apps/web/src/core/sdkStorage.test.ts diff --git a/apps/web/src/core/sdkStorage.test.ts b/apps/web/src/core/sdkStorage.test.ts new file mode 100644 index 000000000..aecd13f08 --- /dev/null +++ b/apps/web/src/core/sdkStorage.test.ts @@ -0,0 +1,49 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const sqlocal = vi.hoisted(() => ({ + open: vi.fn(), + close: vi.fn(async () => {}), +})); + +vi.mock("@core/storage/db.ts", () => ({ + openSqlocalDb: sqlocal.open, +})); + +describe("sdkStorage singletons", () => { + beforeEach(() => { + vi.resetModules(); + sqlocal.open.mockReset(); + sqlocal.close.mockClear(); + sqlocal.open.mockImplementation(async () => ({ + db: {}, + storageType: "opfs", + persistent: true, + close: sqlocal.close, + })); + }); + + it("closes the database on request and reopens a fresh one afterwards", async () => { + const { getStorageDb, closeStorageDb } = await import("./sdkStorage.ts"); + const first = await getStorageDb(); + + await closeStorageDb(); + const second = await getStorageDb(); + + expect(sqlocal.close).toHaveBeenCalledTimes(1); + expect(sqlocal.open).toHaveBeenCalledTimes(2); + expect(second).not.toBe(first); + }); + + it("closing while nothing is open is a no-op", async () => { + const { closeStorageDb } = await import("./sdkStorage.ts"); + await closeStorageDb(); + expect(sqlocal.close).not.toHaveBeenCalled(); + }); + + it("swallows a close that fails, so the lock is still released", async () => { + sqlocal.close.mockRejectedValueOnce(new Error("worker gone")); + const { getStorageDb, closeStorageDb } = await import("./sdkStorage.ts"); + await getStorageDb(); + await expect(closeStorageDb()).resolves.toBeUndefined(); + }); +}); diff --git a/apps/web/src/core/sdkStorage.ts b/apps/web/src/core/sdkStorage.ts index ca6d069a6..eb4ca0b4c 100644 --- a/apps/web/src/core/sdkStorage.ts +++ b/apps/web/src/core/sdkStorage.ts @@ -43,4 +43,25 @@ export function getStorageDb(): Promise { return dbPromise; } +/** + * Closes the database and forgets it, so another tab can take the OPFS + * handle and the next `getStorageDb()` here opens afresh. A failing close is + * logged, not thrown: the caller is giving the app away and must finish. + */ +export async function closeStorageDb(): Promise { + const pending = dbPromise; + if (!pending) return; + dbPromise = undefined; + try { + const opened = await pending; + await opened.close(); + log.info("closeStorageDb: sqlocal DB closed"); + } catch (err) { + log.warn("closeStorageDb: close failed", { + name: err instanceof Error ? err.name : undefined, + message: err instanceof Error ? err.message : String(err), + }); + } +} + export const coordinator = new MultiTabCoordinator(); diff --git a/apps/web/src/core/storage/db.ts b/apps/web/src/core/storage/db.ts index 40d53346b..dc2700fff 100644 --- a/apps/web/src/core/storage/db.ts +++ b/apps/web/src/core/storage/db.ts @@ -25,6 +25,8 @@ export interface OpenedSqlocalDb { storageType: string; /** True when the database is saved to OPFS. */ persistent: boolean; + /** Disconnects from the database and stops its worker, releasing the OPFS handle. */ + close: () => Promise; } /** @@ -47,7 +49,12 @@ export async function openSqlocalDb( await applyMigrations(sql); const { storageType = "memory" } = await client.getDatabaseInfo(); - return { db, storageType, persistent: storageType === "opfs" }; + return { + db, + storageType, + persistent: storageType === "opfs", + close: () => client.destroy(), + }; } type RawSql = ( diff --git a/apps/web/src/core/storage/deviceStorage.test.ts b/apps/web/src/core/storage/deviceStorage.test.ts index c1013aaae..8d73315ac 100644 --- a/apps/web/src/core/storage/deviceStorage.test.ts +++ b/apps/web/src/core/storage/deviceStorage.test.ts @@ -1,8 +1,9 @@ import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; import { Protobuf } from "@core/protobuf.ts"; -import { beforeEach, describe, expect, it } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import type { SqlocalDb } from "./db.ts"; -import { SqlocalDeviceStorage } from "./deviceStorage.ts"; +import type { DeviceStorageJs } from "@meshtastic/sdk-kmp"; +import { boundedDeviceStorage, SqlocalDeviceStorage } from "./deviceStorage.ts"; import { createMemoryDb } from "./memoryDb.ts"; import { SqlocalNodesRepository } from "./nodes.ts"; @@ -126,3 +127,52 @@ describe("SqlocalDeviceStorage", () => { expect(await storage.loadNodes()).toEqual([]); }); }); + +describe("boundedDeviceStorage", () => { + const hanging = (): DeviceStorageJs => ({ + loadNodes: () => new Promise(() => {}), + saveNode: () => new Promise(() => {}), + removeNode: () => new Promise(() => {}), + loadConfig: () => new Promise(() => {}), + saveConfig: () => new Promise(() => {}), + loadChannels: () => new Promise(() => {}), + saveChannels: () => new Promise(() => {}), + recordOwnNode: () => new Promise(() => {}), + clear: () => new Promise(() => {}), + close: () => {}, + saveSessionPasskey: () => new Promise(() => {}), + loadSessionPasskey: () => new Promise(() => {}), + saveHeartbeat: () => new Promise(() => {}), + loadHeartbeats: () => new Promise(() => {}), + }); + + it("answers every read with its empty value when the database never responds", async () => { + vi.useFakeTimers(); + try { + const storage = boundedDeviceStorage(hanging(), 50); + const reads = Promise.all([ + storage.loadConfig(), + storage.loadNodes(), + storage.loadChannels(), + storage.loadSessionPasskey(), + storage.loadHeartbeats(), + ]); + await vi.advanceTimersByTimeAsync(60); + expect(await reads).toEqual([null, [], [], null, []]); + } finally { + vi.useRealTimers(); + } + }); + + it("lets a write that never responds complete, so connect is not held up", async () => { + vi.useFakeTimers(); + try { + const storage = boundedDeviceStorage(hanging(), 50); + const write = storage.saveChannels([]); + await vi.advanceTimersByTimeAsync(60); + await expect(write).resolves.toBeUndefined(); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/apps/web/src/core/storage/deviceStorage.ts b/apps/web/src/core/storage/deviceStorage.ts index f1ffb8cd5..10fb300d0 100644 --- a/apps/web/src/core/storage/deviceStorage.ts +++ b/apps/web/src/core/storage/deviceStorage.ts @@ -1,4 +1,5 @@ import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; +import { createLogger } from "@core/log.ts"; import { Protobuf } from "@core/protobuf.ts"; import type { ConfigBundleJs, @@ -25,6 +26,8 @@ import { base64Decode, base64Encode } from "./types.ts"; * the same radio shares them: the scope starts as the node this connection * reached last time and moves to the node the handshake names. */ +const log = createLogger("deviceStorage"); + export class SqlocalDeviceStorage implements DeviceStorageJs { private scope: number; @@ -257,11 +260,91 @@ function decodeList(json: string): Uint8Array[] { } /** A `StorageJs` for the facade's factories, opening the DB on activation. */ +const STORAGE_CALL_TIMEOUT_MS = 5000; + +function bounded( + call: () => Promise, + fallback: T, + what: string, + timeoutMs: number, +): Promise { + return new Promise((resolve) => { + const timer = setTimeout(() => { + log.warn(`${what} did not answer within ${timeoutMs}ms, continuing`); + resolve(fallback); + }, timeoutMs); + call().then( + (value) => { + clearTimeout(timer); + resolve(value); + }, + (err) => { + clearTimeout(timer); + log.warn(`${what} failed, continuing`, { + message: err instanceof Error ? err.message : String(err), + }); + resolve(fallback); + }, + ); + }); +} + +/** + * The same storage, with every call answered within `timeoutMs`: a read + * falls back to its empty value and a write is treated as done. A database + * whose OPFS handle another tab still holds can then never stall the SDK's + * connect. + */ +export function boundedDeviceStorage( + inner: DeviceStorageJs, + timeoutMs = STORAGE_CALL_TIMEOUT_MS, +): DeviceStorageJs { + const run = (what: string, call: () => Promise, fallback: T) => + bounded(call, fallback, what, timeoutMs); + return { + loadNodes: () => run("loadNodes", () => inner.loadNodes(), []), + saveNode: (node) => run("saveNode", () => inner.saveNode(node), undefined), + removeNode: (nodeNum) => + run("removeNode", () => inner.removeNode(nodeNum), undefined), + loadConfig: () => run("loadConfig", () => inner.loadConfig(), null), + saveConfig: (bundle) => + run("saveConfig", () => inner.saveConfig(bundle), undefined), + loadChannels: () => run("loadChannels", () => inner.loadChannels(), []), + saveChannels: (channels) => + run("saveChannels", () => inner.saveChannels(channels), undefined), + recordOwnNode: (nodeNum, firmwareVersion) => + run( + "recordOwnNode", + () => inner.recordOwnNode(nodeNum, firmwareVersion), + undefined, + ), + clear: () => run("clear", () => inner.clear(), undefined), + close: () => inner.close(), + saveSessionPasskey: (passkey) => + run( + "saveSessionPasskey", + () => inner.saveSessionPasskey(passkey), + undefined, + ), + loadSessionPasskey: () => + run("loadSessionPasskey", () => inner.loadSessionPasskey(), null), + saveHeartbeat: (nodeNum, epochMillis) => + run( + "saveHeartbeat", + () => inner.saveHeartbeat(nodeNum, epochMillis), + undefined, + ), + loadHeartbeats: () => + run("loadHeartbeats", () => inner.loadHeartbeats(), []), + }; +} + export function sqlocalStorage( openDb: () => Promise, scope: number, ): StorageJs { return { - activate: async () => new SqlocalDeviceStorage(await openDb(), scope), + activate: async () => + boundedDeviceStorage(new SqlocalDeviceStorage(await openDb(), scope)), }; } diff --git a/apps/web/src/pages/Connections/useConnections.kmp.test.ts b/apps/web/src/pages/Connections/useConnections.kmp.test.ts index ddfbcb79e..1c0ad072c 100644 --- a/apps/web/src/pages/Connections/useConnections.kmp.test.ts +++ b/apps/web/src/pages/Connections/useConnections.kmp.test.ts @@ -9,6 +9,8 @@ import { act, renderHook } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { disconnectAllConnections, useConnections } from "./useConnections.ts"; +const storage = vi.hoisted(() => ({ close: vi.fn(async () => {}) })); + const kmp = vi.hoisted( (): { client?: FakeKmpClient; @@ -22,6 +24,7 @@ vi.mock("@core/sdkStorage.ts", () => ({ getStorageDb: async () => { throw new Error("no storage in tests"); }, + closeStorageDb: storage.close, coordinator: undefined, })); @@ -116,10 +119,12 @@ describe("useConnections over the Kotlin SDK (HTTP)", () => { const client = kmp.client; if (!client) throw new Error("no client created"); + storage.close.mockClear(); await act(() => disconnectAllConnections()); expect(client.disconnects).toHaveLength(1); expect(saved(conn.id)?.status).toBe("disconnected"); expect(meshRegistry.get(conn.id)?.kmp).toBe(client); + expect(storage.close).toHaveBeenCalledTimes(1); }); it("shows the SDK's reconnect attempts and reports when they run out", async () => { diff --git a/apps/web/src/pages/Connections/useConnections.ts b/apps/web/src/pages/Connections/useConnections.ts index d0d1a29c1..9abf44567 100644 --- a/apps/web/src/pages/Connections/useConnections.ts +++ b/apps/web/src/pages/Connections/useConnections.ts @@ -37,6 +37,7 @@ import { import { meshRegistry } from "@core/kmp/registry.ts"; import { MeshSession } from "@core/kmp/session.ts"; import { createLogger } from "@core/log.ts"; +import { closeStorageDb } from "@core/sdkStorage.ts"; import { useAppStore, useDeviceStore } from "@core/stores"; import { subscribeAll } from "@core/subscriptions.ts"; import { MIN_FIRMWARE_VERSION } from "@core/utils/firmware.ts"; @@ -178,6 +179,7 @@ export async function disconnectAllConnections(): Promise { for (const id of [...sessionTeardowns.keys()]) { await disconnectConnection(id); } + await closeStorageDb(); } export function useConnections() { From ec70d23602f2fe0f5885b414f9eabfbac1d67228 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 14:01:41 -0500 Subject: [PATCH 32/49] fix(web): stop an in-flight connect on handover and harden the tab lock Review findings I1, M1 and M2 on the single-tab lock. - I1: a connect still choosing a port or opening storage when the app was handed over went on to open the serial port and the database in the old tab. disconnectAllConnections bumps a handover counter; connect checks it after every await and abandons, and getStorageDb refuses to reopen until this tab owns the app again (resumeStorageDb on grant). - M1: a late grant of the normal request arriving after the steal timer made the claimant steal from itself and then tear itself down. Each request carries a grant token; only the current grant's loss counts, and a grant that lands once stealing began is let go at once. - M2: the gate rendered nothing while the lock was still being asked for, so an early click hit a blank page. The overlay now renders with Use here disabled during that time and takes focus once it is enabled. - M3 (retry a busy serial open after handover) is already covered: the transport retries a busy open three times over 1.5 s. --- apps/web/src/components/TabLockGate.test.tsx | 20 ++++++++ apps/web/src/components/TabLockGate.tsx | 7 ++- apps/web/src/components/TabLockOverlay.tsx | 14 ++++-- apps/web/src/core/sdkStorage.test.ts | 18 ++++++- apps/web/src/core/sdkStorage.ts | 12 +++++ apps/web/src/core/tabLock.test.ts | 47 +++++++++++++++++++ apps/web/src/core/tabLock.ts | 35 +++++++++----- apps/web/src/index.tsx | 4 ++ .../Connections/useConnections.kmp.test.ts | 24 ++++++++++ .../src/pages/Connections/useConnections.ts | 22 ++++++++- 10 files changed, 183 insertions(+), 20 deletions(-) diff --git a/apps/web/src/components/TabLockGate.test.tsx b/apps/web/src/components/TabLockGate.test.tsx index dcff4226f..ba08e2ed7 100644 --- a/apps/web/src/components/TabLockGate.test.tsx +++ b/apps/web/src/components/TabLockGate.test.tsx @@ -125,4 +125,24 @@ describe("TabLockGate", () => { expect(document.documentElement.getAttribute("data-theme")).toBe("dark"); localStorage.removeItem("theme"); }); + + it("shows the overlay, with Use here disabled, while the lock is still being asked for", () => { + const pending = { + start: () => {}, + takeOver: () => {}, + getStatus: () => "pending" as const, + subscribe: () => () => {}, + }; + render( + +

app

+
, + ); + + expect(screen.queryByText("app")).toBeNull(); + const dialog = screen.getByRole("dialog"); + expect(within(dialog).getByRole("button").hasAttribute("disabled")).toBe( + true, + ); + }); }); diff --git a/apps/web/src/components/TabLockGate.tsx b/apps/web/src/components/TabLockGate.tsx index dbf057e50..b0b14bc5c 100644 --- a/apps/web/src/components/TabLockGate.tsx +++ b/apps/web/src/components/TabLockGate.tsx @@ -15,8 +15,11 @@ export function TabLockGate({ lock, children }: TabLockGateProps) { useLayoutEffect(applyStoredTheme, []); if (status === "owner") return children; - if (status === "pending") return null; return ( - + ); } diff --git a/apps/web/src/components/TabLockOverlay.tsx b/apps/web/src/components/TabLockOverlay.tsx index 90a7954bd..9496ca512 100644 --- a/apps/web/src/components/TabLockOverlay.tsx +++ b/apps/web/src/components/TabLockOverlay.tsx @@ -3,16 +3,22 @@ import { useTranslation } from "react-i18next"; export interface TabLockOverlayProps { claiming: boolean; + /** The lock has not been answered yet: nothing to act on. */ + pending?: boolean; onUseHere: () => void; } -export function TabLockOverlay({ claiming, onUseHere }: TabLockOverlayProps) { +export function TabLockOverlay({ + claiming, + pending = false, + onUseHere, +}: TabLockOverlayProps) { const { t } = useTranslation("ui"); const buttonRef = useRef(null); useEffect(() => { - buttonRef.current?.focus(); - }, []); + if (!pending) buttonRef.current?.focus(); + }, [pending]); return (
diff --git a/apps/web/src/core/sdkStorage.test.ts b/apps/web/src/core/sdkStorage.test.ts index aecd13f08..6300ffb1d 100644 --- a/apps/web/src/core/sdkStorage.test.ts +++ b/apps/web/src/core/sdkStorage.test.ts @@ -23,10 +23,12 @@ describe("sdkStorage singletons", () => { }); it("closes the database on request and reopens a fresh one afterwards", async () => { - const { getStorageDb, closeStorageDb } = await import("./sdkStorage.ts"); + const { getStorageDb, closeStorageDb, resumeStorageDb } = + await import("./sdkStorage.ts"); const first = await getStorageDb(); await closeStorageDb(); + resumeStorageDb(); const second = await getStorageDb(); expect(sqlocal.close).toHaveBeenCalledTimes(1); @@ -46,4 +48,18 @@ describe("sdkStorage singletons", () => { await getStorageDb(); await expect(closeStorageDb()).resolves.toBeUndefined(); }); + + it("refuses to reopen after a close until the tab owns the app again", async () => { + const { getStorageDb, closeStorageDb, resumeStorageDb } = + await import("./sdkStorage.ts"); + await getStorageDb(); + await closeStorageDb(); + + await expect(getStorageDb()).rejects.toThrow(/another tab/); + expect(sqlocal.open).toHaveBeenCalledTimes(1); + + resumeStorageDb(); + await getStorageDb(); + expect(sqlocal.open).toHaveBeenCalledTimes(2); + }); }); diff --git a/apps/web/src/core/sdkStorage.ts b/apps/web/src/core/sdkStorage.ts index eb4ca0b4c..9f76d211f 100644 --- a/apps/web/src/core/sdkStorage.ts +++ b/apps/web/src/core/sdkStorage.ts @@ -17,8 +17,14 @@ const log = createLogger("sdkStorage"); * stay fast and headless-safe. */ let dbPromise: Promise | undefined; +let relinquished = false; export function getStorageDb(): Promise { + if (relinquished) { + return Promise.reject( + new Error("storage was handed to another tab; not reopening"), + ); + } if (!dbPromise) { log.debug("getStorageDb: creating sqlocal DB", { path: "meshtastic.db" }); const t0 = Date.now(); @@ -49,6 +55,7 @@ export function getStorageDb(): Promise { * logged, not thrown: the caller is giving the app away and must finish. */ export async function closeStorageDb(): Promise { + relinquished = true; const pending = dbPromise; if (!pending) return; dbPromise = undefined; @@ -64,4 +71,9 @@ export async function closeStorageDb(): Promise { } } +/** This tab owns the app again: `getStorageDb()` may open the database. */ +export function resumeStorageDb(): void { + relinquished = false; +} + export const coordinator = new MultiTabCoordinator(); diff --git a/apps/web/src/core/tabLock.test.ts b/apps/web/src/core/tabLock.test.ts index 3f98a89a8..fde50d296 100644 --- a/apps/web/src/core/tabLock.test.ts +++ b/apps/web/src/core/tabLock.test.ts @@ -4,6 +4,7 @@ import { } from "@app/tests/fakeTabEnvironment.ts"; import { APP_LOCK_NAME, + type AppLockManager, createTabLock, STEAL_AFTER_MS, TAB_CHANNEL_NAME, @@ -157,6 +158,52 @@ describe("tabLock", () => { expect(a.lock.getStatus()).toBe("other"); }); + it("does not tear itself down when a late grant and the steal both arrive", async () => { + const hub = createFakeChannelHub(); + const requests: Array<{ + options: LockOptions; + callback: (lock: Lock | null) => Promise; + resolve: (value: unknown) => void; + reject: (reason: unknown) => void; + }> = []; + const locks: AppLockManager = { + request: (_name, options, callback) => + new Promise((resolve, reject) => { + requests.push({ options, callback, resolve, reject }); + }), + }; + const onRelinquish = vi.fn(async () => {}); + const lock = createTabLock({ + locks, + openChannel: (name) => hub.open(name), + onRelinquish, + }); + lock.start(); + const [initial] = requests; + if (!initial) throw new Error("no initial request"); + void initial.callback(null); + await flush(); + expect(lock.getStatus()).toBe("other"); + + lock.takeOver(); + const normal = requests[1]; + if (!normal) throw new Error("no takeover request"); + vi.advanceTimersByTime(STEAL_AFTER_MS); + const steal = requests[2]; + if (!steal) throw new Error("no steal request"); + const late = normal.callback({ name: APP_LOCK_NAME, mode: "exclusive" }); + void steal.callback({ name: APP_LOCK_NAME, mode: "exclusive" }); + await flush(); + expect(lock.getStatus()).toBe("owner"); + + normal.reject(new DOMException("stolen", "AbortError")); + await late; + await flush(); + + expect(lock.getStatus()).toBe("owner"); + expect(onRelinquish).not.toHaveBeenCalled(); + }); + it("ignores takeover requests while not the owner", async () => { const { tab } = setup(); const a = tab(); diff --git a/apps/web/src/core/tabLock.ts b/apps/web/src/core/tabLock.ts index 266ad043b..1df3078ec 100644 --- a/apps/web/src/core/tabLock.ts +++ b/apps/web/src/core/tabLock.ts @@ -65,6 +65,7 @@ export function createTabLock(env: TabLockEnvironment): TabLock { let release: (() => void) | undefined; let relinquishing = false; let channel: TabChannel | undefined; + let current: symbol | undefined; const setStatus = (next: TabLockStatus) => { if (status === next) return; @@ -85,7 +86,7 @@ export function createTabLock(env: TabLockEnvironment): TabLock { } }; - const onGranted = async (lock: Lock | null): Promise => { + const onGranted = async (lock: Lock | null, grant: symbol): Promise => { if (!lock) { log.info("another tab owns the app"); setStatus("other"); @@ -95,15 +96,16 @@ export function createTabLock(env: TabLockEnvironment): TabLock { const held = new Promise((resolve) => { release = resolve; }); + current = grant; setStatus("owner"); return held; }; - const watch = (request: Promise) => { + const watch = (request: Promise, grant: symbol) => { request.then( () => {}, (error) => { - if (status !== "owner") return; + if (status !== "owner" || current !== grant) return; log.warn("lock lost", { message: error instanceof Error ? error.message : String(error), }); @@ -114,6 +116,16 @@ export function createTabLock(env: TabLockEnvironment): TabLock { ); }; + const request = (options: LockOptions, onLock = onGranted) => { + const grant = Symbol("grant"); + watch( + env.locks?.request(APP_LOCK_NAME, options, (lock) => + onLock(lock, grant), + ) ?? Promise.resolve(), + grant, + ); + }; + const relinquish = async () => { if (relinquishing) return; const held = release; @@ -140,7 +152,7 @@ export function createTabLock(env: TabLockEnvironment): TabLock { if (isTakeover(event.data) && status === "owner") void relinquish(); }; channel = opened; - watch(locks.request(APP_LOCK_NAME, { ifAvailable: true }, onGranted)); + request({ ifAvailable: true }); }, takeOver() { const { locks } = env; @@ -148,17 +160,18 @@ export function createTabLock(env: TabLockEnvironment): TabLock { setStatus("claiming"); channel?.postMessage({ type: "takeover" }); const waiting = new AbortController(); + let stealing = false; const stealTimer = setTimeout(() => { log.warn("owner did not release, stealing the lock"); + stealing = true; waiting.abort(); - watch(locks.request(APP_LOCK_NAME, { steal: true }, onGranted)); + request({ steal: true }); }, STEAL_AFTER_MS); - watch( - locks.request(APP_LOCK_NAME, { signal: waiting.signal }, (lock) => { - clearTimeout(stealTimer); - return onGranted(lock); - }), - ); + request({ signal: waiting.signal }, async (lock, grant) => { + if (stealing) return; + clearTimeout(stealTimer); + return onGranted(lock, grant); + }); }, getStatus: () => status, subscribe(listener) { diff --git a/apps/web/src/index.tsx b/apps/web/src/index.tsx index 72baee51f..cc35605ec 100644 --- a/apps/web/src/index.tsx +++ b/apps/web/src/index.tsx @@ -11,6 +11,7 @@ import { router } from "@app/routes.tsx"; import { TabLockGate } from "@components/TabLockGate.tsx"; import { meshRegistry } from "@core/kmp/registry.ts"; import { useAppStore } from "@core/stores"; +import { resumeStorageDb } from "@core/sdkStorage.ts"; import { createBrowserTabLock } from "@core/tabLock.ts"; import { disconnectAllConnections } from "@app/pages/Connections/useConnections.ts"; import { MeshRegistryProvider } from "@core/kmp/hooks"; @@ -25,6 +26,9 @@ declare module "@tanstack/react-router" { const container = document.getElementById("root") as HTMLElement; const root = createRoot(container); const tabLock = createBrowserTabLock(disconnectAllConnections); +tabLock.subscribe(() => { + if (tabLock.getStatus() === "owner") resumeStorageDb(); +}); tabLock.start(); function IndexPage() { diff --git a/apps/web/src/pages/Connections/useConnections.kmp.test.ts b/apps/web/src/pages/Connections/useConnections.kmp.test.ts index 1c0ad072c..fc010b7a6 100644 --- a/apps/web/src/pages/Connections/useConnections.kmp.test.ts +++ b/apps/web/src/pages/Connections/useConnections.kmp.test.ts @@ -17,6 +17,7 @@ const kmp = vi.hoisted( clients: FakeKmpClient[]; storages: Array; connectError?: Error; + holdFactory?: Promise; } => ({ clients: [], storages: [] }), ); @@ -37,6 +38,7 @@ vi.mock("@core/kmp/client.ts", async () => { storage?: StorageJs, ) => { kmp.storages.push(storage); + await kmp.holdFactory; const client = new FakeKmpClient(); if (kmp.connectError) { const error = kmp.connectError; @@ -127,6 +129,28 @@ describe("useConnections over the Kotlin SDK (HTTP)", () => { expect(storage.close).toHaveBeenCalledTimes(1); }); + it("abandons a connect that was in flight when the app is handed to another tab", async () => { + let releaseFactory: () => void = () => {}; + kmp.holdFactory = new Promise( + (resolve) => (releaseFactory = resolve), + ); + const { result } = renderHook(() => useConnections()); + const conn = addRadio(result); + const connecting = result.current.connect(conn.id); + await act(async () => {}); + + await act(() => disconnectAllConnections()); + releaseFactory(); + expect(await act(() => connecting)).toBe(false); + + const client = kmp.client; + if (!client) throw new Error("no client created"); + expect(client.connects).toHaveLength(0); + expect(meshRegistry.get(conn.id)).toBeUndefined(); + expect(saved(conn.id)?.status).toBe("disconnected"); + kmp.holdFactory = undefined; + }); + it("shows the SDK's reconnect attempts and reports when they run out", async () => { const { result } = renderHook(() => useConnections()); const conn = result.current.addConnection({ diff --git a/apps/web/src/pages/Connections/useConnections.ts b/apps/web/src/pages/Connections/useConnections.ts index 9abf44567..f6eedc382 100644 --- a/apps/web/src/pages/Connections/useConnections.ts +++ b/apps/web/src/pages/Connections/useConnections.ts @@ -138,6 +138,14 @@ async function clientFactory( } } +function abandonConnect(id: ConnectionId): false { + log.info("connect: abandoned, the app was handed to another tab", { id }); + useDeviceStore + .getState() + .updateSavedConnection(id, { status: "disconnected", error: undefined }); + return false; +} + const savedConnection = (id: ConnectionId): Connection | undefined => useDeviceStore.getState().savedConnections.find((c) => c.id === id); @@ -175,7 +183,13 @@ async function disconnectConnection(id: ConnectionId): Promise { } /** Disconnects every live session, as the drawer's Disconnect does. */ +// Bumped when the app is handed to another tab, so a connect still in +// flight here stops before it opens the port or registers a session. +let handovers = 0; +const handedOver = (seen: number): boolean => seen !== handovers; + export async function disconnectAllConnections(): Promise { + handovers += 1; for (const id of [...sessionTeardowns.keys()]) { await disconnectConnection(id); } @@ -252,12 +266,14 @@ export function useConnections() { * this connection reached last time. */ const connectThroughKmp = useCallback( - async (id: ConnectionId, makeClient: ClientFactory) => { + async (id: ConnectionId, makeClient: ClientFactory, seen: number) => { const conn = savedConnection(id); const { options, persistent, sdkStorage } = await openRepositories( conn?.nodeNum, ); + if (handedOver(seen)) return abandonConnect(id); const client = await makeClient(sdkStorage); + if (handedOver(seen)) return abandonConnect(id); let deviceId = conn?.meshDeviceId; if (deviceId && !useDeviceStore.getState().getDevice(deviceId)) { deviceId = undefined; @@ -470,9 +486,11 @@ export function useConnections() { }); updateStatus(id, "connecting"); const allowPrompt = opts?.allowPrompt ?? false; + const seen = handovers; try { // The picker runs first, while the click's activation is still live. const makeClient = await clientFactory(conn, allowPrompt); + if (handedOver(seen)) return abandonConnect(id); // The app follows one radio at a time: a session still live on // another connection would keep its port and poller to itself. for (const other of [...sessionTeardowns.keys()]) { @@ -490,7 +508,7 @@ export function useConnections() { error: undefined, }); } - return await connectThroughKmp(id, makeClient); + return await connectThroughKmp(id, makeClient, seen); } catch (error) { log.error("connect: no device to connect to", { id, From 9a00a59e28899c3eb44951e24734124822d22740 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 14:01:42 -0500 Subject: [PATCH 33/49] fix(kmp): drop the bytes a serial device queued before the port opened Every fresh serial connect decoded a few garbage frames during Stage 1: the device's queued output (log text, the tail of an earlier frame) reaches the framer first and a chance 0x94 0xC3 inside it is taken as a header. The SDK's jSerialComm transport purges its input buffers before sending the wake bytes; Web Serial has no purge, so the transport now reads and discards until the line has been quiet for 50 ms (300 ms at most) before reporting Connected and starting the framer. The web logs a frame it cannot decode at debug, as the old transport did; the engine still reports its own decode failures. --- apps/web/src/core/kmp/session.ts | 2 +- .../meshtastic/sdk/js/WebSerialTransport.kt | 27 +++++++++++++++++++ .../sdk/js/WebSerialTransportTest.kt | 19 ++++++++++++- 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/apps/web/src/core/kmp/session.ts b/apps/web/src/core/kmp/session.ts index d43697cba..ff378a76a 100644 --- a/apps/web/src/core/kmp/session.ts +++ b/apps/web/src/core/kmp/session.ts @@ -410,7 +410,7 @@ export class MeshSession { try { frame = decodeFromRadio(bytes); } catch (e) { - log.warn("undecodable FromRadio frame", e); + log.debug("undecodable FromRadio frame", e); return; } this.events.onFromRadio.dispatch(frame); diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebSerialTransport.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebSerialTransport.kt index 2b79441de..6e1a4bf3d 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebSerialTransport.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/WebSerialTransport.kt @@ -13,6 +13,7 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull import org.khronos.webgl.Uint8Array import org.meshtastic.sdk.Frame import org.meshtastic.sdk.RadioTransport @@ -72,6 +73,7 @@ internal class WebSerialTransport( ) port = opened open(opened) + discardStale(opened) if (!listening) { serial.addEventListener("disconnect", onOsDisconnect) serial.addEventListener("connect", onOsConnect) @@ -185,6 +187,29 @@ internal class WebSerialTransport( writer = p.writable.getWriter() } + /** + * Drops whatever the device had queued before the port opened (its log + * text, the tail of an earlier frame), as the native transports purge + * their input buffers, so the framer starts at a quiet boundary. Reads + * until the line is silent for [DRAIN_QUIET_MS], or [DRAIN_MAX_MS] at most. + */ + private suspend fun discardStale(p: dynamic) { + val r = p.readable.getReader() + try { + withTimeoutOrNull(DRAIN_MAX_MS) { + while (true) { + val result = withTimeoutOrNull(DRAIN_QUIET_MS) { (r.read() as Promise).await() } ?: break + if (result.done == true) break + } + } + } finally { + try { + r.releaseLock() + } catch (_: Throwable) { + } + } + } + private suspend fun readLoop(p: dynamic) { val assembler = FrameAssembler { inbound.trySend(it) } val r = p.readable.getReader() @@ -236,6 +261,8 @@ internal class WebSerialTransport( const val DISCONNECTED = "serial-disconnected" const val READ_BUFFER_SIZE = 64 * 1024 const val POST_CLOSE_DELAY_MS = 200L + const val DRAIN_QUIET_MS = 50L + const val DRAIN_MAX_MS = 300L val OPEN_RETRY_DELAYS_MS = longArrayOf(250, 500, 750) fun serialApi(): dynamic { diff --git a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebSerialTransportTest.kt b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebSerialTransportTest.kt index 94d14950d..0d2f90c8b 100644 --- a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebSerialTransportTest.kt +++ b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/WebSerialTransportTest.kt @@ -54,10 +54,11 @@ class WebSerialTransportTest { val port = js( """({ readable: null, writable: null, written: [], opens: 0, closes: 0, + stale: null, open: function () { var self = this; self.opens++; - self.readable = new ReadableStream({ start: function (c) { self.reader = c; } }); + self.readable = new ReadableStream({ start: function (c) { self.reader = c; if (self.stale) c.enqueue(self.stale); } }); self.writable = new WritableStream({ start: function (c) { self.writer = c; }, write: function (chunk) { self.written.push(chunk); } }); return Promise.resolve(); }, @@ -245,6 +246,22 @@ class WebSerialTransportTest { transport.disconnect() } + @Test + fun bytes_left_in_the_port_before_connect_never_become_frames() = GlobalScope.promise { + val radio = fakePort(0x303a, 0x1001) + radio.stale = (byteArrayOf(0x41, 0x94.toByte(), 0xC3.toByte(), 0x00, 0x03, 0x7F) + "INFO | boot\n".encodeToByteArray()).toUint8Array() + installSerial(arrayOf(radio)) + val transport = WebSerialTransport(null, 0x303a, 0x1001) + transport.connect() + + val payload = byteArrayOf(0x08, 0x01) + radio.push(framed(payload).toByteArray().toUint8Array()) + val frame = withTimeout(1_000) { transport.frames().first() } + + assertEquals(Frame(framed(payload)), frame) + transport.disconnect() + } + @Test fun a_port_left_open_is_closed_before_reopening() = GlobalScope.promise { val radio = fakePort(0x303a, 0x1001) From b8a79aa9631445f655718958ff5de7b181ecf22c Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 13:55:56 -0500 Subject: [PATCH 34/49] chore: remove the hand-written TypeScript SDK and transport packages Delete packages/sdk, sdk-react, sdk-storage-sqlocal, transport-* and tests/utils. The web app runs on the Kotlin SDK facade (packages/sdk-kmp). --- packages/sdk-react/README.md | 42 - packages/sdk-react/mod.ts | 59 -- packages/sdk-react/package.json | 72 -- .../sdk-react/src/adapters/useActiveClient.ts | 8 - packages/sdk-react/src/adapters/useClient.ts | 31 - .../sdk-react/src/adapters/useClientById.ts | 11 - .../sdk-react/src/adapters/useMeshRegistry.ts | 17 - packages/sdk-react/src/adapters/useSignal.ts | 16 - .../sdk-react/src/adapters/useSignalValue.ts | 19 - packages/sdk-react/src/hooks/useChannels.ts | 24 - packages/sdk-react/src/hooks/useChat.ts | 35 - packages/sdk-react/src/hooks/useConfig.ts | 24 - .../sdk-react/src/hooks/useConfigEditor.ts | 14 - packages/sdk-react/src/hooks/useConnection.ts | 30 - .../src/hooks/useConnectionProgress.ts | 23 - packages/sdk-react/src/hooks/useDirectChat.ts | 40 - packages/sdk-react/src/hooks/useDraft.ts | 36 - .../sdk-react/src/hooks/useFavoriteNode.ts | 18 - .../sdk-react/src/hooks/useFileTransfer.ts | 8 - packages/sdk-react/src/hooks/useIgnoreNode.ts | 18 - packages/sdk-react/src/hooks/useMeshDevice.ts | 35 - .../sdk-react/src/hooks/useModuleMessages.ts | 134 ---- packages/sdk-react/src/hooks/useNode.ts | 10 - packages/sdk-react/src/hooks/useNodeError.ts | 28 - packages/sdk-react/src/hooks/useNodes.ts | 8 - packages/sdk-react/src/hooks/usePosition.ts | 10 - packages/sdk-react/src/hooks/useTelemetry.ts | 24 - packages/sdk-react/src/hooks/useTraceroute.ts | 10 - packages/sdk-react/src/hooks/useUnread.ts | 41 - .../sdk-react/src/provider/MeshContext.ts | 4 - .../sdk-react/src/provider/MeshProvider.tsx | 12 - .../src/provider/MeshRegistryContext.ts | 6 - .../src/provider/MeshRegistryProvider.tsx | 24 - .../sdk-react/tests/hooks.registry.test.tsx | 134 ---- packages/sdk-react/tests/hooks.test.tsx | 44 -- .../tests/useModuleMessages.test.tsx | 88 --- packages/sdk-react/tsconfig.json | 4 - packages/sdk-react/vitest.config.ts | 14 - packages/sdk-storage-sqlocal/README.md | 62 -- packages/sdk-storage-sqlocal/mod.ts | 16 - packages/sdk-storage-sqlocal/package.json | 62 -- .../src/chat/SqlocalDraftRepository.test.ts | 92 --- .../src/chat/SqlocalDraftRepository.ts | 88 --- .../src/chat/SqlocalMessageRepository.test.ts | 215 ----- .../src/chat/SqlocalMessageRepository.ts | 273 ------- .../sdk-storage-sqlocal/src/chat/index.ts | 4 - .../MultiTabCoordinator.broadcast.test.ts | 33 - .../coordination/MultiTabCoordinator.test.ts | 21 - .../src/coordination/MultiTabCoordinator.ts | 84 -- .../src/coordination/index.ts | 2 - packages/sdk-storage-sqlocal/src/db.ts | 84 -- .../src/nodes/SqlocalNodesRepository.test.ts | 96 --- .../src/nodes/SqlocalNodesRepository.ts | 155 ---- .../sdk-storage-sqlocal/src/nodes/index.ts | 2 - .../sdk-storage-sqlocal/src/schema/chat.ts | 52 -- .../sdk-storage-sqlocal/src/schema/drafts.ts | 22 - .../sdk-storage-sqlocal/src/schema/index.ts | 5 - .../src/schema/migrations.test.ts | 101 --- .../src/schema/migrations.ts | 90 --- .../sdk-storage-sqlocal/src/schema/nodes.ts | 38 - .../src/schema/telemetry.ts | 19 - .../SqlocalTelemetryRepository.test.ts | 120 --- .../telemetry/SqlocalTelemetryRepository.ts | 218 ------ .../src/telemetry/index.ts | 4 - .../src/testing/createMemoryDb.ts | 29 - .../sdk-storage-sqlocal/src/testing/index.ts | 1 - .../tests/sqlocal-opfs.browser.test.ts | 52 -- packages/sdk-storage-sqlocal/tsconfig.json | 4 - .../vitest.browser.config.ts | 27 - packages/sdk-storage-sqlocal/vitest.config.ts | 12 - packages/sdk/README.md | 40 - packages/sdk/mod.ts | 182 ----- packages/sdk/package.json | 88 --- packages/sdk/scripts/rename-dts.mjs | 213 ----- .../core/client/MeshClient.handshake.test.ts | 228 ------ .../core/client/MeshClient.progress.test.ts | 122 --- .../client/MeshClient.storageScope.test.ts | 311 -------- packages/sdk/src/core/client/MeshClient.ts | 635 --------------- packages/sdk/src/core/client/handshake.ts | 55 -- packages/sdk/src/core/client/index.ts | 2 - packages/sdk/src/core/constants/index.ts | 8 - packages/sdk/src/core/errors/MeshError.ts | 34 - .../sdk/src/core/event-bus/EventBus.test.ts | 34 - packages/sdk/src/core/event-bus/EventBus.ts | 158 ---- packages/sdk/src/core/event-bus/index.ts | 1 - packages/sdk/src/core/identifiers/PacketId.ts | 7 - packages/sdk/src/core/logging/logger.ts | 51 -- .../core/packet-codec/decodePacket.test.ts | 226 ------ .../sdk/src/core/packet-codec/decodePacket.ts | 737 ------------------ .../src/core/packet-codec/fromDevice.test.ts | 82 -- .../sdk/src/core/packet-codec/fromDevice.ts | 96 --- packages/sdk/src/core/packet-codec/index.ts | 4 - .../sdk/src/core/packet-codec/toDevice.ts | 20 - packages/sdk/src/core/protobuf/index.ts | 1 - packages/sdk/src/core/queue/Queue.ts | 156 ---- .../src/core/registry/MeshRegistry.test.ts | 58 -- .../sdk/src/core/registry/MeshRegistry.ts | 123 --- packages/sdk/src/core/registry/index.ts | 2 - .../sdk/src/core/signals/createStore.test.ts | 62 -- packages/sdk/src/core/signals/createStore.ts | 100 --- packages/sdk/src/core/signals/index.ts | 2 - .../src/core/testing/createFakeTransport.ts | 140 ---- packages/sdk/src/core/testing/index.ts | 10 - .../core/testing/interceptAdminMessages.ts | 115 --- packages/sdk/src/core/transport/Transport.ts | 40 - packages/sdk/src/core/transport/index.ts | 2 - packages/sdk/src/core/types.ts | 127 --- packages/sdk/src/core/xmodem/Xmodem.ts | 132 ---- .../features/channels/ChannelsClient.test.ts | 67 -- .../src/features/channels/ChannelsClient.ts | 78 -- .../channels/application/ChannelUseCases.ts | 46 -- .../src/features/channels/domain/Channel.ts | 7 - .../channels/domain/MeshBeaconOffer.test.ts | 118 --- .../channels/domain/MeshBeaconOffer.ts | 145 ---- packages/sdk/src/features/channels/index.ts | 12 - .../channels/infrastructure/ChannelMapper.ts | 8 - .../features/channels/state/channelsStore.ts | 4 - .../features/chat/ChatClient.drafts.test.ts | 51 -- .../chat/ChatClient.persistence.test.ts | 138 ---- .../src/features/chat/ChatClient.send.test.ts | 287 ------- packages/sdk/src/features/chat/ChatClient.ts | 495 ------------ .../features/chat/ChatClient.unread.test.ts | 104 --- .../chat/application/SendTextUseCase.test.ts | 50 -- .../chat/application/SendTextUseCase.ts | 91 --- .../chat/application/SendWaypointUseCase.ts | 38 - .../features/chat/domain/DraftRepository.ts | 18 - .../src/features/chat/domain/Message.test.ts | 32 - .../sdk/src/features/chat/domain/Message.ts | 45 -- .../features/chat/domain/MessageRepository.ts | 90 --- .../src/features/chat/domain/MessageState.ts | 16 - packages/sdk/src/features/chat/index.ts | 28 - .../chat/infrastructure/MessageMapper.ts | 27 - .../repositories/InMemoryDraftRepository.ts | 34 - .../InMemoryMessageRepository.test.ts | 88 --- .../repositories/InMemoryMessageRepository.ts | 132 ---- .../sdk/src/features/chat/state/chatStore.ts | 152 ---- .../sdk/src/features/chat/state/draftStore.ts | 53 -- .../src/features/config/ConfigClient.test.ts | 87 --- .../sdk/src/features/config/ConfigClient.ts | 181 ----- .../src/features/config/ConfigEditor.test.ts | 399 ---------- .../features/config/ModuleMessages.test.ts | 227 ------ .../config/application/ConfigUseCases.ts | 94 --- .../application/ModuleMessagesUseCases.ts | 91 --- .../features/config/domain/ConfigEditor.ts | 636 --------------- .../features/config/domain/ModuleConfig.ts | 13 - .../src/features/config/domain/RadioConfig.ts | 21 - packages/sdk/src/features/config/index.ts | 12 - .../config/infrastructure/ConfigMapper.ts | 22 - .../src/features/config/state/configStore.ts | 14 - .../DeviceClient.keyVerification.test.ts | 40 - .../sdk/src/features/device/DeviceClient.ts | 221 ------ .../device/application/ConfigureUseCase.ts | 10 - .../device/application/DisconnectUseCase.ts | 5 - .../device/application/GetMetadataUseCase.ts | 15 - .../device/application/HeartbeatService.ts | 9 - .../application/LockdownService.test.ts | 111 --- .../device/application/LockdownService.ts | 73 -- .../device/application/RebootService.ts | 29 - .../sdk/src/features/device/domain/Device.ts | 13 - .../features/device/domain/DeviceStatus.ts | 15 - .../device/domain/FirmwareVersion.test.ts | 23 - .../features/device/domain/FirmwareVersion.ts | 49 -- packages/sdk/src/features/device/index.ts | 7 - .../infrastructure/AdminMessageSender.ts | 93 --- .../infrastructure/AdminSession.test.ts | 155 ---- .../device/infrastructure/AdminSession.ts | 83 -- .../src/features/device/state/deviceStore.ts | 45 -- .../sdk/src/features/files/FilesClient.ts | 66 -- .../src/features/files/domain/FileTransfer.ts | 9 - packages/sdk/src/features/files/index.ts | 2 - .../src/features/files/state/filesStore.ts | 4 - .../features/nodes/NodesClient.errors.test.ts | 103 --- .../src/features/nodes/NodesClient.test.ts | 149 ---- .../sdk/src/features/nodes/NodesClient.ts | 288 ------- .../nodes/application/FavoriteNodeUseCase.ts | 33 - .../nodes/application/IgnoreNodeUseCase.ts | 33 - .../nodes/application/RemoveNodeUseCase.ts | 32 - .../nodes/application/SetOwnerUseCase.ts | 19 - .../sdk/src/features/nodes/domain/Node.ts | 34 - .../src/features/nodes/domain/NodeError.ts | 18 - .../features/nodes/domain/NodesRepository.ts | 23 - packages/sdk/src/features/nodes/index.ts | 12 - .../nodes/infrastructure/NodeMapper.test.ts | 23 - .../nodes/infrastructure/NodeMapper.ts | 24 - .../nodes/infrastructure/nodeValidation.ts | 74 -- .../repositories/InMemoryNodesRepository.ts | 33 - .../features/nodes/state/nodeErrorsStore.ts | 4 - .../src/features/nodes/state/nodesStore.ts | 4 - .../features/position/PositionClient.test.ts | 30 - .../src/features/position/PositionClient.ts | 52 -- .../position/application/PositionUseCases.ts | 79 -- .../src/features/position/domain/Position.ts | 7 - packages/sdk/src/features/position/index.ts | 3 - .../position/infrastructure/PositionMapper.ts | 15 - .../features/position/state/positionStore.ts | 4 - .../TelemetryClient.persistence.test.ts | 92 --- .../telemetry/TelemetryClient.test.ts | 52 -- .../src/features/telemetry/TelemetryClient.ts | 105 --- .../telemetry/domain/TelemetryReading.ts | 10 - .../telemetry/domain/TelemetryRepository.ts | 35 - packages/sdk/src/features/telemetry/index.ts | 12 - .../infrastructure/TelemetryMapper.ts | 16 - .../InMemoryTelemetryRepository.test.ts | 65 -- .../InMemoryTelemetryRepository.ts | 69 -- .../telemetry/state/telemetryStore.ts | 104 --- .../features/traceroute/TraceRouteClient.ts | 35 - .../application/TraceRouteUseCase.ts | 23 - .../features/traceroute/domain/TraceRoute.ts | 6 - packages/sdk/src/features/traceroute/index.ts | 2 - .../traceroute/state/tracerouteStore.ts | 4 - packages/sdk/src/shim/legacyMeshDevice.ts | 409 ---------- packages/sdk/src/shim/legacyTypes.ts | 25 - packages/sdk/src/shim/legacyUtils.ts | 9 - packages/sdk/src/types-namespace.ts | 8 - .../tests/integration/fake-transport.test.ts | 71 -- packages/sdk/tsconfig.json | 4 - packages/sdk/vitest.config.ts | 9 - packages/transport-deno/README.md | 28 - packages/transport-deno/deno.json | 5 - packages/transport-deno/mod.ts | 1 - packages/transport-deno/package.json | 44 -- packages/transport-deno/scripts/build_npm.ts | 32 - packages/transport-deno/src/transport.ts | 39 - packages/transport-http/LICENSE | 674 ---------------- packages/transport-http/README.md | 28 - packages/transport-http/mod.ts | 2 - packages/transport-http/package.json | 54 -- .../transport-http/src/localNetwork.test.ts | 36 - packages/transport-http/src/localNetwork.ts | 40 - packages/transport-http/src/transport.test.ts | 247 ------ packages/transport-http/src/transport.ts | 253 ------ packages/transport-http/tsconfig.json | 4 - packages/transport-node-serial/README.md | 28 - packages/transport-node-serial/mod.ts | 1 - packages/transport-node-serial/package.json | 55 -- .../src/transport.test.ts | 231 ------ .../transport-node-serial/src/transport.ts | 188 ----- packages/transport-node-serial/tsconfig.json | 7 - packages/transport-node/README.md | 28 - packages/transport-node/mod.ts | 1 - packages/transport-node/package.json | 54 -- packages/transport-node/src/transport.test.ts | 188 ----- packages/transport-node/src/transport.ts | 205 ----- packages/transport-node/tsconfig.json | 7 - packages/transport-web-bluetooth/README.md | 35 - packages/transport-web-bluetooth/mod.ts | 4 - packages/transport-web-bluetooth/package.json | 55 -- .../src/transport.test.ts | 201 ----- .../transport-web-bluetooth/src/transport.ts | 341 -------- .../transport-web-bluetooth/tsconfig.json | 7 - packages/transport-web-serial/README.md | 35 - packages/transport-web-serial/mod.ts | 1 - packages/transport-web-serial/package.json | 56 -- .../src/transport.test.ts | 371 --------- .../transport-web-serial/src/transport.ts | 439 ----------- packages/transport-web-serial/tsconfig.json | 7 - tests/utils/transportContract.ts | 126 --- 257 files changed, 19409 deletions(-) delete mode 100644 packages/sdk-react/README.md delete mode 100644 packages/sdk-react/mod.ts delete mode 100644 packages/sdk-react/package.json delete mode 100644 packages/sdk-react/src/adapters/useActiveClient.ts delete mode 100644 packages/sdk-react/src/adapters/useClient.ts delete mode 100644 packages/sdk-react/src/adapters/useClientById.ts delete mode 100644 packages/sdk-react/src/adapters/useMeshRegistry.ts delete mode 100644 packages/sdk-react/src/adapters/useSignal.ts delete mode 100644 packages/sdk-react/src/adapters/useSignalValue.ts delete mode 100644 packages/sdk-react/src/hooks/useChannels.ts delete mode 100644 packages/sdk-react/src/hooks/useChat.ts delete mode 100644 packages/sdk-react/src/hooks/useConfig.ts delete mode 100644 packages/sdk-react/src/hooks/useConfigEditor.ts delete mode 100644 packages/sdk-react/src/hooks/useConnection.ts delete mode 100644 packages/sdk-react/src/hooks/useConnectionProgress.ts delete mode 100644 packages/sdk-react/src/hooks/useDirectChat.ts delete mode 100644 packages/sdk-react/src/hooks/useDraft.ts delete mode 100644 packages/sdk-react/src/hooks/useFavoriteNode.ts delete mode 100644 packages/sdk-react/src/hooks/useFileTransfer.ts delete mode 100644 packages/sdk-react/src/hooks/useIgnoreNode.ts delete mode 100644 packages/sdk-react/src/hooks/useMeshDevice.ts delete mode 100644 packages/sdk-react/src/hooks/useModuleMessages.ts delete mode 100644 packages/sdk-react/src/hooks/useNode.ts delete mode 100644 packages/sdk-react/src/hooks/useNodeError.ts delete mode 100644 packages/sdk-react/src/hooks/useNodes.ts delete mode 100644 packages/sdk-react/src/hooks/usePosition.ts delete mode 100644 packages/sdk-react/src/hooks/useTelemetry.ts delete mode 100644 packages/sdk-react/src/hooks/useTraceroute.ts delete mode 100644 packages/sdk-react/src/hooks/useUnread.ts delete mode 100644 packages/sdk-react/src/provider/MeshContext.ts delete mode 100644 packages/sdk-react/src/provider/MeshProvider.tsx delete mode 100644 packages/sdk-react/src/provider/MeshRegistryContext.ts delete mode 100644 packages/sdk-react/src/provider/MeshRegistryProvider.tsx delete mode 100644 packages/sdk-react/tests/hooks.registry.test.tsx delete mode 100644 packages/sdk-react/tests/hooks.test.tsx delete mode 100644 packages/sdk-react/tests/useModuleMessages.test.tsx delete mode 100644 packages/sdk-react/tsconfig.json delete mode 100644 packages/sdk-react/vitest.config.ts delete mode 100644 packages/sdk-storage-sqlocal/README.md delete mode 100644 packages/sdk-storage-sqlocal/mod.ts delete mode 100644 packages/sdk-storage-sqlocal/package.json delete mode 100644 packages/sdk-storage-sqlocal/src/chat/SqlocalDraftRepository.test.ts delete mode 100644 packages/sdk-storage-sqlocal/src/chat/SqlocalDraftRepository.ts delete mode 100644 packages/sdk-storage-sqlocal/src/chat/SqlocalMessageRepository.test.ts delete mode 100644 packages/sdk-storage-sqlocal/src/chat/SqlocalMessageRepository.ts delete mode 100644 packages/sdk-storage-sqlocal/src/chat/index.ts delete mode 100644 packages/sdk-storage-sqlocal/src/coordination/MultiTabCoordinator.broadcast.test.ts delete mode 100644 packages/sdk-storage-sqlocal/src/coordination/MultiTabCoordinator.test.ts delete mode 100644 packages/sdk-storage-sqlocal/src/coordination/MultiTabCoordinator.ts delete mode 100644 packages/sdk-storage-sqlocal/src/coordination/index.ts delete mode 100644 packages/sdk-storage-sqlocal/src/db.ts delete mode 100644 packages/sdk-storage-sqlocal/src/nodes/SqlocalNodesRepository.test.ts delete mode 100644 packages/sdk-storage-sqlocal/src/nodes/SqlocalNodesRepository.ts delete mode 100644 packages/sdk-storage-sqlocal/src/nodes/index.ts delete mode 100644 packages/sdk-storage-sqlocal/src/schema/chat.ts delete mode 100644 packages/sdk-storage-sqlocal/src/schema/drafts.ts delete mode 100644 packages/sdk-storage-sqlocal/src/schema/index.ts delete mode 100644 packages/sdk-storage-sqlocal/src/schema/migrations.test.ts delete mode 100644 packages/sdk-storage-sqlocal/src/schema/migrations.ts delete mode 100644 packages/sdk-storage-sqlocal/src/schema/nodes.ts delete mode 100644 packages/sdk-storage-sqlocal/src/schema/telemetry.ts delete mode 100644 packages/sdk-storage-sqlocal/src/telemetry/SqlocalTelemetryRepository.test.ts delete mode 100644 packages/sdk-storage-sqlocal/src/telemetry/SqlocalTelemetryRepository.ts delete mode 100644 packages/sdk-storage-sqlocal/src/telemetry/index.ts delete mode 100644 packages/sdk-storage-sqlocal/src/testing/createMemoryDb.ts delete mode 100644 packages/sdk-storage-sqlocal/src/testing/index.ts delete mode 100644 packages/sdk-storage-sqlocal/tests/sqlocal-opfs.browser.test.ts delete mode 100644 packages/sdk-storage-sqlocal/tsconfig.json delete mode 100644 packages/sdk-storage-sqlocal/vitest.browser.config.ts delete mode 100644 packages/sdk-storage-sqlocal/vitest.config.ts delete mode 100644 packages/sdk/README.md delete mode 100644 packages/sdk/mod.ts delete mode 100644 packages/sdk/package.json delete mode 100644 packages/sdk/scripts/rename-dts.mjs delete mode 100644 packages/sdk/src/core/client/MeshClient.handshake.test.ts delete mode 100644 packages/sdk/src/core/client/MeshClient.progress.test.ts delete mode 100644 packages/sdk/src/core/client/MeshClient.storageScope.test.ts delete mode 100644 packages/sdk/src/core/client/MeshClient.ts delete mode 100644 packages/sdk/src/core/client/handshake.ts delete mode 100644 packages/sdk/src/core/client/index.ts delete mode 100644 packages/sdk/src/core/constants/index.ts delete mode 100644 packages/sdk/src/core/errors/MeshError.ts delete mode 100644 packages/sdk/src/core/event-bus/EventBus.test.ts delete mode 100644 packages/sdk/src/core/event-bus/EventBus.ts delete mode 100644 packages/sdk/src/core/event-bus/index.ts delete mode 100644 packages/sdk/src/core/identifiers/PacketId.ts delete mode 100644 packages/sdk/src/core/logging/logger.ts delete mode 100644 packages/sdk/src/core/packet-codec/decodePacket.test.ts delete mode 100644 packages/sdk/src/core/packet-codec/decodePacket.ts delete mode 100644 packages/sdk/src/core/packet-codec/fromDevice.test.ts delete mode 100644 packages/sdk/src/core/packet-codec/fromDevice.ts delete mode 100644 packages/sdk/src/core/packet-codec/index.ts delete mode 100644 packages/sdk/src/core/packet-codec/toDevice.ts delete mode 100644 packages/sdk/src/core/protobuf/index.ts delete mode 100644 packages/sdk/src/core/queue/Queue.ts delete mode 100644 packages/sdk/src/core/registry/MeshRegistry.test.ts delete mode 100644 packages/sdk/src/core/registry/MeshRegistry.ts delete mode 100644 packages/sdk/src/core/registry/index.ts delete mode 100644 packages/sdk/src/core/signals/createStore.test.ts delete mode 100644 packages/sdk/src/core/signals/createStore.ts delete mode 100644 packages/sdk/src/core/signals/index.ts delete mode 100644 packages/sdk/src/core/testing/createFakeTransport.ts delete mode 100644 packages/sdk/src/core/testing/index.ts delete mode 100644 packages/sdk/src/core/testing/interceptAdminMessages.ts delete mode 100644 packages/sdk/src/core/transport/Transport.ts delete mode 100644 packages/sdk/src/core/transport/index.ts delete mode 100644 packages/sdk/src/core/types.ts delete mode 100644 packages/sdk/src/core/xmodem/Xmodem.ts delete mode 100644 packages/sdk/src/features/channels/ChannelsClient.test.ts delete mode 100644 packages/sdk/src/features/channels/ChannelsClient.ts delete mode 100644 packages/sdk/src/features/channels/application/ChannelUseCases.ts delete mode 100644 packages/sdk/src/features/channels/domain/Channel.ts delete mode 100644 packages/sdk/src/features/channels/domain/MeshBeaconOffer.test.ts delete mode 100644 packages/sdk/src/features/channels/domain/MeshBeaconOffer.ts delete mode 100644 packages/sdk/src/features/channels/index.ts delete mode 100644 packages/sdk/src/features/channels/infrastructure/ChannelMapper.ts delete mode 100644 packages/sdk/src/features/channels/state/channelsStore.ts delete mode 100644 packages/sdk/src/features/chat/ChatClient.drafts.test.ts delete mode 100644 packages/sdk/src/features/chat/ChatClient.persistence.test.ts delete mode 100644 packages/sdk/src/features/chat/ChatClient.send.test.ts delete mode 100644 packages/sdk/src/features/chat/ChatClient.ts delete mode 100644 packages/sdk/src/features/chat/ChatClient.unread.test.ts delete mode 100644 packages/sdk/src/features/chat/application/SendTextUseCase.test.ts delete mode 100644 packages/sdk/src/features/chat/application/SendTextUseCase.ts delete mode 100644 packages/sdk/src/features/chat/application/SendWaypointUseCase.ts delete mode 100644 packages/sdk/src/features/chat/domain/DraftRepository.ts delete mode 100644 packages/sdk/src/features/chat/domain/Message.test.ts delete mode 100644 packages/sdk/src/features/chat/domain/Message.ts delete mode 100644 packages/sdk/src/features/chat/domain/MessageRepository.ts delete mode 100644 packages/sdk/src/features/chat/domain/MessageState.ts delete mode 100644 packages/sdk/src/features/chat/index.ts delete mode 100644 packages/sdk/src/features/chat/infrastructure/MessageMapper.ts delete mode 100644 packages/sdk/src/features/chat/infrastructure/repositories/InMemoryDraftRepository.ts delete mode 100644 packages/sdk/src/features/chat/infrastructure/repositories/InMemoryMessageRepository.test.ts delete mode 100644 packages/sdk/src/features/chat/infrastructure/repositories/InMemoryMessageRepository.ts delete mode 100644 packages/sdk/src/features/chat/state/chatStore.ts delete mode 100644 packages/sdk/src/features/chat/state/draftStore.ts delete mode 100644 packages/sdk/src/features/config/ConfigClient.test.ts delete mode 100644 packages/sdk/src/features/config/ConfigClient.ts delete mode 100644 packages/sdk/src/features/config/ConfigEditor.test.ts delete mode 100644 packages/sdk/src/features/config/ModuleMessages.test.ts delete mode 100644 packages/sdk/src/features/config/application/ConfigUseCases.ts delete mode 100644 packages/sdk/src/features/config/application/ModuleMessagesUseCases.ts delete mode 100644 packages/sdk/src/features/config/domain/ConfigEditor.ts delete mode 100644 packages/sdk/src/features/config/domain/ModuleConfig.ts delete mode 100644 packages/sdk/src/features/config/domain/RadioConfig.ts delete mode 100644 packages/sdk/src/features/config/index.ts delete mode 100644 packages/sdk/src/features/config/infrastructure/ConfigMapper.ts delete mode 100644 packages/sdk/src/features/config/state/configStore.ts delete mode 100644 packages/sdk/src/features/device/DeviceClient.keyVerification.test.ts delete mode 100644 packages/sdk/src/features/device/DeviceClient.ts delete mode 100644 packages/sdk/src/features/device/application/ConfigureUseCase.ts delete mode 100644 packages/sdk/src/features/device/application/DisconnectUseCase.ts delete mode 100644 packages/sdk/src/features/device/application/GetMetadataUseCase.ts delete mode 100644 packages/sdk/src/features/device/application/HeartbeatService.ts delete mode 100644 packages/sdk/src/features/device/application/LockdownService.test.ts delete mode 100644 packages/sdk/src/features/device/application/LockdownService.ts delete mode 100644 packages/sdk/src/features/device/application/RebootService.ts delete mode 100644 packages/sdk/src/features/device/domain/Device.ts delete mode 100644 packages/sdk/src/features/device/domain/DeviceStatus.ts delete mode 100644 packages/sdk/src/features/device/domain/FirmwareVersion.test.ts delete mode 100644 packages/sdk/src/features/device/domain/FirmwareVersion.ts delete mode 100644 packages/sdk/src/features/device/index.ts delete mode 100644 packages/sdk/src/features/device/infrastructure/AdminMessageSender.ts delete mode 100644 packages/sdk/src/features/device/infrastructure/AdminSession.test.ts delete mode 100644 packages/sdk/src/features/device/infrastructure/AdminSession.ts delete mode 100644 packages/sdk/src/features/device/state/deviceStore.ts delete mode 100644 packages/sdk/src/features/files/FilesClient.ts delete mode 100644 packages/sdk/src/features/files/domain/FileTransfer.ts delete mode 100644 packages/sdk/src/features/files/index.ts delete mode 100644 packages/sdk/src/features/files/state/filesStore.ts delete mode 100644 packages/sdk/src/features/nodes/NodesClient.errors.test.ts delete mode 100644 packages/sdk/src/features/nodes/NodesClient.test.ts delete mode 100644 packages/sdk/src/features/nodes/NodesClient.ts delete mode 100644 packages/sdk/src/features/nodes/application/FavoriteNodeUseCase.ts delete mode 100644 packages/sdk/src/features/nodes/application/IgnoreNodeUseCase.ts delete mode 100644 packages/sdk/src/features/nodes/application/RemoveNodeUseCase.ts delete mode 100644 packages/sdk/src/features/nodes/application/SetOwnerUseCase.ts delete mode 100644 packages/sdk/src/features/nodes/domain/Node.ts delete mode 100644 packages/sdk/src/features/nodes/domain/NodeError.ts delete mode 100644 packages/sdk/src/features/nodes/domain/NodesRepository.ts delete mode 100644 packages/sdk/src/features/nodes/index.ts delete mode 100644 packages/sdk/src/features/nodes/infrastructure/NodeMapper.test.ts delete mode 100644 packages/sdk/src/features/nodes/infrastructure/NodeMapper.ts delete mode 100644 packages/sdk/src/features/nodes/infrastructure/nodeValidation.ts delete mode 100644 packages/sdk/src/features/nodes/infrastructure/repositories/InMemoryNodesRepository.ts delete mode 100644 packages/sdk/src/features/nodes/state/nodeErrorsStore.ts delete mode 100644 packages/sdk/src/features/nodes/state/nodesStore.ts delete mode 100644 packages/sdk/src/features/position/PositionClient.test.ts delete mode 100644 packages/sdk/src/features/position/PositionClient.ts delete mode 100644 packages/sdk/src/features/position/application/PositionUseCases.ts delete mode 100644 packages/sdk/src/features/position/domain/Position.ts delete mode 100644 packages/sdk/src/features/position/index.ts delete mode 100644 packages/sdk/src/features/position/infrastructure/PositionMapper.ts delete mode 100644 packages/sdk/src/features/position/state/positionStore.ts delete mode 100644 packages/sdk/src/features/telemetry/TelemetryClient.persistence.test.ts delete mode 100644 packages/sdk/src/features/telemetry/TelemetryClient.test.ts delete mode 100644 packages/sdk/src/features/telemetry/TelemetryClient.ts delete mode 100644 packages/sdk/src/features/telemetry/domain/TelemetryReading.ts delete mode 100644 packages/sdk/src/features/telemetry/domain/TelemetryRepository.ts delete mode 100644 packages/sdk/src/features/telemetry/index.ts delete mode 100644 packages/sdk/src/features/telemetry/infrastructure/TelemetryMapper.ts delete mode 100644 packages/sdk/src/features/telemetry/infrastructure/repositories/InMemoryTelemetryRepository.test.ts delete mode 100644 packages/sdk/src/features/telemetry/infrastructure/repositories/InMemoryTelemetryRepository.ts delete mode 100644 packages/sdk/src/features/telemetry/state/telemetryStore.ts delete mode 100644 packages/sdk/src/features/traceroute/TraceRouteClient.ts delete mode 100644 packages/sdk/src/features/traceroute/application/TraceRouteUseCase.ts delete mode 100644 packages/sdk/src/features/traceroute/domain/TraceRoute.ts delete mode 100644 packages/sdk/src/features/traceroute/index.ts delete mode 100644 packages/sdk/src/features/traceroute/state/tracerouteStore.ts delete mode 100644 packages/sdk/src/shim/legacyMeshDevice.ts delete mode 100644 packages/sdk/src/shim/legacyTypes.ts delete mode 100644 packages/sdk/src/shim/legacyUtils.ts delete mode 100644 packages/sdk/src/types-namespace.ts delete mode 100644 packages/sdk/tests/integration/fake-transport.test.ts delete mode 100644 packages/sdk/tsconfig.json delete mode 100644 packages/sdk/vitest.config.ts delete mode 100644 packages/transport-deno/README.md delete mode 100644 packages/transport-deno/deno.json delete mode 100644 packages/transport-deno/mod.ts delete mode 100644 packages/transport-deno/package.json delete mode 100644 packages/transport-deno/scripts/build_npm.ts delete mode 100644 packages/transport-deno/src/transport.ts delete mode 100644 packages/transport-http/LICENSE delete mode 100644 packages/transport-http/README.md delete mode 100644 packages/transport-http/mod.ts delete mode 100644 packages/transport-http/package.json delete mode 100644 packages/transport-http/src/localNetwork.test.ts delete mode 100644 packages/transport-http/src/localNetwork.ts delete mode 100644 packages/transport-http/src/transport.test.ts delete mode 100644 packages/transport-http/src/transport.ts delete mode 100644 packages/transport-http/tsconfig.json delete mode 100644 packages/transport-node-serial/README.md delete mode 100644 packages/transport-node-serial/mod.ts delete mode 100644 packages/transport-node-serial/package.json delete mode 100644 packages/transport-node-serial/src/transport.test.ts delete mode 100644 packages/transport-node-serial/src/transport.ts delete mode 100644 packages/transport-node-serial/tsconfig.json delete mode 100644 packages/transport-node/README.md delete mode 100644 packages/transport-node/mod.ts delete mode 100644 packages/transport-node/package.json delete mode 100644 packages/transport-node/src/transport.test.ts delete mode 100644 packages/transport-node/src/transport.ts delete mode 100644 packages/transport-node/tsconfig.json delete mode 100644 packages/transport-web-bluetooth/README.md delete mode 100644 packages/transport-web-bluetooth/mod.ts delete mode 100644 packages/transport-web-bluetooth/package.json delete mode 100644 packages/transport-web-bluetooth/src/transport.test.ts delete mode 100644 packages/transport-web-bluetooth/src/transport.ts delete mode 100644 packages/transport-web-bluetooth/tsconfig.json delete mode 100644 packages/transport-web-serial/README.md delete mode 100644 packages/transport-web-serial/mod.ts delete mode 100644 packages/transport-web-serial/package.json delete mode 100644 packages/transport-web-serial/src/transport.test.ts delete mode 100644 packages/transport-web-serial/src/transport.ts delete mode 100644 packages/transport-web-serial/tsconfig.json delete mode 100644 tests/utils/transportContract.ts diff --git a/packages/sdk-react/README.md b/packages/sdk-react/README.md deleted file mode 100644 index a9b3d7ddc..000000000 --- a/packages/sdk-react/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# @meshtastic/sdk-react - -React hooks and provider for `@meshtastic/sdk`. - -## Install - -```sh -pnpm add @meshtastic/sdk @meshtastic/sdk-react @meshtastic/transport-web-serial -``` - -## Quickstart - -```tsx -import { MeshClient } from "@meshtastic/sdk"; -import { MeshProvider, useDevice, useChat } from "@meshtastic/sdk-react"; -import { TransportWebSerial } from "@meshtastic/transport-web-serial"; -import { ChannelNumber } from "@meshtastic/sdk"; - -const transport = await TransportWebSerial.create({ baudRate: 115200 }); -const client = new MeshClient({ transport }); -await client.connect(); - -function App() { - return ( - - - - ); -} - -function Status() { - const { status, myNodeNum } = useDevice(); - const { messages, send } = useChat(ChannelNumber.Primary); - return
{status} / {myNodeNum} / {messages.length} msgs
; -} -``` - -All hooks are read-only against a single `MeshClient` instance supplied through context. Commands are returned as stable functions. - -## License - -GPL-3.0-only. diff --git a/packages/sdk-react/mod.ts b/packages/sdk-react/mod.ts deleted file mode 100644 index 0d3d06ebf..000000000 --- a/packages/sdk-react/mod.ts +++ /dev/null @@ -1,59 +0,0 @@ -export { MeshProvider } from "./src/provider/MeshProvider.tsx"; -export type { MeshProviderProps } from "./src/provider/MeshProvider.tsx"; -export { MeshContext } from "./src/provider/MeshContext.ts"; -export { MeshRegistryProvider } from "./src/provider/MeshRegistryProvider.tsx"; -export type { MeshRegistryProviderProps } from "./src/provider/MeshRegistryProvider.tsx"; -export { MeshRegistryContext } from "./src/provider/MeshRegistryContext.ts"; - -export { useClient } from "./src/adapters/useClient.ts"; -export { useClientById } from "./src/adapters/useClientById.ts"; -export { useActiveClient } from "./src/adapters/useActiveClient.ts"; -export { - useMeshRegistry, - useOptionalMeshRegistry, -} from "./src/adapters/useMeshRegistry.ts"; -export { useSignal } from "./src/adapters/useSignal.ts"; -export { useSignalValue } from "./src/adapters/useSignalValue.ts"; - -export { useMeshDevice } from "./src/hooks/useMeshDevice.ts"; -export type { UseMeshDeviceResult } from "./src/hooks/useMeshDevice.ts"; -export { useConnection } from "./src/hooks/useConnection.ts"; -export type { UseConnectionResult } from "./src/hooks/useConnection.ts"; -export { useChat } from "./src/hooks/useChat.ts"; -export type { UseChatResult } from "./src/hooks/useChat.ts"; -export { useDirectChat } from "./src/hooks/useDirectChat.ts"; -export type { UseDirectChatResult } from "./src/hooks/useDirectChat.ts"; -export { useDraft } from "./src/hooks/useDraft.ts"; -export type { UseDraftResult } from "./src/hooks/useDraft.ts"; -export { - useHasNodeError, - useNodeError, - useNodeErrors, -} from "./src/hooks/useNodeError.ts"; -export { useNodes } from "./src/hooks/useNodes.ts"; -export { useNode } from "./src/hooks/useNode.ts"; -export { useChannels, useChannel } from "./src/hooks/useChannels.ts"; -export { - useConfig, - useIsRegionUnset, - useModuleConfig, -} from "./src/hooks/useConfig.ts"; -export { useConfigEditor } from "./src/hooks/useConfigEditor.ts"; -export { - useCannedMessages, - useRingtone, -} from "./src/hooks/useModuleMessages.ts"; -export type { UseModuleMessagesResult } from "./src/hooks/useModuleMessages.ts"; -export { useConnectionProgress } from "./src/hooks/useConnectionProgress.ts"; -export { - useTotalUnread, - useUnreadByKey, - useUnreadCount, -} from "./src/hooks/useUnread.ts"; -export { useTelemetry } from "./src/hooks/useTelemetry.ts"; -export type { UseTelemetryResult } from "./src/hooks/useTelemetry.ts"; -export { usePosition } from "./src/hooks/usePosition.ts"; -export { useTraceroute } from "./src/hooks/useTraceroute.ts"; -export { useFileTransfer } from "./src/hooks/useFileTransfer.ts"; -export { useFavoriteNode } from "./src/hooks/useFavoriteNode.ts"; -export { useIgnoreNode } from "./src/hooks/useIgnoreNode.ts"; diff --git a/packages/sdk-react/package.json b/packages/sdk-react/package.json deleted file mode 100644 index 269f865b6..000000000 --- a/packages/sdk-react/package.json +++ /dev/null @@ -1,72 +0,0 @@ -{ - "name": "@meshtastic/sdk-react", - "version": "1.0.0", - "description": "React hooks + provider for @meshtastic/sdk. Signal-backed reactive state exposed as idiomatic hooks.", - "license": "GPL-3.0-only", - "repository": { - "type": "git", - "url": "git+https://github.com/meshtastic/web.git", - "directory": "packages/sdk-react" - }, - "files": [ - "package.json", - "README.md", - "LICENSE", - "dist" - ], - "type": "module", - "main": "./dist/mod.js", - "module": "./dist/mod.js", - "types": "./dist/mod.d.ts", - "exports": { - ".": "./mod.ts" - }, - "scripts": { - "preinstall": "npx only-allow pnpm", - "prepack": "cp ../../LICENSE ./LICENSE", - "clean": "rm -rf dist LICENSE", - "build:npm": "tsdown", - "publish:npm": "pnpm clean && pnpm build:npm && pnpm publish --access public --no-git-checks", - "test": "vitest run" - }, - "dependencies": { - "@meshtastic/sdk": "workspace:*", - "better-result": "^3.0.1" - }, - "devDependencies": { - "@testing-library/react": "^16.3.3", - "@types/react": "^19.3.0", - "jsdom": "^30.1.3", - "react": "^19.3.1", - "react-dom": "^19.3.1" - }, - "peerDependencies": { - "react": "^18 || ^19" - }, - "tsdown": { - "clean": true, - "dts": true, - "entry": "mod.ts", - "format": [ - "esm" - ], - "minify": false, - "platform": "neutral", - "report": false, - "sourcemap": false, - "splitting": false, - "target": "esnext", - "treeshake": true - }, - "jsrExclude": [ - "src/**/*.test.ts", - "src/**/*.test.tsx", - "tests" - ], - "jsrInclude": [ - "mod.ts", - "src", - "README.md", - "LICENSE" - ] -} diff --git a/packages/sdk-react/src/adapters/useActiveClient.ts b/packages/sdk-react/src/adapters/useActiveClient.ts deleted file mode 100644 index 7f615d5dd..000000000 --- a/packages/sdk-react/src/adapters/useActiveClient.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { MeshClient } from "@meshtastic/sdk"; -import { useMeshRegistry } from "./useMeshRegistry.ts"; -import { useSignal } from "./useSignal.ts"; - -export function useActiveClient(): MeshClient | undefined { - const registry = useMeshRegistry(); - return useSignal(registry.active); -} diff --git a/packages/sdk-react/src/adapters/useClient.ts b/packages/sdk-react/src/adapters/useClient.ts deleted file mode 100644 index 596c02b8b..000000000 --- a/packages/sdk-react/src/adapters/useClient.ts +++ /dev/null @@ -1,31 +0,0 @@ -import type { MeshClient } from "@meshtastic/sdk"; -import { useContext } from "react"; -import { MeshContext } from "../provider/MeshContext.ts"; -import { MeshRegistryContext } from "../provider/MeshRegistryContext.ts"; -import { useSignal } from "./useSignal.ts"; - -/** - * Returns the `MeshClient` for the current tree. Resolves in this order: - * 1. The nearest ``. - * 2. The active client of the nearest ``. - * - * Throws if neither is present or the registry has no active client. - */ -export function useClient(): MeshClient { - const direct = useContext(MeshContext); - const registry = useContext(MeshRegistryContext); - const active = useSignal( - registry?.active ?? { - value: undefined, - peek: () => undefined, - subscribe: () => () => {}, - }, - ); - const client = direct ?? active; - if (!client) { - throw new Error( - "useClient must be called inside a or a with an active client.", - ); - } - return client; -} diff --git a/packages/sdk-react/src/adapters/useClientById.ts b/packages/sdk-react/src/adapters/useClientById.ts deleted file mode 100644 index 43cb8c7d5..000000000 --- a/packages/sdk-react/src/adapters/useClientById.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { ConnectionId, MeshClient } from "@meshtastic/sdk"; -import { useMeshRegistry } from "./useMeshRegistry.ts"; - -export function useClientById(id: ConnectionId): MeshClient { - const registry = useMeshRegistry(); - const client = registry.get(id); - if (!client) { - throw new Error(`No MeshClient registered for id ${id}`); - } - return client; -} diff --git a/packages/sdk-react/src/adapters/useMeshRegistry.ts b/packages/sdk-react/src/adapters/useMeshRegistry.ts deleted file mode 100644 index 5bb65dbe7..000000000 --- a/packages/sdk-react/src/adapters/useMeshRegistry.ts +++ /dev/null @@ -1,17 +0,0 @@ -import type { MeshRegistry } from "@meshtastic/sdk"; -import { useContext } from "react"; -import { MeshRegistryContext } from "../provider/MeshRegistryContext.ts"; - -export function useMeshRegistry(): MeshRegistry { - const registry = useContext(MeshRegistryContext); - if (!registry) { - throw new Error( - "useMeshRegistry must be called inside a .", - ); - } - return registry; -} - -export function useOptionalMeshRegistry(): MeshRegistry | undefined { - return useContext(MeshRegistryContext); -} diff --git a/packages/sdk-react/src/adapters/useSignal.ts b/packages/sdk-react/src/adapters/useSignal.ts deleted file mode 100644 index 582f65f6a..000000000 --- a/packages/sdk-react/src/adapters/useSignal.ts +++ /dev/null @@ -1,16 +0,0 @@ -import type { ReadonlySignal } from "@meshtastic/sdk"; -import { useSyncExternalStore } from "react"; - -/** - * Subscribes a component to a SDK ReadonlySignal and returns the current value. - * - * Uses useSyncExternalStore so concurrent-mode renders see a consistent - * snapshot. The signal's `.subscribe` is called once per mount. - */ -export function useSignal(sig: ReadonlySignal): T { - return useSyncExternalStore( - sig.subscribe, - () => sig.value, - () => sig.peek(), - ); -} diff --git a/packages/sdk-react/src/adapters/useSignalValue.ts b/packages/sdk-react/src/adapters/useSignalValue.ts deleted file mode 100644 index a8c3e7a96..000000000 --- a/packages/sdk-react/src/adapters/useSignalValue.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { ReadonlySignal } from "@meshtastic/sdk"; -import { useCallback, useSyncExternalStore } from "react"; - -/** - * Like `useSignal` but projects the signal value through a selector before - * returning. The selector should be stable; memoize it with `useCallback` in - * the caller when it closes over changing values. - */ -export function useSignalValue( - sig: ReadonlySignal, - select: (value: T) => U, -): U { - const getSnapshot = useCallback(() => select(sig.value), [sig, select]); - const getServerSnapshot = useCallback( - () => select(sig.peek()), - [sig, select], - ); - return useSyncExternalStore(sig.subscribe, getSnapshot, getServerSnapshot); -} diff --git a/packages/sdk-react/src/hooks/useChannels.ts b/packages/sdk-react/src/hooks/useChannels.ts deleted file mode 100644 index 4982d0964..000000000 --- a/packages/sdk-react/src/hooks/useChannels.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { Channel } from "@meshtastic/sdk"; -import { useActiveClient } from "../adapters/useActiveClient.ts"; -import { useSignal } from "../adapters/useSignal.ts"; - -const EMPTY: ReadonlyArray = []; -const EMPTY_SIGNAL = { - value: EMPTY, - peek: () => EMPTY, - subscribe: () => () => {}, -}; - -/** - * Returns the channel list from the active client. Empty when no client - * is active (e.g. before any device connects, or in isolated tests). - */ -export function useChannels(): ReadonlyArray { - const client = useActiveClient(); - return useSignal(client?.channels.list ?? EMPTY_SIGNAL); -} - -export function useChannel(index: number): Channel | undefined { - const channels = useChannels(); - return channels.find((c) => c.index === index); -} diff --git a/packages/sdk-react/src/hooks/useChat.ts b/packages/sdk-react/src/hooks/useChat.ts deleted file mode 100644 index 65b30ca5d..000000000 --- a/packages/sdk-react/src/hooks/useChat.ts +++ /dev/null @@ -1,35 +0,0 @@ -import type { - ChannelNumber, - ConversationKey, - Message, - SendTextError, - SendTextInput, -} from "@meshtastic/sdk"; -import type { Result } from "better-result"; -import { useCallback, useMemo } from "react"; -import { useClient } from "../adapters/useClient.ts"; -import { useSignal } from "../adapters/useSignal.ts"; - -export interface UseChatResult { - messages: Message[]; - send(input: SendTextInput): Promise>; - loadOlder(before: Date, limit?: number): Promise; -} - -export function useChat(channel: ChannelNumber): UseChatResult { - const client = useClient(); - const sig = useMemo(() => client.chat.messages(channel), [client, channel]); - const messages = useSignal(sig); - const send = useCallback( - (input: SendTextInput) => client.chat.send(input), - [client], - ); - const loadOlder = useCallback( - (before: Date, limit?: number) => { - const conv: ConversationKey = { kind: "channel", channel }; - return client.chat.loadOlder(conv, before, limit); - }, - [client, channel], - ); - return { messages, send, loadOlder }; -} diff --git a/packages/sdk-react/src/hooks/useConfig.ts b/packages/sdk-react/src/hooks/useConfig.ts deleted file mode 100644 index 84259c7ea..000000000 --- a/packages/sdk-react/src/hooks/useConfig.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { ModuleConfig, RadioConfig } from "@meshtastic/sdk"; -import { useClient } from "../adapters/useClient.ts"; -import { useSignal } from "../adapters/useSignal.ts"; - -export function useConfig(): RadioConfig { - const client = useClient(); - return useSignal(client.config.radio); -} - -export function useModuleConfig(): ModuleConfig { - const client = useClient(); - return useSignal(client.config.modules); -} - -/** - * `true` when the connected device's LoRa region is UNSET — the canonical - * "this device was just flashed and hasn't been provisioned" cue. See - * `ConfigClient.isRegionUnset` for semantics + reference to the equivalent - * Meshtastic-Android flow. - */ -export function useIsRegionUnset(): boolean { - const client = useClient(); - return useSignal(client.config.isRegionUnset); -} diff --git a/packages/sdk-react/src/hooks/useConfigEditor.ts b/packages/sdk-react/src/hooks/useConfigEditor.ts deleted file mode 100644 index eed0660dd..000000000 --- a/packages/sdk-react/src/hooks/useConfigEditor.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ConfigEditor } from "@meshtastic/sdk"; -import { useActiveClient } from "../adapters/useActiveClient.ts"; - -/** - * Returns the active client's `ConfigEditor`, or `undefined` when no client - * is active. The editor itself owns reactive signals — components bind to - * `editor.radio.value`, `editor.dirtyRadioSections.value`, etc. via - * `useSignal` (or the existing `useSignalValue`/`useSyncExternalStore` - * helpers) to re-render on change. - */ -export function useConfigEditor(): ConfigEditor | undefined { - const client = useActiveClient(); - return client?.config.editor; -} diff --git a/packages/sdk-react/src/hooks/useConnection.ts b/packages/sdk-react/src/hooks/useConnection.ts deleted file mode 100644 index b7fc6883b..000000000 --- a/packages/sdk-react/src/hooks/useConnection.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { DeviceStatusEnum } from "@meshtastic/sdk"; -import { useCallback } from "react"; -import { useClient } from "../adapters/useClient.ts"; -import { useSignal } from "../adapters/useSignal.ts"; - -export interface UseConnectionResult { - status: DeviceStatusEnum; - isConnected: boolean; - isConnecting: boolean; - connect(): Promise; - disconnect(): Promise; -} - -export function useConnection(): UseConnectionResult { - const client = useClient(); - const status = useSignal(client.device.status); - const connect = useCallback(() => client.connect(), [client]); - const disconnect = useCallback(() => client.disconnect(), [client]); - - return { - status, - isConnected: - status === DeviceStatusEnum.DeviceConnected || - status === DeviceStatusEnum.DeviceConfiguring || - status === DeviceStatusEnum.DeviceConfigured, - isConnecting: status === DeviceStatusEnum.DeviceConnecting, - connect, - disconnect, - }; -} diff --git a/packages/sdk-react/src/hooks/useConnectionProgress.ts b/packages/sdk-react/src/hooks/useConnectionProgress.ts deleted file mode 100644 index 6371dc998..000000000 --- a/packages/sdk-react/src/hooks/useConnectionProgress.ts +++ /dev/null @@ -1,23 +0,0 @@ -import type { ConnectionProgress, ReadonlySignal } from "@meshtastic/sdk"; -import { useActiveClient } from "../adapters/useActiveClient.ts"; -import { useSignal } from "../adapters/useSignal.ts"; - -const IDLE_PROGRESS: ConnectionProgress = { phase: "idle" }; -const IDLE_SIGNAL: ReadonlySignal = { - value: IDLE_PROGRESS, - peek: () => IDLE_PROGRESS, - subscribe: () => () => {}, -}; - -/** - * Live view of `MeshClient.progress` for the active registry client. - * Returns `{ phase: "idle" }` when no client is active or before - * `configure()` runs; flips through `configuring` (with per-section - * counters) and lands on `configured` once the device finishes streaming - * its config bundle. UI surfaces use this to drive a connecting overlay - * with live "received N nodes / X channels" feedback. - */ -export function useConnectionProgress(): ConnectionProgress { - const client = useActiveClient(); - return useSignal(client?.progress ?? IDLE_SIGNAL); -} diff --git a/packages/sdk-react/src/hooks/useDirectChat.ts b/packages/sdk-react/src/hooks/useDirectChat.ts deleted file mode 100644 index 49b194837..000000000 --- a/packages/sdk-react/src/hooks/useDirectChat.ts +++ /dev/null @@ -1,40 +0,0 @@ -import type { - ConversationKey, - Message, - SendTextError, - SendTextInput, -} from "@meshtastic/sdk"; -import type { Result } from "better-result"; -import { useCallback, useMemo } from "react"; -import { useClient } from "../adapters/useClient.ts"; -import { useSignal } from "../adapters/useSignal.ts"; - -export interface UseDirectChatResult { - messages: Message[]; - send(input: SendTextInput): Promise>; - loadOlder(before: Date, limit?: number): Promise; -} - -/** - * Direct-message conversation with a single peer node. The bucket is keyed - * by the peer (so messages from-me-to-peer and from-peer-to-me share one - * bucket). Lazy-hydrates from the configured MessageRepository on first - * subscribe. - */ -export function useDirectChat(peer: number): UseDirectChatResult { - const client = useClient(); - const sig = useMemo(() => client.chat.direct(peer), [client, peer]); - const messages = useSignal(sig); - const send = useCallback( - (input: SendTextInput) => client.chat.send(input), - [client], - ); - const loadOlder = useCallback( - (before: Date, limit?: number) => { - const conv: ConversationKey = { kind: "direct", peer }; - return client.chat.loadOlder(conv, before, limit); - }, - [client, peer], - ); - return { messages, send, loadOlder }; -} diff --git a/packages/sdk-react/src/hooks/useDraft.ts b/packages/sdk-react/src/hooks/useDraft.ts deleted file mode 100644 index 1da974be7..000000000 --- a/packages/sdk-react/src/hooks/useDraft.ts +++ /dev/null @@ -1,36 +0,0 @@ -import type { ConversationKey } from "@meshtastic/sdk"; -import { useCallback, useMemo } from "react"; -import { useClient } from "../adapters/useClient.ts"; -import { useSignal } from "../adapters/useSignal.ts"; - -export interface UseDraftResult { - text: string; - setText(value: string): void; - clear(): void; -} - -/** - * Per-conversation draft text bound to the SDK chat slice. Re-renders on - * every change. Auto-clears when send() succeeds. - */ -export function useDraft(conv: ConversationKey): UseDraftResult { - const client = useClient(); - const sig = useMemo( - () => client.chat.drafts.get(conv), - [client, conv.kind, keyOf(conv)], - ); - const text = useSignal(sig); - const setText = useCallback( - (value: string) => client.chat.drafts.set(conv, value), - [client, conv], - ); - const clear = useCallback( - () => client.chat.drafts.clear(conv), - [client, conv], - ); - return { text, setText, clear }; -} - -function keyOf(conv: ConversationKey): number { - return conv.kind === "channel" ? conv.channel : conv.peer; -} diff --git a/packages/sdk-react/src/hooks/useFavoriteNode.ts b/packages/sdk-react/src/hooks/useFavoriteNode.ts deleted file mode 100644 index 96068c8a2..000000000 --- a/packages/sdk-react/src/hooks/useFavoriteNode.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { Result } from "better-result"; -import { useCallback } from "react"; -import { useClient } from "../adapters/useClient.ts"; - -export function useFavoriteNode() { - const client = useClient(); - const favorite = useCallback( - (nodeNum: number): Promise> => - client.nodes.favorite(nodeNum), - [client], - ); - const unfavorite = useCallback( - (nodeNum: number): Promise> => - client.nodes.unfavorite(nodeNum), - [client], - ); - return { favorite, unfavorite }; -} diff --git a/packages/sdk-react/src/hooks/useFileTransfer.ts b/packages/sdk-react/src/hooks/useFileTransfer.ts deleted file mode 100644 index 02781a62c..000000000 --- a/packages/sdk-react/src/hooks/useFileTransfer.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { FileTransfer } from "@meshtastic/sdk"; -import { useClient } from "../adapters/useClient.ts"; -import { useSignal } from "../adapters/useSignal.ts"; - -export function useFileTransfer(): ReadonlyArray { - const client = useClient(); - return useSignal(client.files.transfers); -} diff --git a/packages/sdk-react/src/hooks/useIgnoreNode.ts b/packages/sdk-react/src/hooks/useIgnoreNode.ts deleted file mode 100644 index 88a0ff0c0..000000000 --- a/packages/sdk-react/src/hooks/useIgnoreNode.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { Result } from "better-result"; -import { useCallback } from "react"; -import { useClient } from "../adapters/useClient.ts"; - -export function useIgnoreNode() { - const client = useClient(); - const ignore = useCallback( - (nodeNum: number): Promise> => - client.nodes.ignore(nodeNum), - [client], - ); - const unignore = useCallback( - (nodeNum: number): Promise> => - client.nodes.unignore(nodeNum), - [client], - ); - return { ignore, unignore }; -} diff --git a/packages/sdk-react/src/hooks/useMeshDevice.ts b/packages/sdk-react/src/hooks/useMeshDevice.ts deleted file mode 100644 index 0b1d06da5..000000000 --- a/packages/sdk-react/src/hooks/useMeshDevice.ts +++ /dev/null @@ -1,35 +0,0 @@ -import type { DeviceStatusEnum, Protobuf } from "@meshtastic/sdk"; -import { useClient } from "../adapters/useClient.ts"; -import { useSignal } from "../adapters/useSignal.ts"; - -export interface UseMeshDeviceResult { - status: DeviceStatusEnum; - isConfigured: boolean; - myNodeNum: number | undefined; - metadata: Protobuf.Mesh.DeviceMetadata | undefined; - reboot(seconds?: number): Promise; - shutdown(seconds?: number): Promise; -} - -/** - * Exposes the device slice of the current MeshClient: status, metadata, and - * reboot/shutdown commands. Named `useMeshDevice` (not `useDevice`) so it does - * not collide with consumer hooks of the same name (e.g. the legacy one in - * `packages/web`). - */ -export function useMeshDevice(): UseMeshDeviceResult { - const client = useClient(); - const status = useSignal(client.device.status); - const isConfigured = useSignal(client.device.isConfigured); - const myNodeNum = useSignal(client.device.myNodeNum); - const metadata = useSignal(client.device.metadata); - - return { - status, - isConfigured, - myNodeNum, - metadata, - reboot: client.device.reboot.bind(client.device), - shutdown: client.device.shutdown.bind(client.device), - }; -} diff --git a/packages/sdk-react/src/hooks/useModuleMessages.ts b/packages/sdk-react/src/hooks/useModuleMessages.ts deleted file mode 100644 index 96c7de8a7..000000000 --- a/packages/sdk-react/src/hooks/useModuleMessages.ts +++ /dev/null @@ -1,134 +0,0 @@ -import type { MeshClient, Protobuf, ReadonlySignal } from "@meshtastic/sdk"; -import { Result } from "better-result"; -import { useCallback, useContext, useEffect, useRef, useState } from "react"; -import { useOptionalMeshRegistry } from "../adapters/useMeshRegistry.ts"; -import { useSignal } from "../adapters/useSignal.ts"; -import { MeshContext } from "../provider/MeshContext.ts"; - -/** How long to wait for the device to answer before giving up. */ -export const MODULE_MESSAGES_TIMEOUT_MS = 15_000; - -export interface UseModuleMessagesResult { - /** The device's value, or undefined until it has answered once. */ - value: string | undefined; - /** A request is out and the device hasn't answered it yet. */ - isLoading: boolean; - /** The request couldn't be sent, or the device didn't answer in time. */ - error: Error | undefined; - /** Ask the device again. */ - refresh: () => void; -} - -const EMPTY_STRING_SIGNAL: ReadonlySignal = { - value: undefined, - peek: () => undefined, - subscribe: () => () => {}, -}; - -const EMPTY_CLIENT_SIGNAL: ReadonlySignal = { - value: undefined, - peek: () => undefined, - subscribe: () => () => {}, -}; - -type ResponseCase = Extract< - Protobuf.Admin.AdminMessage["payloadVariant"]["case"], - "getCannedMessageModuleMessagesResponse" | "getRingtoneResponse" ->; - -interface Source { - signal: (client: MeshClient) => ReadonlySignal; - request: (client: MeshClient) => Promise>; - responseCase: ResponseCase; -} - -/** The nearest MeshProvider client, else the registry's active one, if any. */ -function useOptionalClient(): MeshClient | undefined { - const direct = useContext(MeshContext); - const registry = useOptionalMeshRegistry(); - const active = useSignal(registry?.active ?? EMPTY_CLIENT_SIGNAL); - return direct ?? active; -} - -function useModuleMessages(source: Source): UseModuleMessagesResult { - const client = useOptionalClient(); - const value = useSignal(client ? source.signal(client) : EMPTY_STRING_SIGNAL); - // Loading from the first render, since the request goes out on mount. - const [isLoading, setIsLoading] = useState(client !== undefined); - const [error, setError] = useState(undefined); - const timer = useRef | undefined>(undefined); - const sourceRef = useRef(source); - - const stopWaiting = useCallback(() => { - clearTimeout(timer.current); - timer.current = undefined; - setIsLoading(false); - }, []); - - // The answer may repeat the cached value, so wait on the packet rather - // than on the signal changing. - useEffect(() => { - if (!client) return; - return client.events.onAdminPacket.subscribe((packet) => { - if (packet.from !== client.myNodeNum) return; - if (packet.data.payloadVariant.case !== sourceRef.current.responseCase) { - return; - } - setError(undefined); - stopWaiting(); - }); - }, [client, stopWaiting]); - - const refresh = useCallback(() => { - if (!client) return; - clearTimeout(timer.current); - setIsLoading(true); - setError(undefined); - timer.current = setTimeout(() => { - timer.current = undefined; - setIsLoading(false); - setError(new Error("The device did not answer")); - }, MODULE_MESSAGES_TIMEOUT_MS); - sourceRef.current.request(client).then((result) => { - if (Result.isError(result)) { - setError(result.error); - stopWaiting(); - } - }); - }, [client, stopWaiting]); - - useEffect(() => { - refresh(); - return () => clearTimeout(timer.current); - }, [refresh]); - - return { value, isLoading, error, refresh }; -} - -const CANNED_MESSAGES: Source = { - signal: (client) => client.config.cannedMessages, - request: (client) => client.config.requestCannedMessages(), - responseCase: "getCannedMessageModuleMessagesResponse", -}; - -const RINGTONE: Source = { - signal: (client) => client.config.ringtone, - request: (client) => client.config.requestRingtone(), - responseCase: "getRingtoneResponse", -}; - -/** - * The connected device's `|`-separated canned message list. Asks the device - * for it on mount. Returns an undefined value when no client is active. - */ -export function useCannedMessages(): UseModuleMessagesResult { - return useModuleMessages(CANNED_MESSAGES); -} - -/** - * The connected device's External Notification ringtone (RTTTL). Asks the - * device for it on mount. Returns an undefined value when no client is active. - */ -export function useRingtone(): UseModuleMessagesResult { - return useModuleMessages(RINGTONE); -} diff --git a/packages/sdk-react/src/hooks/useNode.ts b/packages/sdk-react/src/hooks/useNode.ts deleted file mode 100644 index 0e7fe6f7b..000000000 --- a/packages/sdk-react/src/hooks/useNode.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { Node } from "@meshtastic/sdk"; -import { useClient } from "../adapters/useClient.ts"; -import { useSignalValue } from "../adapters/useSignalValue.ts"; - -export function useNode(nodeNum: number): Node | undefined { - const client = useClient(); - return useSignalValue(client.nodes.list, (list) => - list.find((n) => n.num === nodeNum), - ); -} diff --git a/packages/sdk-react/src/hooks/useNodeError.ts b/packages/sdk-react/src/hooks/useNodeError.ts deleted file mode 100644 index c9b6260f2..000000000 --- a/packages/sdk-react/src/hooks/useNodeError.ts +++ /dev/null @@ -1,28 +0,0 @@ -import type { NodeError } from "@meshtastic/sdk"; -import { useActiveClient } from "../adapters/useActiveClient.ts"; -import { useSignal } from "../adapters/useSignal.ts"; - -const EMPTY: ReadonlyArray = []; -const EMPTY_SIGNAL = { - value: EMPTY, - peek: () => EMPTY, - subscribe: () => () => {}, -}; - -/** - * Returns the current per-node error array from the active client. Empty - * when no client is active or no errors have been recorded. - */ -export function useNodeErrors(): ReadonlyArray { - const client = useActiveClient(); - return useSignal(client?.nodes.errors ?? EMPTY_SIGNAL); -} - -export function useNodeError(nodeNum: number): NodeError | undefined { - const errors = useNodeErrors(); - return errors.find((e) => e.node === nodeNum); -} - -export function useHasNodeError(nodeNum: number): boolean { - return useNodeError(nodeNum) !== undefined; -} diff --git a/packages/sdk-react/src/hooks/useNodes.ts b/packages/sdk-react/src/hooks/useNodes.ts deleted file mode 100644 index bb757895b..000000000 --- a/packages/sdk-react/src/hooks/useNodes.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { Node } from "@meshtastic/sdk"; -import { useClient } from "../adapters/useClient.ts"; -import { useSignal } from "../adapters/useSignal.ts"; - -export function useNodes(): ReadonlyArray { - const client = useClient(); - return useSignal(client.nodes.list); -} diff --git a/packages/sdk-react/src/hooks/usePosition.ts b/packages/sdk-react/src/hooks/usePosition.ts deleted file mode 100644 index b47e58082..000000000 --- a/packages/sdk-react/src/hooks/usePosition.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { Position } from "@meshtastic/sdk"; -import { useClient } from "../adapters/useClient.ts"; -import { useSignalValue } from "../adapters/useSignalValue.ts"; - -export function usePosition(nodeNum: number): Position | undefined { - const client = useClient(); - return useSignalValue(client.position.list, (list) => - list.find((p) => p.nodeNum === nodeNum), - ); -} diff --git a/packages/sdk-react/src/hooks/useTelemetry.ts b/packages/sdk-react/src/hooks/useTelemetry.ts deleted file mode 100644 index 1dba2ba09..000000000 --- a/packages/sdk-react/src/hooks/useTelemetry.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { TelemetryReading } from "@meshtastic/sdk"; -import { useMemo } from "react"; -import { useClient } from "../adapters/useClient.ts"; -import { useSignal } from "../adapters/useSignal.ts"; - -export interface UseTelemetryResult { - latest: TelemetryReading | undefined; - history: TelemetryReading[]; -} - -export function useTelemetry(nodeNum: number): UseTelemetryResult { - const client = useClient(); - const latestSig = useMemo( - () => client.telemetry.latest(nodeNum), - [client, nodeNum], - ); - const historySig = useMemo( - () => client.telemetry.history(nodeNum), - [client, nodeNum], - ); - const latest = useSignal(latestSig); - const history = useSignal(historySig); - return { latest, history }; -} diff --git a/packages/sdk-react/src/hooks/useTraceroute.ts b/packages/sdk-react/src/hooks/useTraceroute.ts deleted file mode 100644 index 85776eca4..000000000 --- a/packages/sdk-react/src/hooks/useTraceroute.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { TraceRoute } from "@meshtastic/sdk"; -import { useClient } from "../adapters/useClient.ts"; -import { useSignalValue } from "../adapters/useSignalValue.ts"; - -export function useTraceroute(destination: number): TraceRoute | undefined { - const client = useClient(); - return useSignalValue(client.traceroute.list, (list) => - list.find((t) => t.destination === destination), - ); -} diff --git a/packages/sdk-react/src/hooks/useUnread.ts b/packages/sdk-react/src/hooks/useUnread.ts deleted file mode 100644 index b0fede6a2..000000000 --- a/packages/sdk-react/src/hooks/useUnread.ts +++ /dev/null @@ -1,41 +0,0 @@ -import type { ConversationKey } from "@meshtastic/sdk"; -import { useActiveClient } from "../adapters/useActiveClient.ts"; -import { useSignal } from "../adapters/useSignal.ts"; - -const EMPTY_NUMBER_SIGNAL = { - value: 0, - peek: () => 0, - subscribe: () => () => {}, -} as const; - -const EMPTY_MAP_SIGNAL = { - value: new Map() as ReadonlyMap, - peek: () => new Map() as ReadonlyMap, - subscribe: () => () => {}, -} as const; - -/** - * Total unread count across every conversation on the active client. - * Returns 0 when no client is active. - */ -export function useTotalUnread(): number { - const client = useActiveClient(); - return useSignal(client?.chat.unread.total ?? EMPTY_NUMBER_SIGNAL); -} - -/** - * Unread count for a single conversation. Returns 0 when no client is active. - */ -export function useUnreadCount(key: ConversationKey): number { - const client = useActiveClient(); - return useSignal(client?.chat.unread.count(key) ?? EMPTY_NUMBER_SIGNAL); -} - -/** - * Whole unread map (``). Useful for sidebar - * badges that walk every saved conversation. - */ -export function useUnreadByKey(): ReadonlyMap { - const client = useActiveClient(); - return useSignal(client?.chat.unread.byKey ?? EMPTY_MAP_SIGNAL); -} diff --git a/packages/sdk-react/src/provider/MeshContext.ts b/packages/sdk-react/src/provider/MeshContext.ts deleted file mode 100644 index 9a34a9206..000000000 --- a/packages/sdk-react/src/provider/MeshContext.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { MeshClient } from "@meshtastic/sdk"; -import { createContext } from "react"; - -export const MeshContext = createContext(undefined); diff --git a/packages/sdk-react/src/provider/MeshProvider.tsx b/packages/sdk-react/src/provider/MeshProvider.tsx deleted file mode 100644 index 6533aaad0..000000000 --- a/packages/sdk-react/src/provider/MeshProvider.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import type { MeshClient } from "@meshtastic/sdk"; -import type { ReactNode } from "react"; -import { MeshContext } from "./MeshContext.ts"; - -export interface MeshProviderProps { - client: MeshClient; - children: ReactNode; -} - -export function MeshProvider({ client, children }: MeshProviderProps) { - return {children}; -} diff --git a/packages/sdk-react/src/provider/MeshRegistryContext.ts b/packages/sdk-react/src/provider/MeshRegistryContext.ts deleted file mode 100644 index 54cfecb6b..000000000 --- a/packages/sdk-react/src/provider/MeshRegistryContext.ts +++ /dev/null @@ -1,6 +0,0 @@ -import type { MeshRegistry } from "@meshtastic/sdk"; -import { createContext } from "react"; - -export const MeshRegistryContext = createContext( - undefined, -); diff --git a/packages/sdk-react/src/provider/MeshRegistryProvider.tsx b/packages/sdk-react/src/provider/MeshRegistryProvider.tsx deleted file mode 100644 index 3cbe62bfe..000000000 --- a/packages/sdk-react/src/provider/MeshRegistryProvider.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import type { MeshRegistry } from "@meshtastic/sdk"; -import type { ReactNode } from "react"; -import { MeshRegistryContext } from "./MeshRegistryContext.ts"; - -export interface MeshRegistryProviderProps { - registry: MeshRegistry; - children: ReactNode; -} - -/** - * Makes a MeshRegistry available to descendant hooks. Use when the app holds - * more than one connected device at a time. For single-client apps, prefer - * ``. - */ -export function MeshRegistryProvider({ - registry, - children, -}: MeshRegistryProviderProps) { - return ( - - {children} - - ); -} diff --git a/packages/sdk-react/tests/hooks.registry.test.tsx b/packages/sdk-react/tests/hooks.registry.test.tsx deleted file mode 100644 index 1a94091bf..000000000 --- a/packages/sdk-react/tests/hooks.registry.test.tsx +++ /dev/null @@ -1,134 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { ChannelNumber, MeshRegistry } from "@meshtastic/sdk"; -import { createFakeTransport } from "@meshtastic/sdk/testing"; -import { act, renderHook, waitFor } from "@testing-library/react"; -import { describe, expect, it } from "vitest"; -import { - MeshRegistryProvider, - useChannels, - useMeshDevice, - useNode, - useNodes, -} from "../mod.ts"; - -function makeRegistry(deviceCount: number) { - const registry = new MeshRegistry(); - const handles: ReturnType[] = []; - for (let i = 0; i < deviceCount; i++) { - const handle = createFakeTransport(); - handles.push(handle); - registry.create(i + 1, { transport: handle.transport }); - } - return { registry, handles }; -} - -describe("sdk-react under MeshRegistryProvider", () => { - it("useMeshDevice resolves through the registry's active client", async () => { - const { registry, handles } = makeRegistry(1); - const wrapper = ({ children }: { children: React.ReactNode }) => ( - - {children} - - ); - const { result } = renderHook(() => useMeshDevice(), { wrapper }); - expect(result.current.myNodeNum).toBeUndefined(); - - await act(async () => { - handles[0]!.respond.withMyNodeInfo({ myNodeNum: 555 }); - await new Promise((r) => setTimeout(r, 10)); - }); - await waitFor(() => expect(result.current.myNodeNum).toBe(555)); - }); - - it("useNodes lists nodes from the active client and updates on packets", async () => { - const { registry, handles } = makeRegistry(1); - const wrapper = ({ children }: { children: React.ReactNode }) => ( - - {children} - - ); - const { result } = renderHook(() => useNodes(), { wrapper }); - expect(result.current).toEqual([]); - - await act(async () => { - handles[0]!.respond.withNodeInfo({ num: 7 }); - await new Promise((r) => setTimeout(r, 10)); - }); - await waitFor(() => { - expect(result.current.map((n) => n.num)).toEqual([7]); - }); - }); - - it("useNode selects by node number and re-renders on update", async () => { - const { registry, handles } = makeRegistry(1); - const wrapper = ({ children }: { children: React.ReactNode }) => ( - - {children} - - ); - const { result } = renderHook(() => useNode(11), { wrapper }); - expect(result.current).toBeUndefined(); - - await act(async () => { - handles[0]!.respond.withNodeInfo({ num: 11, isFavorite: true }); - await new Promise((r) => setTimeout(r, 10)); - }); - await waitFor(() => { - expect(result.current?.isFavorite).toBe(true); - }); - }); - - it("useChannels reflects channel packets dispatched on the active client", async () => { - const { registry } = makeRegistry(1); - const client = registry.active.value; - if (!client) throw new Error("expected an active client"); - - const wrapper = ({ children }: { children: React.ReactNode }) => ( - - {children} - - ); - const { result } = renderHook(() => useChannels(), { wrapper }); - expect(result.current).toEqual([]); - - await act(async () => { - client.events.onChannelPacket.dispatch( - create(Protobuf.Channel.ChannelSchema, { - index: 0, - role: Protobuf.Channel.Channel_Role.PRIMARY, - }), - ); - }); - await waitFor(() => { - expect(result.current.length).toBe(1); - }); - }); - - it("switches active client and re-renders against the new device", async () => { - const { registry, handles } = makeRegistry(2); - - const wrapper = ({ children }: { children: React.ReactNode }) => ( - - {children} - - ); - const { result } = renderHook(() => useMeshDevice(), { wrapper }); - - await act(async () => { - handles[0]!.respond.withMyNodeInfo({ myNodeNum: 1 }); - handles[1]!.respond.withMyNodeInfo({ myNodeNum: 2 }); - await new Promise((r) => setTimeout(r, 10)); - }); - await waitFor(() => expect(result.current.myNodeNum).toBe(1)); - - await act(async () => { - registry.setActive(2); - }); - await waitFor(() => expect(result.current.myNodeNum).toBe(2)); - }); - - it("ChannelNumber enum exported as a value", () => { - expect(ChannelNumber.Primary).toBe(0); - }); -}); diff --git a/packages/sdk-react/tests/hooks.test.tsx b/packages/sdk-react/tests/hooks.test.tsx deleted file mode 100644 index dc82d11f2..000000000 --- a/packages/sdk-react/tests/hooks.test.tsx +++ /dev/null @@ -1,44 +0,0 @@ -import { act, render, renderHook, waitFor } from "@testing-library/react"; -import { MeshClient } from "@meshtastic/sdk"; -import { createFakeTransport } from "@meshtastic/sdk/testing"; -import { ChannelNumber } from "@meshtastic/sdk"; -import { describe, expect, it } from "vitest"; -import { MeshProvider, useChat, useMeshDevice } from "../mod.ts"; - -function setup() { - const handle = createFakeTransport(); - const client = new MeshClient({ transport: handle.transport }); - const wrapper = ({ children }: { children: React.ReactNode }) => ( - {children} - ); - return { client, handle, wrapper }; -} - -describe("sdk-react hooks", () => { - it("useMeshDevice re-renders on myNodeInfo", async () => { - const { handle, wrapper } = setup(); - const { result } = renderHook(() => useMeshDevice(), { wrapper }); - expect(result.current.myNodeNum).toBeUndefined(); - - await act(async () => { - handle.respond.withMyNodeInfo({ myNodeNum: 99 }); - await new Promise((r) => setTimeout(r, 10)); - }); - - await waitFor(() => { - expect(result.current.myNodeNum).toBe(99); - }); - }); - - it("useChat surfaces inbound messages", async () => { - const { handle, wrapper } = setup(); - const { result } = renderHook(() => useChat(ChannelNumber.Primary), { - wrapper, - }); - expect(result.current.messages).toEqual([]); - // Exhaustive integration coverage is in packages/sdk; this test ensures - // the hook wiring re-renders on a signal change. - void handle; - void render; - }); -}); diff --git a/packages/sdk-react/tests/useModuleMessages.test.tsx b/packages/sdk-react/tests/useModuleMessages.test.tsx deleted file mode 100644 index 267da7710..000000000 --- a/packages/sdk-react/tests/useModuleMessages.test.tsx +++ /dev/null @@ -1,88 +0,0 @@ -import { act, renderHook, waitFor } from "@testing-library/react"; -import { MeshClient, Protobuf } from "@meshtastic/sdk"; -import { createFakeTransport } from "@meshtastic/sdk/testing"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import { MeshProvider, useCannedMessages, useRingtone } from "../mod.ts"; -import { MODULE_MESSAGES_TIMEOUT_MS } from "../src/hooks/useModuleMessages.ts"; - -function setup() { - const handle = createFakeTransport(); - const client = new MeshClient({ transport: handle.transport }); - const sendPacket = vi.spyOn(client, "sendPacket").mockResolvedValue(1); - const wrapper = ({ children }: { children: React.ReactNode }) => ( - {children} - ); - return { client, sendPacket, wrapper }; -} - -function answer( - client: MeshClient, - payloadVariant: Protobuf.Admin.AdminMessage["payloadVariant"], -) { - client.events.onAdminPacket.dispatch({ - id: 2, - rxTime: new Date(), - type: "direct", - from: client.myNodeNum, - to: client.myNodeNum, - channel: 0, - // Only the fields the SDK reads; avoids a protobuf runtime dependency. - data: { - payloadVariant, - sessionPasskey: new Uint8Array(), - } as unknown as Protobuf.Admin.AdminMessage, - }); -} - -describe("useCannedMessages / useRingtone", () => { - afterEach(() => vi.useRealTimers()); - - it("asks the device on mount and shows its answer", async () => { - const { client, sendPacket, wrapper } = setup(); - const { result } = renderHook(() => useCannedMessages(), { wrapper }); - - expect(result.current.isLoading).toBe(true); - expect(result.current.value).toBeUndefined(); - expect(sendPacket).toHaveBeenCalledTimes(1); - - act(() => - answer(client, { - case: "getCannedMessageModuleMessagesResponse", - value: "Yes|No", - }), - ); - await waitFor(() => expect(result.current.value).toBe("Yes|No")); - expect(result.current.isLoading).toBe(false); - expect(result.current.error).toBeUndefined(); - }); - - it("stops loading when the answer repeats the cached value", async () => { - const { client, wrapper } = setup(); - answer(client, { case: "getRingtoneResponse", value: "tone" }); - const { result } = renderHook(() => useRingtone(), { wrapper }); - expect(result.current.value).toBe("tone"); - expect(result.current.isLoading).toBe(true); - - act(() => answer(client, { case: "getRingtoneResponse", value: "tone" })); - await waitFor(() => expect(result.current.isLoading).toBe(false)); - }); - - it("reports an error when the device doesn't answer", async () => { - vi.useFakeTimers(); - const { wrapper } = setup(); - const { result } = renderHook(() => useRingtone(), { wrapper }); - await act(async () => { - await vi.advanceTimersByTimeAsync(MODULE_MESSAGES_TIMEOUT_MS); - }); - expect(result.current.isLoading).toBe(false); - expect(result.current.error).toBeInstanceOf(Error); - }); - - it("reports an error when the request can't be sent", async () => { - const { sendPacket, wrapper } = setup(); - sendPacket.mockRejectedValue(new Error("offline")); - const { result } = renderHook(() => useRingtone(), { wrapper }); - await waitFor(() => expect(result.current.error?.message).toBe("offline")); - expect(result.current.isLoading).toBe(false); - }); -}); diff --git a/packages/sdk-react/tsconfig.json b/packages/sdk-react/tsconfig.json deleted file mode 100644 index b01917932..000000000 --- a/packages/sdk-react/tsconfig.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "include": ["mod.ts", "src"] -} diff --git a/packages/sdk-react/vitest.config.ts b/packages/sdk-react/vitest.config.ts deleted file mode 100644 index e68d6320a..000000000 --- a/packages/sdk-react/vitest.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { defineProject } from "vitest/config"; - -export default defineProject({ - test: { - name: "@meshtastic/sdk-react", - environment: "jsdom", - include: [ - "src/**/*.test.ts", - "src/**/*.test.tsx", - "tests/**/*.test.ts", - "tests/**/*.test.tsx", - ], - }, -}); diff --git a/packages/sdk-storage-sqlocal/README.md b/packages/sdk-storage-sqlocal/README.md deleted file mode 100644 index 5154a633c..000000000 --- a/packages/sdk-storage-sqlocal/README.md +++ /dev/null @@ -1,62 +0,0 @@ -# @meshtastic/sdk-storage-sqlocal - -SQLite WASM persistence adapters for `@meshtastic/sdk`. Implements the SDK's per-slice repository ports (`MessageRepository`, future `NodesRepository`, `TelemetryRepository`) against a single OPFS-backed SQLite database. - -Drizzle ORM provides typed queries; sqlocal handles the WASM runtime and OPFS-backed storage. Multi-tab coordination uses the Web Locks API for write exclusion and BroadcastChannel for cross-tab change notifications. - -## Install - -```sh -pnpm add @meshtastic/sdk @meshtastic/sdk-storage-sqlocal -``` - -## Headers - -OPFS in browsers requires cross-origin isolation. Serve your app with: - -``` -Cross-Origin-Opener-Policy: same-origin -Cross-Origin-Embedder-Policy: require-corp -``` - -## Quickstart - -```ts -import { MeshClient, MeshRegistry } from "@meshtastic/sdk"; -import { createSqlocalDb } from "@meshtastic/sdk-storage-sqlocal"; -import { SqlocalMessageRepository } from "@meshtastic/sdk-storage-sqlocal/chat"; - -const db = await createSqlocalDb({ databasePath: "meshtastic.db" }); - -const registry = new MeshRegistry(); -// Scope the history to the radio's node number. Pass the one saved from an -// earlier connection, or any unused value (e.g. -1) when it isn't known yet: -// with `storageScope: "node"` the client calls `setScope(myNodeNum)` on every -// repository as soon as the handshake's my_info names the radio, and reloads. -registry.create(connectionId, { - transport, - storageScope: "node", - storageNodeNum: savedNodeNum, - chat: { - repository: new SqlocalMessageRepository(db, { - deviceId: savedNodeNum ?? -1, - }), - retention: { maxPerBucket: 1000, olderThanMs: 90 * 24 * 60 * 60 * 1000 }, - }, -}); -``` - -## Schema - -Single database per origin. Every table has a `device_id` column so a multi-device `MeshRegistry` can share one DB safely. It holds whatever scope the repository was opened with or last given through `setScope` (the web app uses the radio's node number, so every connection to one radio shares its history). - -| Table | Purpose | -| --- | --- | -| `messages` | Chat (text + waypoints) | -| `nodes` | Node DB snapshot per device | -| `telemetry` | Per-node ring buffer of telemetry readings | -| `_schema` | Migration version | - -## License - -GPL-3.0-only. diff --git a/packages/sdk-storage-sqlocal/mod.ts b/packages/sdk-storage-sqlocal/mod.ts deleted file mode 100644 index 4ec5d860b..000000000 --- a/packages/sdk-storage-sqlocal/mod.ts +++ /dev/null @@ -1,16 +0,0 @@ -export { createSqlocalDb, openSqlocalDb } from "./src/db.ts"; -export type { - CreateSqlocalDbOptions, - OpenedSqlocalDb, - SqlocalDb, -} from "./src/db.ts"; -export { MultiTabCoordinator } from "./src/coordination/index.ts"; -export type { ChangeEvent, ChangeKind } from "./src/coordination/index.ts"; -export { SqlocalMessageRepository } from "./src/chat/index.ts"; -export type { SqlocalMessageRepositoryOptions } from "./src/chat/index.ts"; -export { SqlocalDraftRepository } from "./src/chat/index.ts"; -export type { SqlocalDraftRepositoryOptions } from "./src/chat/index.ts"; -export { SqlocalNodesRepository } from "./src/nodes/index.ts"; -export type { SqlocalNodesRepositoryOptions } from "./src/nodes/index.ts"; -export { SqlocalTelemetryRepository } from "./src/telemetry/index.ts"; -export type { SqlocalTelemetryRepositoryOptions } from "./src/telemetry/index.ts"; diff --git a/packages/sdk-storage-sqlocal/package.json b/packages/sdk-storage-sqlocal/package.json deleted file mode 100644 index e34125927..000000000 --- a/packages/sdk-storage-sqlocal/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "name": "@meshtastic/sdk-storage-sqlocal", - "version": "1.0.0", - "description": "SQLite WASM (sqlocal + OPFS) persistence adapters for @meshtastic/sdk repository ports. Drizzle-typed queries, Web Lock + BroadcastChannel multi-tab coordination.", - "license": "GPL-3.0-only", - "repository": { - "type": "git", - "url": "git+https://github.com/meshtastic/web.git", - "directory": "packages/sdk-storage-sqlocal" - }, - "files": [ - "package.json", - "README.md", - "LICENSE", - "dist" - ], - "type": "module", - "main": "./dist/mod.js", - "module": "./dist/mod.js", - "types": "./dist/mod.d.ts", - "exports": { - ".": "./mod.ts", - "./chat": "./src/chat/index.ts", - "./nodes": "./src/nodes/index.ts", - "./telemetry": "./src/telemetry/index.ts", - "./schema": "./src/schema/index.ts", - "./testing": "./src/testing/index.ts" - }, - "scripts": { - "preinstall": "npx only-allow pnpm", - "prepack": "cp ../../LICENSE ./LICENSE", - "clean": "rm -rf dist LICENSE", - "build:npm": "tsdown", - "publish:npm": "pnpm clean && pnpm build:npm && pnpm publish --access public --no-git-checks", - "test": "vitest run", - "test:browser": "vitest run --config vitest.browser.config.ts" - }, - "dependencies": { - "@meshtastic/sdk": "workspace:*", - "drizzle-orm": "^0.45.4", - "sqlocal": "^0.18.0" - }, - "devDependencies": { - "@types/sql.js": "^1.4.11", - "sql.js": "^1.15.0" - }, - "tsdown": { - "clean": true, - "dts": false, - "entry": { - "chat": "src/chat/index.ts", - "mod": "mod.ts", - "schema": "src/schema/index.ts", - "testing": "src/testing/index.ts" - }, - "format": [ - "esm" - ], - "platform": "browser", - "splitting": false - } -} diff --git a/packages/sdk-storage-sqlocal/src/chat/SqlocalDraftRepository.test.ts b/packages/sdk-storage-sqlocal/src/chat/SqlocalDraftRepository.test.ts deleted file mode 100644 index 28e2ddfb3..000000000 --- a/packages/sdk-storage-sqlocal/src/chat/SqlocalDraftRepository.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { ChannelNumber } from "@meshtastic/sdk"; -import { beforeEach, describe, expect, it } from "vitest"; -import type { SqlocalDb } from "../db.ts"; -import { createMemoryDb } from "../testing/createMemoryDb.ts"; -import { SqlocalDraftRepository } from "./SqlocalDraftRepository.ts"; - -describe("SqlocalDraftRepository", () => { - let db: SqlocalDb; - let repo: SqlocalDraftRepository; - - beforeEach(async () => { - db = await createMemoryDb(); - repo = new SqlocalDraftRepository(db, { deviceId: 1 }); - }); - - it("save then load returns the same text", async () => { - await repo.save( - { kind: "channel", channel: ChannelNumber.Primary }, - "hello", - ); - expect( - await repo.load({ kind: "channel", channel: ChannelNumber.Primary }), - ).toBe("hello"); - }); - - it("save with empty text deletes the row", async () => { - await repo.save({ kind: "direct", peer: 7 }, "wip"); - await repo.save({ kind: "direct", peer: 7 }, ""); - expect(await repo.load({ kind: "direct", peer: 7 })).toBe(""); - }); - - it("clear removes the row", async () => { - await repo.save( - { kind: "channel", channel: ChannelNumber.Channel1 }, - "draft", - ); - await repo.clear({ kind: "channel", channel: ChannelNumber.Channel1 }); - expect( - await repo.load({ kind: "channel", channel: ChannelNumber.Channel1 }), - ).toBe(""); - }); - - it("upsert overwrites prior text without throwing", async () => { - await repo.save({ kind: "direct", peer: 12 }, "first"); - await repo.save({ kind: "direct", peer: 12 }, "second"); - expect(await repo.load({ kind: "direct", peer: 12 })).toBe("second"); - }); - - it("scoped per device_id", async () => { - const repoB = new SqlocalDraftRepository(db, { deviceId: 2 }); - await repo.save( - { kind: "channel", channel: ChannelNumber.Primary }, - "from-1", - ); - await repoB.save( - { kind: "channel", channel: ChannelNumber.Primary }, - "from-2", - ); - expect( - await repo.load({ kind: "channel", channel: ChannelNumber.Primary }), - ).toBe("from-1"); - expect( - await repoB.load({ kind: "channel", channel: ChannelNumber.Primary }), - ).toBe("from-2"); - }); - - it("loadAll returns all drafts for the device", async () => { - await repo.save({ kind: "channel", channel: ChannelNumber.Primary }, "a"); - await repo.save({ kind: "direct", peer: 99 }, "b"); - const all = await repo.loadAll(); - expect(all.length).toBe(2); - }); - - it("setScope moves reads and writes to the new scope", async () => { - const channel = { - kind: "channel", - channel: ChannelNumber.Primary, - } as const; - await repo.save(channel, "old"); - - repo.setScope(0xabcd); - expect(await repo.load(channel)).toBe(""); - expect(await repo.loadAll()).toEqual([]); - await repo.save(channel, "new"); - await repo.save({ kind: "direct", peer: 7 }, "dm"); - await repo.clear({ kind: "direct", peer: 7 }); - expect(await repo.loadAll()).toEqual([{ key: channel, text: "new" }]); - - const old = new SqlocalDraftRepository(db, { deviceId: 1 }); - expect(await old.load(channel)).toBe("old"); - }); -}); diff --git a/packages/sdk-storage-sqlocal/src/chat/SqlocalDraftRepository.ts b/packages/sdk-storage-sqlocal/src/chat/SqlocalDraftRepository.ts deleted file mode 100644 index ede753a61..000000000 --- a/packages/sdk-storage-sqlocal/src/chat/SqlocalDraftRepository.ts +++ /dev/null @@ -1,88 +0,0 @@ -import type { ConversationKey, DraftRepository } from "@meshtastic/sdk"; -import { conversationKeyString, parseConversationKey } from "@meshtastic/sdk"; -import { and, eq, sql } from "drizzle-orm"; -import type { SqlocalDb } from "../db.ts"; -import { drafts } from "../schema/drafts.ts"; - -export interface SqlocalDraftRepositoryOptions { - deviceId: number; -} - -/** - * Per-conversation draft persistence. Single row per (device_id, - * conversation_key); upsert on save, delete on clear or empty save. - */ -export class SqlocalDraftRepository implements DraftRepository { - private readonly db: SqlocalDb; - private deviceId: number; - - constructor(db: SqlocalDb, options: SqlocalDraftRepositoryOptions) { - this.db = db; - this.deviceId = options.deviceId; - } - - /** - * Points every later read and write at another `device_id`. Rows under the - * old one are left as they are. - */ - setScope(deviceId: number): void { - this.deviceId = deviceId; - } - - async load(key: ConversationKey): Promise { - const rows = await this.db - .select({ text: drafts.text }) - .from(drafts) - .where( - and( - eq(drafts.deviceId, this.deviceId), - eq(drafts.conversationKey, conversationKeyString(key)), - )!, - ) - .limit(1); - return rows[0]?.text ?? ""; - } - - async save(key: ConversationKey, text: string): Promise { - if (text.length === 0) { - await this.clear(key); - return; - } - await this.db - .insert(drafts) - .values({ - deviceId: this.deviceId, - conversationKey: conversationKeyString(key), - text, - updatedAt: Date.now(), - }) - .onConflictDoUpdate({ - target: [drafts.deviceId, drafts.conversationKey], - set: { text: sql`excluded.text`, updatedAt: sql`excluded.updated_at` }, - }); - } - - async clear(key: ConversationKey): Promise { - await this.db - .delete(drafts) - .where( - and( - eq(drafts.deviceId, this.deviceId), - eq(drafts.conversationKey, conversationKeyString(key)), - )!, - ); - } - - async loadAll(): Promise< - ReadonlyArray<{ key: ConversationKey; text: string }> - > { - const rows = await this.db - .select({ conversationKey: drafts.conversationKey, text: drafts.text }) - .from(drafts) - .where(eq(drafts.deviceId, this.deviceId)); - return rows.map((r) => ({ - key: parseConversationKey(r.conversationKey), - text: r.text, - })); - } -} diff --git a/packages/sdk-storage-sqlocal/src/chat/SqlocalMessageRepository.test.ts b/packages/sdk-storage-sqlocal/src/chat/SqlocalMessageRepository.test.ts deleted file mode 100644 index d1ee407a5..000000000 --- a/packages/sdk-storage-sqlocal/src/chat/SqlocalMessageRepository.test.ts +++ /dev/null @@ -1,215 +0,0 @@ -import { ChannelNumber, type Message, MessageState } from "@meshtastic/sdk"; -import { beforeEach, describe, expect, it, vi } from "vitest"; -import { MultiTabCoordinator } from "../coordination/MultiTabCoordinator.ts"; -import type { SqlocalDb } from "../db.ts"; -import { createMemoryDb } from "../testing/createMemoryDb.ts"; -import { SqlocalMessageRepository } from "./SqlocalMessageRepository.ts"; - -function msg(id: number, ms: number, text = "t"): Message { - return { - id, - from: 1, - to: 0xffffffff, - channel: ChannelNumber.Primary, - rxTime: new Date(ms), - type: "broadcast", - text, - state: MessageState.Ack, - }; -} - -describe("SqlocalMessageRepository (sql.js test driver)", () => { - let db: SqlocalDb; - let repo: SqlocalMessageRepository; - - beforeEach(async () => { - db = await createMemoryDb(); - repo = new SqlocalMessageRepository(db, { deviceId: 1 }); - }); - - it("loadRecent returns the tail in chronological order", async () => { - await repo.appendBatch([msg(1, 1000), msg(2, 2000), msg(3, 3000)]); - const out = await repo.loadRecent( - { kind: "channel", channel: ChannelNumber.Primary }, - 2, - ); - expect(out.map((m) => m.id)).toEqual([2, 3]); - }); - - it("loadBefore paginates older messages", async () => { - await repo.appendBatch([ - msg(1, 1000), - msg(2, 2000), - msg(3, 3000), - msg(4, 4000), - ]); - const out = await repo.loadBefore( - { kind: "channel", channel: ChannelNumber.Primary }, - new Date(3000), - 10, - ); - expect(out.map((m) => m.id)).toEqual([1, 2]); - }); - - it("round-trips how a message was received, keeping 0 readings", async () => { - await repo.append({ - ...msg(7, 1000), - snr: 0, - rssi: -97, - hopsAway: 0, - viaMqtt: true, - transport: 0, - }); - await repo.append(msg(8, 2000)); - const [withRadio, without] = await repo.loadRecent( - { kind: "channel", channel: ChannelNumber.Primary }, - 2, - ); - expect(withRadio).toMatchObject({ - snr: 0, - rssi: -97, - hopsAway: 0, - viaMqtt: true, - transport: 0, - }); - expect(without?.snr).toBeUndefined(); - expect(without?.rssi).toBeUndefined(); - expect(without?.hopsAway).toBeUndefined(); - expect(without?.viaMqtt).toBeUndefined(); - expect(without?.transport).toBeUndefined(); - }); - - it("files a message under the conversation it is given", async () => { - const sent: Message = { - ...msg(5, 1000, "hi"), - from: 1, - to: 2, - type: "direct", - }; - await repo.append(sent, { kind: "direct", peer: 2 }); - expect( - (await repo.loadRecent({ kind: "direct", peer: 2 }, 10)).map((m) => m.id), - ).toEqual([5]); - expect(await repo.loadRecent({ kind: "direct", peer: 1 }, 10)).toEqual([]); - }); - - it("refiles sent direct messages filed under our own node", async () => { - const direct = (id: number, from: number, to: number): Message => ({ - ...msg(id, id * 1000), - from, - to, - type: "direct", - }); - // What older versions wrote: everything under direct:. - await repo.appendBatch([ - direct(1, 1, 2), // sent by us (node 1) to 2: misfiled - direct(2, 2, 1), // received from 2: already right - direct(3, 1, 1), // a note to ourselves: stays put - ]); - - expect(await repo.refileSentDirect(1)).toBe(1); - expect( - (await repo.loadRecent({ kind: "direct", peer: 2 }, 10)).map((m) => m.id), - ).toEqual([1, 2]); - expect( - (await repo.loadRecent({ kind: "direct", peer: 1 }, 10)).map((m) => m.id), - ).toEqual([3]); - expect(await repo.refileSentDirect(1)).toBe(0); - }); - - it("updateState mutates the matching row", async () => { - await repo.append(msg(42, 1000)); - await repo.updateState(42, MessageState.Failed); - const [found] = await repo.loadRecent( - { kind: "channel", channel: ChannelNumber.Primary }, - 1, - ); - expect(found?.state).toBe(MessageState.Failed); - }); - - it("prune enforces maxPerBucket", async () => { - await repo.appendBatch([ - msg(1, 1000), - msg(2, 2000), - msg(3, 3000), - msg(4, 4000), - ]); - await repo.prune({ maxPerBucket: 2 }); - const out = await repo.loadRecent( - { kind: "channel", channel: ChannelNumber.Primary }, - 10, - ); - expect(out.map((m) => m.id)).toEqual([3, 4]); - }); - - it("prune enforces olderThanMs", async () => { - const now = Date.now(); - await repo.appendBatch([ - msg(1, now - 1000 * 60 * 60 * 24 * 10), - msg(2, now), - ]); - await repo.prune({ olderThanMs: 1000 * 60 * 60 * 24 }); - const out = await repo.loadRecent( - { kind: "channel", channel: ChannelNumber.Primary }, - 10, - ); - expect(out.map((m) => m.id)).toEqual([2]); - }); - - it("isolates devices via device_id scoping", async () => { - const repoB = new SqlocalMessageRepository(db, { deviceId: 2 }); - await repo.append(msg(1, 1000, "from-1")); - await repoB.append(msg(2, 2000, "from-2")); - const a = await repo.loadRecent( - { kind: "channel", channel: ChannelNumber.Primary }, - 10, - ); - const b = await repoB.loadRecent( - { kind: "channel", channel: ChannelNumber.Primary }, - 10, - ); - expect(a.map((m) => m.text)).toEqual(["from-1"]); - expect(b.map((m) => m.text)).toEqual(["from-2"]); - }); - - it("setScope moves reads, writes and pruning to the new scope", async () => { - const channel = { - kind: "channel", - channel: ChannelNumber.Primary, - } as const; - await repo.appendBatch([msg(1, 1000, "old"), msg(2, 2000, "old")]); - - repo.setScope(0xabcd); - expect(await repo.loadRecent(channel, 10)).toEqual([]); - await repo.append(msg(3, 3000, "new"), channel); - await repo.append(msg(4, 4000, "new"), channel); - await repo.prune({ maxPerBucket: 1 }); - await repo.updateState(1, MessageState.Failed); - expect( - (await repo.loadRecent(channel, 10)).map((m) => [m.id, m.text]), - ).toEqual([[4, "new"]]); - - const old = new SqlocalMessageRepository(db, { deviceId: 1 }); - const untouched = await old.loadRecent(channel, 10); - expect(untouched.map((m) => m.id)).toEqual([1, 2]); - expect(untouched.map((m) => m.state)).toEqual([ - MessageState.Ack, - MessageState.Ack, - ]); - }); - - it("broadcasts changes under the current scope", async () => { - const coordinator = new MultiTabCoordinator(); - const broadcast = vi.spyOn(coordinator, "broadcast"); - const scoped = new SqlocalMessageRepository(db, { - deviceId: 1, - coordinator, - }); - scoped.setScope(0xabcd); - await scoped.append(msg(5, 5000)); - expect(broadcast.mock.calls).toEqual([ - [{ kind: "messages-changed", deviceId: 0xabcd, key: "channel:0" }], - ]); - coordinator.close(); - }); -}); diff --git a/packages/sdk-storage-sqlocal/src/chat/SqlocalMessageRepository.ts b/packages/sdk-storage-sqlocal/src/chat/SqlocalMessageRepository.ts deleted file mode 100644 index 026100b3e..000000000 --- a/packages/sdk-storage-sqlocal/src/chat/SqlocalMessageRepository.ts +++ /dev/null @@ -1,273 +0,0 @@ -import type { - ConversationKey, - Message, - MessageDeliveryPatch, - MessageRepository, - Protobuf, - RetentionPolicy, -} from "@meshtastic/sdk"; -import { - conversationKeyString, - inferConversation, - MessageState, -} from "@meshtastic/sdk"; -import { and, desc, eq, lt, ne, sql } from "drizzle-orm"; -import { type MultiTabCoordinator } from "../coordination/MultiTabCoordinator.ts"; -import type { SqlocalDb } from "../db.ts"; -import { messages } from "../schema/chat.ts"; - -export interface SqlocalMessageRepositoryOptions { - /** - * The `device_id` rows are stored and read under: the storage scope, e.g. - * the radio's node number. Change it later with `setScope`. - */ - deviceId: number; - /** Optional cross-tab coordinator. If omitted, mutations are silent. */ - coordinator?: MultiTabCoordinator; -} - -export class SqlocalMessageRepository implements MessageRepository { - private readonly db: SqlocalDb; - private deviceId: number; - private readonly coordinator: MultiTabCoordinator | undefined; - - constructor(db: SqlocalDb, options: SqlocalMessageRepositoryOptions) { - this.db = db; - this.deviceId = options.deviceId; - this.coordinator = options.coordinator; - } - - /** - * Points every later read and write at another `device_id`. Rows under the - * old one are left as they are. - */ - setScope(deviceId: number): void { - this.deviceId = deviceId; - } - - async loadRecent(key: ConversationKey, limit: number): Promise { - const rows = await this.db - .select() - .from(messages) - .where(this.scoped(key)) - .orderBy(desc(messages.rxTime)) - .limit(limit); - return rows.reverse().map(rowToMessage); - } - - async loadBefore( - key: ConversationKey, - cursor: Date, - limit: number, - ): Promise { - const rows = await this.db - .select() - .from(messages) - .where(and(this.scoped(key), lt(messages.rxTime, cursor.getTime()))!) - .orderBy(desc(messages.rxTime)) - .limit(limit); - return rows.reverse().map(rowToMessage); - } - - async append(message: Message, key?: ConversationKey): Promise { - await this.insert([ - messageToRow(this.deviceId, message, key ?? inferConversation(message)), - ]); - } - - async appendBatch(input: ReadonlyArray): Promise { - await this.insert( - input.map((m) => messageToRow(this.deviceId, m, inferConversation(m))), - ); - } - - async refileSentDirect(localNodeNum: number): Promise { - const moved = await this.db - .update(messages) - .set({ conversationKey: sql`'direct:' || ${messages.toNode}` }) - .where( - and( - eq(messages.deviceId, this.deviceId), - eq(messages.type, "direct"), - eq(messages.fromNode, localNodeNum), - ne(messages.toNode, localNodeNum), - eq( - messages.conversationKey, - conversationKeyString({ kind: "direct", peer: localNodeNum }), - ), - )!, - ) - .returning({ conversationKey: messages.conversationKey }); - this.notify(moved.map((r) => r.conversationKey)); - return moved.length; - } - - private async insert(rows: MessageRow[]): Promise { - if (rows.length === 0) return; - await this.db.insert(messages).values(rows).onConflictDoNothing(); - this.notify(rows.map((r) => r.conversationKey)); - } - - async updateDelivery(id: number, patch: MessageDeliveryPatch): Promise { - const set: Partial = {}; - if ("state" in patch) set.state = patch.state; - if ("ackProof" in patch) set.ackProof = patch.ackProof ?? null; - if ("routingError" in patch) set.routingError = patch.routingError ?? null; - if ("relays" in patch) set.relays = patch.relays ?? null; - if (Object.keys(set).length === 0) return; - await this.db - .update(messages) - .set(set) - .where(and(eq(messages.deviceId, this.deviceId), eq(messages.id, id))!); - } - - async remove(id: number): Promise { - await this.db - .delete(messages) - .where(and(eq(messages.deviceId, this.deviceId), eq(messages.id, id))!); - } - - async updateState(id: number, state: MessageState): Promise { - await this.db - .update(messages) - .set({ state }) - .where(and(eq(messages.deviceId, this.deviceId), eq(messages.id, id))!); - } - - async prune(policy: RetentionPolicy): Promise { - if (policy.olderThanMs !== undefined) { - const cutoff = Date.now() - policy.olderThanMs; - await this.db - .delete(messages) - .where( - and( - eq(messages.deviceId, this.deviceId), - lt(messages.rxTime, cutoff), - )!, - ); - } - if (policy.maxPerBucket !== undefined) { - // Keep the newest N per (device, conversation_key). SQLite has no - // straightforward per-group LIMIT, so use a windowed delete. - await this.db.run(sql` - DELETE FROM messages - WHERE device_id = ${this.deviceId} - AND rowid IN ( - SELECT rowid FROM ( - SELECT rowid, - row_number() OVER ( - PARTITION BY conversation_key - ORDER BY rx_time DESC, id DESC - ) AS rn - FROM messages - WHERE device_id = ${this.deviceId} - ) - WHERE rn > ${policy.maxPerBucket} - ) - `); - } - } - - async clearConversation(key: ConversationKey): Promise { - await this.db.delete(messages).where(this.scoped(key)); - } - - async clear(): Promise { - await this.db.delete(messages).where(eq(messages.deviceId, this.deviceId)); - } - - private scoped(key: ConversationKey) { - return and( - eq(messages.deviceId, this.deviceId), - eq(messages.conversationKey, conversationKeyString(key)), - )!; - } - - private notify(keys: ReadonlyArray): void { - if (!this.coordinator) return; - for (const key of new Set(keys)) { - this.coordinator.broadcast({ - kind: "messages-changed", - deviceId: this.deviceId, - key, - }); - } - } -} - -interface MessageRow { - id: number; - deviceId: number; - conversationKey: string; - fromNode: number; - toNode: number; - channel: number; - rxTime: number; - type: "broadcast" | "direct"; - text: string; - state: "pending" | "delivered" | "ack" | "failed"; - signed?: boolean | null; - ackProof?: number | null; - routingError?: number | null; - relays?: number | null; - snr?: number | null; - rssi?: number | null; - hopsAway?: number | null; - viaMqtt?: boolean | null; - transport?: number | null; -} - -function rowToMessage(row: MessageRow): Message { - return { - id: row.id, - from: row.fromNode, - to: row.toNode, - channel: row.channel, - rxTime: new Date(row.rxTime), - type: row.type, - text: row.text, - state: row.state as MessageState, - signed: row.signed ?? undefined, - ackProof: - (row.ackProof as Protobuf.Mesh.MeshPacket_AckProofStatus | null) ?? - undefined, - routingError: - (row.routingError as Protobuf.Mesh.Routing_Error | null) ?? undefined, - relays: row.relays ?? undefined, - snr: row.snr ?? undefined, - rssi: row.rssi ?? undefined, - hopsAway: row.hopsAway ?? undefined, - viaMqtt: row.viaMqtt ?? undefined, - transport: - (row.transport as Protobuf.Mesh.MeshPacket_TransportMechanism | null) ?? - undefined, - }; -} - -function messageToRow( - deviceId: number, - message: Message, - conv: ConversationKey, -): MessageRow { - return { - id: message.id, - deviceId, - conversationKey: conversationKeyString(conv), - fromNode: message.from, - toNode: message.to, - channel: message.channel, - rxTime: message.rxTime.getTime(), - type: message.type, - text: message.text, - state: message.state, - signed: message.signed ?? null, - ackProof: message.ackProof ?? null, - routingError: message.routingError ?? null, - relays: message.relays ?? null, - snr: message.snr ?? null, - rssi: message.rssi ?? null, - hopsAway: message.hopsAway ?? null, - viaMqtt: message.viaMqtt ?? null, - transport: message.transport ?? null, - }; -} diff --git a/packages/sdk-storage-sqlocal/src/chat/index.ts b/packages/sdk-storage-sqlocal/src/chat/index.ts deleted file mode 100644 index 676403236..000000000 --- a/packages/sdk-storage-sqlocal/src/chat/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { SqlocalMessageRepository } from "./SqlocalMessageRepository.ts"; -export type { SqlocalMessageRepositoryOptions } from "./SqlocalMessageRepository.ts"; -export { SqlocalDraftRepository } from "./SqlocalDraftRepository.ts"; -export type { SqlocalDraftRepositoryOptions } from "./SqlocalDraftRepository.ts"; diff --git a/packages/sdk-storage-sqlocal/src/coordination/MultiTabCoordinator.broadcast.test.ts b/packages/sdk-storage-sqlocal/src/coordination/MultiTabCoordinator.broadcast.test.ts deleted file mode 100644 index 8478e09b4..000000000 --- a/packages/sdk-storage-sqlocal/src/coordination/MultiTabCoordinator.broadcast.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { MultiTabCoordinator } from "./MultiTabCoordinator.ts"; - -/** - * Node 19+ exposes a global BroadcastChannel that respects the WHATWG - * spec for cross-context messaging. We instantiate two coordinators in - * the same process to simulate two browser tabs. - */ -describe("MultiTabCoordinator broadcast", () => { - it("delivers events between two coordinator instances", async () => { - if (typeof BroadcastChannel === "undefined") { - console.warn("BroadcastChannel unavailable; skipping cross-tab test"); - return; - } - const a = new MultiTabCoordinator(); - const b = new MultiTabCoordinator(); - try { - const received = new Promise((resolve) => { - b.subscribe((event) => resolve(event)); - }); - a.broadcast({ kind: "messages-changed", deviceId: 1, key: "channel:0" }); - const event = await received; - expect(event).toEqual({ - kind: "messages-changed", - deviceId: 1, - key: "channel:0", - }); - } finally { - a.close(); - b.close(); - } - }); -}); diff --git a/packages/sdk-storage-sqlocal/src/coordination/MultiTabCoordinator.test.ts b/packages/sdk-storage-sqlocal/src/coordination/MultiTabCoordinator.test.ts deleted file mode 100644 index 4b182a9c7..000000000 --- a/packages/sdk-storage-sqlocal/src/coordination/MultiTabCoordinator.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; -import { MultiTabCoordinator } from "./MultiTabCoordinator.ts"; - -describe("MultiTabCoordinator", () => { - it("falls through acquireLock when navigator.locks is unavailable", async () => { - const coordinator = new MultiTabCoordinator(); - const handler = vi.fn().mockResolvedValue(42); - const result = await coordinator.acquireLock("res", handler); - expect(result).toBe(42); - expect(handler).toHaveBeenCalledTimes(1); - }); - - it("subscribe/unsubscribe gates listeners", () => { - const coordinator = new MultiTabCoordinator(); - const seen: number[] = []; - const off = coordinator.subscribe(() => seen.push(1)); - off(); - // No real BroadcastChannel here; ensure subscribe returns a callable no-op - expect(seen).toEqual([]); - }); -}); diff --git a/packages/sdk-storage-sqlocal/src/coordination/MultiTabCoordinator.ts b/packages/sdk-storage-sqlocal/src/coordination/MultiTabCoordinator.ts deleted file mode 100644 index 65792d86d..000000000 --- a/packages/sdk-storage-sqlocal/src/coordination/MultiTabCoordinator.ts +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Coordination across browser tabs of the same origin. - * - * - **Web Locks API** (`navigator.locks`): a single tab holds the writer lock - * for a given resource; others queue. Used to serialize destructive - * operations (full DB rebuilds, bulk imports) when needed. - * - **BroadcastChannel**: lock-free pub/sub for "data changed" notifications, - * so reader tabs can refresh their views without polling. - * - * sqlocal handles low-level DB write serialization via OPFS file locks; this - * layer is for app-level changes ("messages-changed for device 5, channel 0") - * so the chat slice in another tab can re-query after a write. - */ - -export type ChangeKind = - | "messages-changed" - | "nodes-changed" - | "telemetry-changed"; - -export interface ChangeEvent { - kind: ChangeKind; - deviceId: number; - /** Free-form key (e.g. conversationKey for chat). */ - key?: string; -} - -const CHANNEL_NAME = "meshtastic-storage"; - -export class MultiTabCoordinator { - private readonly channel: BroadcastChannel | undefined; - private readonly listeners = new Set<(event: ChangeEvent) => void>(); - - constructor() { - if (typeof BroadcastChannel === "undefined") { - this.channel = undefined; - return; - } - this.channel = new BroadcastChannel(CHANNEL_NAME); - this.channel.onmessage = (msg) => { - const event = msg.data as ChangeEvent; - for (const listener of this.listeners) listener(event); - }; - } - - broadcast(event: ChangeEvent): void { - this.channel?.postMessage(event); - } - - subscribe(listener: (event: ChangeEvent) => void): () => void { - this.listeners.add(listener); - return () => { - this.listeners.delete(listener); - }; - } - - /** - * Acquires an app-level Web Lock for the given resource. Resolves with a - * release function once the lock is granted. Falls through (no lock held) - * when the Web Locks API is not available. - */ - async acquireLock( - resource: string, - handler: () => Promise, - options?: { mode?: "exclusive" | "shared"; ifAvailable?: boolean }, - ): Promise { - if (typeof navigator === "undefined" || !navigator.locks) { - return handler(); - } - const result = await navigator.locks.request( - resource, - options ?? {}, - async (lock) => { - if (lock === null) return undefined; - return handler(); - }, - ); - return result as T; - } - - close(): void { - this.channel?.close(); - this.listeners.clear(); - } -} diff --git a/packages/sdk-storage-sqlocal/src/coordination/index.ts b/packages/sdk-storage-sqlocal/src/coordination/index.ts deleted file mode 100644 index d981e5dec..000000000 --- a/packages/sdk-storage-sqlocal/src/coordination/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { MultiTabCoordinator } from "./MultiTabCoordinator.ts"; -export type { ChangeEvent, ChangeKind } from "./MultiTabCoordinator.ts"; diff --git a/packages/sdk-storage-sqlocal/src/db.ts b/packages/sdk-storage-sqlocal/src/db.ts deleted file mode 100644 index 0bfb111f5..000000000 --- a/packages/sdk-storage-sqlocal/src/db.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { drizzle } from "drizzle-orm/sqlite-proxy"; -import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -import { SQLocalDrizzle } from "sqlocal/drizzle"; -import * as schema from "./schema/index.ts"; -import { MIGRATIONS } from "./schema/migrations.ts"; - -export interface CreateSqlocalDbOptions { - /** OPFS path. Defaults to "meshtastic.db". */ - databasePath?: string; -} - -export type SqlocalDb = BaseSQLiteDatabase<"async", unknown, typeof schema>; - -export interface OpenedSqlocalDb { - db: SqlocalDb; - /** - * Where the database actually lives. sqlocal falls back to "memory" without - * throwing when OPFS can't be used (no cross-origin isolation, a private - * window), and nothing written then survives a reload. - */ - storageType: string; - /** True when the database is saved to OPFS. */ - persistent: boolean; -} - -/** - * Opens (or creates) the OPFS-backed SQLite database, applies migrations, and - * returns a Drizzle client typed against the schema, along with where sqlocal - * ended up storing it. One instance per origin — sqlocal serializes writes - * via Web Locks under the hood. - */ -export async function openSqlocalDb( - options: CreateSqlocalDbOptions = {}, -): Promise { - const databasePath = options.databasePath ?? "meshtastic.db"; - const client = new SQLocalDrizzle({ databasePath }); - const { driver, batchDriver, sql } = client; - const db = drizzle(driver, batchDriver, { - schema, - casing: "snake_case", - }) as SqlocalDb; - - await applyMigrations(sql); - - const { storageType = "memory" } = await client.getDatabaseInfo(); - return { db, storageType, persistent: storageType === "opfs" }; -} - -/** {@link openSqlocalDb} for callers that only need the Drizzle client. */ -export async function createSqlocalDb( - options: CreateSqlocalDbOptions = {}, -): Promise { - return (await openSqlocalDb(options)).db; -} - -type RawSql = ( - query: TemplateStringsArray, - ...values: ReadonlyArray -) => Promise; - -export const isDuplicateColumn = (e: unknown): boolean => - /duplicate column name/i.test(e instanceof Error ? e.message : String(e)); - -async function applyMigrations(sql: RawSql): Promise { - await sql`CREATE TABLE IF NOT EXISTS _schema (version INTEGER PRIMARY KEY)`; - const rows = - (await sql`SELECT version FROM _schema ORDER BY version DESC LIMIT 1`) as Array<{ - version: number; - }>; - const current = rows[0]?.version ?? 0; - for (const migration of MIGRATIONS) { - if (migration.version <= current) continue; - for (const statement of migration.sql) { - try { - await sql([statement] as unknown as TemplateStringsArray); - } catch (e) { - // Another tab opening the same database can apply an ALTER TABLE - // first; the column it adds is the one we wanted. - if (!isDuplicateColumn(e)) throw e; - } - } - await sql`INSERT OR IGNORE INTO _schema (version) VALUES (${migration.version})`; - } -} diff --git a/packages/sdk-storage-sqlocal/src/nodes/SqlocalNodesRepository.test.ts b/packages/sdk-storage-sqlocal/src/nodes/SqlocalNodesRepository.test.ts deleted file mode 100644 index 59f4eb92f..000000000 --- a/packages/sdk-storage-sqlocal/src/nodes/SqlocalNodesRepository.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import type { Node } from "@meshtastic/sdk"; -import { beforeEach, describe, expect, it } from "vitest"; -import type { SqlocalDb } from "../db.ts"; -import { createMemoryDb } from "../testing/createMemoryDb.ts"; -import { SqlocalNodesRepository } from "./SqlocalNodesRepository.ts"; - -function node(num: number, partial: Partial = {}): Node { - return { - num, - isFavorite: false, - isIgnored: false, - user: undefined, - position: undefined, - deviceMetrics: undefined, - lastHeard: undefined, - snr: undefined, - ...partial, - }; -} - -describe("SqlocalNodesRepository", () => { - let db: SqlocalDb; - let repo: SqlocalNodesRepository; - - beforeEach(async () => { - db = await createMemoryDb(); - repo = new SqlocalNodesRepository(db, { deviceId: 1 }); - }); - - it("upsert + loadAll round-trip", async () => { - await repo.upsert(node(1, { isFavorite: true, lastHeard: 1000 })); - await repo.upsert(node(2, { snr: 5 })); - const all = await repo.loadAll(); - expect(all.map((n) => n.num).sort()).toEqual([1, 2]); - expect((await repo.get(1))?.isFavorite).toBe(true); - }); - - it("upsert overwrites prior row", async () => { - await repo.upsert(node(7, { isFavorite: false })); - await repo.upsert(node(7, { isFavorite: true })); - expect((await repo.get(7))?.isFavorite).toBe(true); - }); - - it("preserves user proto across save + load", async () => { - const user = create(Protobuf.Mesh.UserSchema, { - id: "!abcdef00", - longName: "Test Node", - shortName: "TST", - }); - await repo.upsert(node(42, { user })); - const loaded = await repo.get(42); - expect(loaded?.user?.id).toBe("!abcdef00"); - expect(loaded?.user?.longName).toBe("Test Node"); - }); - - it("remove deletes the row", async () => { - await repo.upsert(node(9)); - await repo.remove(9); - expect(await repo.get(9)).toBeUndefined(); - }); - - it("clear wipes all rows for the scoped device", async () => { - await repo.upsertBatch([node(1), node(2), node(3)]); - await repo.clear(); - expect((await repo.loadAll()).length).toBe(0); - }); - - it("scoped per device_id", async () => { - const repoB = new SqlocalNodesRepository(db, { deviceId: 2 }); - await repo.upsert(node(1, { isFavorite: true })); - await repoB.upsert(node(1, { isFavorite: false })); - expect((await repo.get(1))?.isFavorite).toBe(true); - expect((await repoB.get(1))?.isFavorite).toBe(false); - }); - - it("setScope moves reads and writes to the new scope", async () => { - await repo.upsert(node(1, { snr: 1 })); - await repo.upsert(node(2)); - - repo.setScope(0xabcd); - expect(await repo.loadAll()).toEqual([]); - expect(await repo.get(1)).toBeUndefined(); - await repo.upsert(node(1, { snr: 9 })); - await repo.remove(2); - expect((await repo.loadAll()).map((n) => [n.num, n.snr])).toEqual([[1, 9]]); - await repo.clear(); - - const old = new SqlocalNodesRepository(db, { deviceId: 1 }); - expect((await old.loadAll()).map((n) => [n.num, n.snr]).sort()).toEqual([ - [1, 1], - [2, undefined], - ]); - }); -}); diff --git a/packages/sdk-storage-sqlocal/src/nodes/SqlocalNodesRepository.ts b/packages/sdk-storage-sqlocal/src/nodes/SqlocalNodesRepository.ts deleted file mode 100644 index a128688a4..000000000 --- a/packages/sdk-storage-sqlocal/src/nodes/SqlocalNodesRepository.ts +++ /dev/null @@ -1,155 +0,0 @@ -import type { Node, NodesRepository } from "@meshtastic/sdk"; -import { fromBinary, toBinary } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { and, eq } from "drizzle-orm"; -import type { SqlocalDb } from "../db.ts"; -import { nodes } from "../schema/nodes.ts"; - -export interface SqlocalNodesRepositoryOptions { - deviceId: number; -} - -/** - * Persists the snapshot of the device's NodeDB. user/position/metrics are - * stored as base64-encoded protobuf bytes — round-trip safe across schema - * additions because the wire shape is the source of truth. - */ -export class SqlocalNodesRepository implements NodesRepository { - private readonly db: SqlocalDb; - private deviceId: number; - - constructor(db: SqlocalDb, options: SqlocalNodesRepositoryOptions) { - this.db = db; - this.deviceId = options.deviceId; - } - - /** - * Points every later read and write at another `device_id`. Rows under the - * old one are left as they are. - */ - setScope(deviceId: number): void { - this.deviceId = deviceId; - } - - async loadAll(): Promise { - const rows = await this.db - .select() - .from(nodes) - .where(eq(nodes.deviceId, this.deviceId)); - return rows.map(rowToNode); - } - - async get(nodeNum: number): Promise { - const rows = await this.db - .select() - .from(nodes) - .where(and(eq(nodes.deviceId, this.deviceId), eq(nodes.num, nodeNum))!) - .limit(1); - return rows[0] ? rowToNode(rows[0]) : undefined; - } - - async upsert(node: Node): Promise { - await this.upsertBatch([node]); - } - - async upsertBatch(input: ReadonlyArray): Promise { - if (input.length === 0) return; - for (const node of input) { - const row = nodeToRow(this.deviceId, node); - await this.db - .insert(nodes) - .values(row) - .onConflictDoUpdate({ - target: [nodes.deviceId, nodes.num], - set: { - lastHeard: row.lastHeard, - snr: row.snr, - isFavorite: row.isFavorite, - isIgnored: row.isIgnored, - userJson: row.userJson, - positionJson: row.positionJson, - metricsJson: row.metricsJson, - }, - }); - } - } - - async remove(nodeNum: number): Promise { - await this.db - .delete(nodes) - .where(and(eq(nodes.deviceId, this.deviceId), eq(nodes.num, nodeNum))!); - } - - async clear(): Promise { - await this.db.delete(nodes).where(eq(nodes.deviceId, this.deviceId)); - } -} - -interface NodeRow { - deviceId: number; - num: number; - lastHeard: number | null; - snr: number | null; - isFavorite: boolean; - isIgnored: boolean; - userJson: string | null; - positionJson: string | null; - metricsJson: string | null; -} - -function rowToNode(row: NodeRow): Node { - return { - num: row.num, - user: row.userJson - ? fromBinary(Protobuf.Mesh.UserSchema, base64Decode(row.userJson)) - : undefined, - position: row.positionJson - ? fromBinary(Protobuf.Mesh.PositionSchema, base64Decode(row.positionJson)) - : undefined, - deviceMetrics: row.metricsJson - ? fromBinary( - Protobuf.Telemetry.DeviceMetricsSchema, - base64Decode(row.metricsJson), - ) - : undefined, - lastHeard: row.lastHeard ?? undefined, - snr: row.snr ?? undefined, - isFavorite: row.isFavorite, - isIgnored: row.isIgnored, - }; -} - -function nodeToRow(deviceId: number, node: Node): NodeRow { - return { - deviceId, - num: node.num, - lastHeard: node.lastHeard ?? null, - snr: node.snr ?? null, - isFavorite: node.isFavorite, - isIgnored: node.isIgnored, - userJson: node.user - ? base64Encode(toBinary(Protobuf.Mesh.UserSchema, node.user)) - : null, - positionJson: node.position - ? base64Encode(toBinary(Protobuf.Mesh.PositionSchema, node.position)) - : null, - metricsJson: node.deviceMetrics - ? base64Encode( - toBinary(Protobuf.Telemetry.DeviceMetricsSchema, node.deviceMetrics), - ) - : null, - }; -} - -function base64Encode(bytes: Uint8Array): string { - let s = ""; - for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]!); - return btoa(s); -} - -function base64Decode(s: string): Uint8Array { - const bin = atob(s); - const out = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); - return out; -} diff --git a/packages/sdk-storage-sqlocal/src/nodes/index.ts b/packages/sdk-storage-sqlocal/src/nodes/index.ts deleted file mode 100644 index c4ec529db..000000000 --- a/packages/sdk-storage-sqlocal/src/nodes/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { SqlocalNodesRepository } from "./SqlocalNodesRepository.ts"; -export type { SqlocalNodesRepositoryOptions } from "./SqlocalNodesRepository.ts"; diff --git a/packages/sdk-storage-sqlocal/src/schema/chat.ts b/packages/sdk-storage-sqlocal/src/schema/chat.ts deleted file mode 100644 index c72b39f47..000000000 --- a/packages/sdk-storage-sqlocal/src/schema/chat.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { - index, - integer, - real, - sqliteTable, - text, -} from "drizzle-orm/sqlite-core"; - -export const messages = sqliteTable( - "messages", - { - /** - * Composite primary key would be ideal, but Meshtastic packet IDs are - * already 32-bit random values; collisions across devices are rare. We - * scope reads by (device_id, conversation_key) so collisions only - * matter within a single device's history. - */ - id: integer("id").notNull(), - deviceId: integer("device_id").notNull(), - conversationKey: text("conversation_key").notNull(), - fromNode: integer("from_node").notNull(), - toNode: integer("to_node").notNull(), - channel: integer("channel").notNull(), - rxTime: integer("rx_time").notNull(), - type: text("type", { enum: ["broadcast", "direct"] }).notNull(), - text: text("text").notNull(), - state: text("state", { - enum: ["pending", "delivered", "ack", "failed"], - }).notNull(), - signed: integer("signed", { mode: "boolean" }), - ackProof: integer("ack_proof"), - routingError: integer("routing_error"), - relays: integer("relays"), - snr: real("snr"), - rssi: integer("rssi"), - hopsAway: integer("hops_away"), - viaMqtt: integer("via_mqtt", { mode: "boolean" }), - transport: integer("transport"), - }, - (t) => ({ - pk: index("messages_pk").on(t.deviceId, t.id), - convRxTime: index("idx_messages_conv_rxtime").on( - t.deviceId, - t.conversationKey, - t.rxTime, - ), - pending: index("idx_messages_pending").on(t.deviceId, t.state), - }), -); - -export type MessageRow = typeof messages.$inferSelect; -export type MessageInsert = typeof messages.$inferInsert; diff --git a/packages/sdk-storage-sqlocal/src/schema/drafts.ts b/packages/sdk-storage-sqlocal/src/schema/drafts.ts deleted file mode 100644 index 94a444597..000000000 --- a/packages/sdk-storage-sqlocal/src/schema/drafts.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { - integer, - primaryKey, - sqliteTable, - text, -} from "drizzle-orm/sqlite-core"; - -export const drafts = sqliteTable( - "drafts", - { - deviceId: integer("device_id").notNull(), - conversationKey: text("conversation_key").notNull(), - text: text("text").notNull(), - updatedAt: integer("updated_at").notNull(), - }, - (t) => ({ - pk: primaryKey({ columns: [t.deviceId, t.conversationKey] }), - }), -); - -export type DraftRow = typeof drafts.$inferSelect; -export type DraftInsert = typeof drafts.$inferInsert; diff --git a/packages/sdk-storage-sqlocal/src/schema/index.ts b/packages/sdk-storage-sqlocal/src/schema/index.ts deleted file mode 100644 index e0d60a346..000000000 --- a/packages/sdk-storage-sqlocal/src/schema/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * from "./chat.ts"; -export * from "./drafts.ts"; -export * from "./nodes.ts"; -export * from "./telemetry.ts"; -export * from "./migrations.ts"; diff --git a/packages/sdk-storage-sqlocal/src/schema/migrations.test.ts b/packages/sdk-storage-sqlocal/src/schema/migrations.test.ts deleted file mode 100644 index ae494b868..000000000 --- a/packages/sdk-storage-sqlocal/src/schema/migrations.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { describe, expect, it } from "vitest"; -import initSqlJs from "sql.js"; -import { isDuplicateColumn } from "../db.ts"; -import { MIGRATIONS } from "./migrations.ts"; - -async function freshSqlite() { - const SQL = await initSqlJs({}); - return new SQL.Database(); -} - -describe("MIGRATIONS", () => { - it("first migration creates messages, nodes, telemetry, _schema", async () => { - const db = await freshSqlite(); - for (const stmt of MIGRATIONS[0]!.sql) db.run(stmt); - db.run("INSERT INTO _schema (version) VALUES (?)", [ - MIGRATIONS[0]!.version, - ]); - - const tables = db - .exec( - "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name", - )[0] - ?.values.flat() as string[]; - expect(tables).toEqual( - expect.arrayContaining(["_schema", "messages", "nodes", "telemetry"]), - ); - - const version = db.exec("SELECT MAX(version) FROM _schema")[0] - ?.values[0]?.[0]; - expect(version).toBe(MIGRATIONS[0]!.version); - }); - - it("messages indexes are present after v1", async () => { - const db = await freshSqlite(); - for (const stmt of MIGRATIONS[0]!.sql) db.run(stmt); - const indexes = db - .exec( - "SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='messages' ORDER BY name", - )[0] - ?.values.flat() as string[]; - expect(indexes).toEqual( - expect.arrayContaining([ - "idx_messages_conv_rxtime", - "idx_messages_pending", - "messages_pk", - ]), - ); - }); - - it("re-applying v1 statements is idempotent (CREATE IF NOT EXISTS)", async () => { - const db = await freshSqlite(); - for (const stmt of MIGRATIONS[0]!.sql) db.run(stmt); - expect(() => { - for (const stmt of MIGRATIONS[0]!.sql) db.run(stmt); - }).not.toThrow(); - }); - - it("v3 adds the signed and ack_proof message columns", async () => { - const db = await freshSqlite(); - for (const migration of MIGRATIONS) { - for (const stmt of migration.sql) db.run(stmt); - } - const columns = db - .exec("PRAGMA table_info(messages)")[0] - ?.values.map((row) => row[1]) as string[]; - expect(columns).toEqual(expect.arrayContaining(["signed", "ack_proof"])); - }); - - it("v4 adds the received-signal message columns", async () => { - const db = await freshSqlite(); - for (const migration of MIGRATIONS) { - for (const stmt of migration.sql) db.run(stmt); - } - const columns = db - .exec("PRAGMA table_info(messages)")[0] - ?.values.map((row) => [row[1], row[2]]) as [string, string][]; - expect(columns).toEqual( - expect.arrayContaining([ - ["snr", "REAL"], - ["rssi", "INTEGER"], - ["hops_away", "INTEGER"], - ["via_mqtt", "INTEGER"], - ["transport", "INTEGER"], - ]), - ); - }); - - it("a second ALTER TABLE fails with an error isDuplicateColumn recognises", async () => { - const db = await freshSqlite(); - for (const migration of MIGRATIONS) { - for (const stmt of migration.sql) db.run(stmt); - } - let error: unknown; - try { - db.run(MIGRATIONS.at(-1)!.sql[0]!); - } catch (e) { - error = e; - } - expect(isDuplicateColumn(error)).toBe(true); - }); -}); diff --git a/packages/sdk-storage-sqlocal/src/schema/migrations.ts b/packages/sdk-storage-sqlocal/src/schema/migrations.ts deleted file mode 100644 index 20d99714a..000000000 --- a/packages/sdk-storage-sqlocal/src/schema/migrations.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { integer, sqliteTable } from "drizzle-orm/sqlite-core"; - -export const schemaVersion = sqliteTable("_schema", { - version: integer("version").primaryKey(), -}); - -/** - * Hand-written DDL applied at boot if `_schema` is empty or behind. Drizzle's - * own migration tooling is great but adds a build-time step; we keep migrations - * inline so the package self-bootstraps on first DB open. - */ -export const MIGRATIONS: ReadonlyArray<{ version: number; sql: string[] }> = [ - { - version: 1, - sql: [ - `CREATE TABLE IF NOT EXISTS messages ( - id INTEGER NOT NULL, - device_id INTEGER NOT NULL, - conversation_key TEXT NOT NULL, - from_node INTEGER NOT NULL, - to_node INTEGER NOT NULL, - channel INTEGER NOT NULL, - rx_time INTEGER NOT NULL, - type TEXT NOT NULL, - text TEXT NOT NULL, - state TEXT NOT NULL - )`, - `CREATE INDEX IF NOT EXISTS messages_pk ON messages(device_id, id)`, - `CREATE INDEX IF NOT EXISTS idx_messages_conv_rxtime ON messages(device_id, conversation_key, rx_time)`, - `CREATE INDEX IF NOT EXISTS idx_messages_pending ON messages(device_id, state)`, - `CREATE TABLE IF NOT EXISTS nodes ( - device_id INTEGER NOT NULL, - num INTEGER NOT NULL, - last_heard INTEGER, - snr INTEGER, - is_favorite INTEGER NOT NULL DEFAULT 0, - is_ignored INTEGER NOT NULL DEFAULT 0, - user_json TEXT, - position_json TEXT, - metrics_json TEXT, - PRIMARY KEY (device_id, num) - )`, - `CREATE INDEX IF NOT EXISTS idx_nodes_last_heard ON nodes(device_id, last_heard)`, - `CREATE TABLE IF NOT EXISTS telemetry ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - device_id INTEGER NOT NULL, - node_num INTEGER NOT NULL, - kind TEXT NOT NULL, - ts INTEGER NOT NULL, - payload_json TEXT NOT NULL - )`, - `CREATE INDEX IF NOT EXISTS idx_telemetry_node_ts ON telemetry(device_id, node_num, ts)`, - `CREATE TABLE IF NOT EXISTS _schema (version INTEGER PRIMARY KEY)`, - ], - }, - { - version: 2, - sql: [ - `CREATE TABLE IF NOT EXISTS drafts ( - device_id INTEGER NOT NULL, - conversation_key TEXT NOT NULL, - text TEXT NOT NULL, - updated_at INTEGER NOT NULL, - PRIMARY KEY (device_id, conversation_key) - )`, - ], - }, - { - // Firmware 2.8: XEdDSA-signed messages, ack proof of delivery, and why - // a message failed and how many acks it got. - version: 3, - sql: [ - `ALTER TABLE messages ADD COLUMN signed INTEGER`, - `ALTER TABLE messages ADD COLUMN ack_proof INTEGER`, - `ALTER TABLE messages ADD COLUMN routing_error INTEGER`, - `ALTER TABLE messages ADD COLUMN relays INTEGER`, - ], - }, - { - // How a received message reached us: signal, hops and transport. - version: 4, - sql: [ - `ALTER TABLE messages ADD COLUMN snr REAL`, - `ALTER TABLE messages ADD COLUMN rssi INTEGER`, - `ALTER TABLE messages ADD COLUMN hops_away INTEGER`, - `ALTER TABLE messages ADD COLUMN via_mqtt INTEGER`, - `ALTER TABLE messages ADD COLUMN transport INTEGER`, - ], - }, -]; diff --git a/packages/sdk-storage-sqlocal/src/schema/nodes.ts b/packages/sdk-storage-sqlocal/src/schema/nodes.ts deleted file mode 100644 index c0a387949..000000000 --- a/packages/sdk-storage-sqlocal/src/schema/nodes.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { - index, - integer, - primaryKey, - sqliteTable, - text, -} from "drizzle-orm/sqlite-core"; - -/** - * Snapshot of the device's NodeDB. Position / metrics / user are stored as - * JSON blobs (proto-shape) — slice infrastructure mappers are responsible - * for serialization. Last-heard duplicates the column for sortable indexes. - */ -export const nodes = sqliteTable( - "nodes", - { - deviceId: integer("device_id").notNull(), - num: integer("num").notNull(), - lastHeard: integer("last_heard"), - snr: integer("snr"), - isFavorite: integer("is_favorite", { mode: "boolean" }) - .notNull() - .default(false), - isIgnored: integer("is_ignored", { mode: "boolean" }) - .notNull() - .default(false), - userJson: text("user_json"), - positionJson: text("position_json"), - metricsJson: text("metrics_json"), - }, - (t) => ({ - pk: primaryKey({ columns: [t.deviceId, t.num] }), - lastHeardIdx: index("idx_nodes_last_heard").on(t.deviceId, t.lastHeard), - }), -); - -export type NodeRow = typeof nodes.$inferSelect; -export type NodeInsert = typeof nodes.$inferInsert; diff --git a/packages/sdk-storage-sqlocal/src/schema/telemetry.ts b/packages/sdk-storage-sqlocal/src/schema/telemetry.ts deleted file mode 100644 index b67b1af75..000000000 --- a/packages/sdk-storage-sqlocal/src/schema/telemetry.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; - -export const telemetry = sqliteTable( - "telemetry", - { - id: integer("id").primaryKey({ autoIncrement: true }), - deviceId: integer("device_id").notNull(), - nodeNum: integer("node_num").notNull(), - kind: text("kind").notNull(), - ts: integer("ts").notNull(), - payloadJson: text("payload_json").notNull(), - }, - (t) => ({ - nodeTs: index("idx_telemetry_node_ts").on(t.deviceId, t.nodeNum, t.ts), - }), -); - -export type TelemetryRow = typeof telemetry.$inferSelect; -export type TelemetryInsert = typeof telemetry.$inferInsert; diff --git a/packages/sdk-storage-sqlocal/src/telemetry/SqlocalTelemetryRepository.test.ts b/packages/sdk-storage-sqlocal/src/telemetry/SqlocalTelemetryRepository.test.ts deleted file mode 100644 index 7912483d6..000000000 --- a/packages/sdk-storage-sqlocal/src/telemetry/SqlocalTelemetryRepository.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import type { TelemetryReading } from "@meshtastic/sdk"; -import { beforeEach, describe, expect, it } from "vitest"; -import type { SqlocalDb } from "../db.ts"; -import { createMemoryDb } from "../testing/createMemoryDb.ts"; -import { SqlocalTelemetryRepository } from "./SqlocalTelemetryRepository.ts"; - -function reading(nodeNum: number, ms: number, battery = 80): TelemetryReading { - return { - nodeNum, - time: new Date(ms), - kind: "deviceMetrics", - value: create(Protobuf.Telemetry.DeviceMetricsSchema, { - batteryLevel: battery, - }), - }; -} - -describe("SqlocalTelemetryRepository", () => { - let db: SqlocalDb; - let repo: SqlocalTelemetryRepository; - - beforeEach(async () => { - db = await createMemoryDb(); - repo = new SqlocalTelemetryRepository(db, { deviceId: 1 }); - }); - - it("appends and loads recent readings ordered ascending", async () => { - await repo.append(reading(100, 1000, 90)); - await repo.append(reading(100, 2000, 80)); - await repo.append(reading(100, 3000, 70)); - - const out = await repo.loadRecent(100, 10); - expect(out.map((r) => r.time.getTime())).toEqual([1000, 2000, 3000]); - expect( - (out[2]?.value as { batteryLevel?: number } | undefined)?.batteryLevel, - ).toBe(70); - }); - - it("loadBefore returns rows older than the cursor in ascending order", async () => { - await repo.appendBatch([ - reading(100, 1000), - reading(100, 2000), - reading(100, 3000), - reading(100, 4000), - ]); - - const out = await repo.loadBefore(100, new Date(3000), 10); - expect(out.map((r) => r.time.getTime())).toEqual([1000, 2000]); - }); - - it("scopes by deviceId — different repos see only their own rows", async () => { - const repo2 = new SqlocalTelemetryRepository(db, { deviceId: 2 }); - await repo.append(reading(50, 1000)); - await repo2.append(reading(50, 1000)); - - expect(await repo.loadRecent(50, 10)).toHaveLength(1); - expect(await repo2.loadRecent(50, 10)).toHaveLength(1); - - await repo.clearNode(50); - expect(await repo.loadRecent(50, 10)).toHaveLength(0); - expect(await repo2.loadRecent(50, 10)).toHaveLength(1); - }); - - it("prune trims per-node history to maxPerNode", async () => { - for (let i = 0; i < 20; i++) { - await repo.append(reading(7, (i + 1) * 1000)); - } - await repo.prune({ maxPerNode: 5 }); - const remaining = await repo.loadRecent(7, 100); - expect(remaining).toHaveLength(5); - // The 5 newest entries kept (16k..20k) - expect(remaining[0]?.time.getTime()).toBe(16_000); - expect(remaining[4]?.time.getTime()).toBe(20_000); - }); - - it("prune drops readings older than olderThanMs", async () => { - await repo.append(reading(7, Date.now() - 10_000_000)); - await repo.append(reading(7, Date.now() - 1000)); - await repo.prune({ olderThanMs: 5_000_000 }); - expect(await repo.loadRecent(7, 100)).toHaveLength(1); - }); - - it("preserves the proto payload across save + load", async () => { - const value = create(Protobuf.Telemetry.DeviceMetricsSchema, { - batteryLevel: 73, - voltage: 4.1, - }); - await repo.append({ - nodeNum: 9, - time: new Date(123_456), - kind: "deviceMetrics", - value, - }); - const out = await repo.loadRecent(9, 1); - const v = out[0]?.value as - | { batteryLevel?: number; voltage?: number } - | undefined; - expect(v?.batteryLevel).toBe(73); - expect(v?.voltage).toBeCloseTo(4.1); - }); - - it("setScope moves reads, writes and pruning to the new scope", async () => { - await repo.appendBatch([reading(100, 1000), reading(100, 2000)]); - - repo.setScope(0xabcd); - expect(await repo.loadRecent(100, 10)).toEqual([]); - await repo.appendBatch([reading(100, 3000), reading(100, 4000)]); - await repo.prune({ maxPerNode: 1 }); - expect( - (await repo.loadRecent(100, 10)).map((r) => r.time.getTime()), - ).toEqual([4000]); - - const old = new SqlocalTelemetryRepository(db, { deviceId: 1 }); - expect( - (await old.loadRecent(100, 10)).map((r) => r.time.getTime()), - ).toEqual([1000, 2000]); - }); -}); diff --git a/packages/sdk-storage-sqlocal/src/telemetry/SqlocalTelemetryRepository.ts b/packages/sdk-storage-sqlocal/src/telemetry/SqlocalTelemetryRepository.ts deleted file mode 100644 index 67a6246de..000000000 --- a/packages/sdk-storage-sqlocal/src/telemetry/SqlocalTelemetryRepository.ts +++ /dev/null @@ -1,218 +0,0 @@ -import { fromBinary, toBinary } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import type { - TelemetryReading, - TelemetryRepository, - TelemetryRetentionPolicy, -} from "@meshtastic/sdk"; -import { and, asc, count, desc, eq, gte, lt, sql } from "drizzle-orm"; -import type { SqlocalDb } from "../db.ts"; -import { telemetry } from "../schema/telemetry.ts"; - -export interface SqlocalTelemetryRepositoryOptions { - deviceId: number; -} - -const SCHEMA_FOR_KIND = { - deviceMetrics: Protobuf.Telemetry.DeviceMetricsSchema, - environmentMetrics: Protobuf.Telemetry.EnvironmentMetricsSchema, - airQualityMetrics: Protobuf.Telemetry.AirQualityMetricsSchema, - powerMetrics: Protobuf.Telemetry.PowerMetricsSchema, - localStats: Protobuf.Telemetry.LocalStatsSchema, - healthMetrics: Protobuf.Telemetry.HealthMetricsSchema, - hostMetrics: Protobuf.Telemetry.HostMetricsSchema, -} as const; - -type KnownKind = keyof typeof SCHEMA_FOR_KIND; - -export class SqlocalTelemetryRepository implements TelemetryRepository { - private readonly db: SqlocalDb; - private deviceId: number; - - constructor(db: SqlocalDb, options: SqlocalTelemetryRepositoryOptions) { - this.db = db; - this.deviceId = options.deviceId; - } - - /** - * Points every later read and write at another `device_id`. Rows under the - * old one are left as they are. - */ - setScope(deviceId: number): void { - this.deviceId = deviceId; - } - - async loadRecent( - nodeNum: number, - limit: number, - ): Promise { - const rows = await this.db - .select() - .from(telemetry) - .where( - and( - eq(telemetry.deviceId, this.deviceId), - eq(telemetry.nodeNum, nodeNum), - )!, - ) - .orderBy(desc(telemetry.ts)) - .limit(limit); - return rows.map(rowToReading).reverse(); - } - - async loadBefore( - nodeNum: number, - cursor: Date, - limit: number, - ): Promise { - const rows = await this.db - .select() - .from(telemetry) - .where( - and( - eq(telemetry.deviceId, this.deviceId), - eq(telemetry.nodeNum, nodeNum), - lt(telemetry.ts, cursor.getTime()), - )!, - ) - .orderBy(desc(telemetry.ts)) - .limit(limit); - return rows.map(rowToReading).reverse(); - } - - async append(reading: TelemetryReading): Promise { - await this.appendBatch([reading]); - } - - async appendBatch(readings: ReadonlyArray): Promise { - if (readings.length === 0) return; - const rows = readings - .map((r) => readingToRow(this.deviceId, r)) - .filter((r): r is TelemetryRow => r !== null); - if (rows.length === 0) return; - await this.db.insert(telemetry).values(rows); - } - - async prune(policy: TelemetryRetentionPolicy): Promise { - if (policy.olderThanMs !== undefined) { - const cutoff = Date.now() - policy.olderThanMs; - await this.db - .delete(telemetry) - .where( - and(eq(telemetry.deviceId, this.deviceId), lt(telemetry.ts, cutoff))!, - ); - } - if (policy.maxPerNode !== undefined) { - const max = policy.maxPerNode; - // Get distinct nodes that exceed the cap, then trim each. - const overCap = await this.db - .select({ nodeNum: telemetry.nodeNum, c: count() }) - .from(telemetry) - .where(eq(telemetry.deviceId, this.deviceId)) - .groupBy(telemetry.nodeNum) - .having(sql`count(*) > ${max}`); - for (const row of overCap) { - // Keep the newest `max` rows; delete everything older than the - // ts-of-the-(max+1)th-newest. ts ASC; offset by max-th gives cutoff. - const cutoffRows = await this.db - .select({ ts: telemetry.ts }) - .from(telemetry) - .where( - and( - eq(telemetry.deviceId, this.deviceId), - eq(telemetry.nodeNum, row.nodeNum), - )!, - ) - .orderBy(desc(telemetry.ts)) - .limit(1) - .offset(max - 1); - const cutoff = cutoffRows[0]?.ts; - if (cutoff === undefined) continue; - await this.db - .delete(telemetry) - .where( - and( - eq(telemetry.deviceId, this.deviceId), - eq(telemetry.nodeNum, row.nodeNum), - lt(telemetry.ts, cutoff), - )!, - ); - } - } - void asc; // silence unused import without breaking the export shape - void gte; - } - - async clearNode(nodeNum: number): Promise { - await this.db - .delete(telemetry) - .where( - and( - eq(telemetry.deviceId, this.deviceId), - eq(telemetry.nodeNum, nodeNum), - )!, - ); - } - - async clear(): Promise { - await this.db - .delete(telemetry) - .where(eq(telemetry.deviceId, this.deviceId)); - } -} - -interface TelemetryRow { - deviceId: number; - nodeNum: number; - kind: string; - ts: number; - payloadJson: string; -} - -function readingToRow( - deviceId: number, - reading: TelemetryReading, -): TelemetryRow | null { - if (!reading.kind) return null; - const schema = SCHEMA_FOR_KIND[reading.kind as KnownKind]; - if (!schema) return null; - return { - deviceId, - nodeNum: reading.nodeNum, - kind: reading.kind, - ts: reading.time.getTime(), - payloadJson: base64Encode(toBinary(schema, reading.value as never)), - }; -} - -function rowToReading(row: { - nodeNum: number; - kind: string; - ts: number; - payloadJson: string; -}): TelemetryReading { - const kind = row.kind as KnownKind; - const schema = SCHEMA_FOR_KIND[kind]; - const value = schema - ? fromBinary(schema, base64Decode(row.payloadJson)) - : (undefined as unknown as TelemetryReading["value"]); - return { - nodeNum: row.nodeNum, - time: new Date(row.ts), - kind, - value: value as TelemetryReading["value"], - }; -} - -function base64Encode(bytes: Uint8Array): string { - let s = ""; - for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]!); - return btoa(s); -} - -function base64Decode(s: string): Uint8Array { - const bin = atob(s); - const out = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); - return out; -} diff --git a/packages/sdk-storage-sqlocal/src/telemetry/index.ts b/packages/sdk-storage-sqlocal/src/telemetry/index.ts deleted file mode 100644 index 7b90aff83..000000000 --- a/packages/sdk-storage-sqlocal/src/telemetry/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { - SqlocalTelemetryRepository, - type SqlocalTelemetryRepositoryOptions, -} from "./SqlocalTelemetryRepository.ts"; diff --git a/packages/sdk-storage-sqlocal/src/testing/createMemoryDb.ts b/packages/sdk-storage-sqlocal/src/testing/createMemoryDb.ts deleted file mode 100644 index 8a0b48992..000000000 --- a/packages/sdk-storage-sqlocal/src/testing/createMemoryDb.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { drizzle } from "drizzle-orm/sql-js"; -import initSqlJs from "sql.js"; -import * as schema from "../schema/index.ts"; -import { MIGRATIONS } from "../schema/migrations.ts"; -import type { SqlocalDb } from "../db.ts"; - -/** - * In-memory database backed by sql.js, for tests and other Node contexts. - * Same Drizzle interface as the production sqlocal connection so repository - * code is portable between browser and test runs. - */ -export async function createMemoryDb(): Promise { - const SQL = await initSqlJs({}); - const sqlite = new SQL.Database(); - - for (const migration of MIGRATIONS) { - for (const statement of migration.sql) { - sqlite.run(statement); - } - sqlite.run("INSERT OR IGNORE INTO _schema (version) VALUES (?)", [ - migration.version, - ]); - } - - return drizzle(sqlite, { - schema, - casing: "snake_case", - }) as unknown as SqlocalDb; -} diff --git a/packages/sdk-storage-sqlocal/src/testing/index.ts b/packages/sdk-storage-sqlocal/src/testing/index.ts deleted file mode 100644 index 0e02274eb..000000000 --- a/packages/sdk-storage-sqlocal/src/testing/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { createMemoryDb } from "./createMemoryDb.ts"; diff --git a/packages/sdk-storage-sqlocal/tests/sqlocal-opfs.browser.test.ts b/packages/sdk-storage-sqlocal/tests/sqlocal-opfs.browser.test.ts deleted file mode 100644 index 6a45a6abb..000000000 --- a/packages/sdk-storage-sqlocal/tests/sqlocal-opfs.browser.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { ChannelNumber, type Message, MessageState } from "@meshtastic/sdk"; -import { describe, expect, it } from "vitest"; -import { SqlocalMessageRepository } from "../src/chat/SqlocalMessageRepository.ts"; -import { createSqlocalDb, openSqlocalDb } from "../src/db.ts"; - -/** - * Browser-mode end-to-end test: opens a real OPFS-backed SQLite database via - * sqlocal, exercises the chat repository, asserts persistence across two - * separate `createSqlocalDb()` calls (simulating page reload). - * - * Run with `pnpm --filter @meshtastic/sdk-storage-sqlocal test:browser`. - */ - -function msg(id: number, ms: number, text = "t"): Message { - return { - id, - from: 1, - to: 0xffffffff, - channel: ChannelNumber.Primary, - rxTime: new Date(ms), - type: "broadcast", - text, - state: MessageState.Ack, - }; -} - -describe.runIf(typeof navigator !== "undefined")( - "sqlocal OPFS round-trip", - () => { - it("reports that the database is saved to OPFS", async () => { - const opened = await openSqlocalDb({ - databasePath: `meshtastic-test-info-${Date.now()}.db`, - }); - expect(opened).toMatchObject({ storageType: "opfs", persistent: true }); - }); - - it("persists messages across DB instances", async () => { - const dbPath = `meshtastic-test-${Date.now()}.db`; - const dbA = await createSqlocalDb({ databasePath: dbPath }); - const repoA = new SqlocalMessageRepository(dbA, { deviceId: 1 }); - await repoA.appendBatch([msg(1, 1000), msg(2, 2000)]); - - const dbB = await createSqlocalDb({ databasePath: dbPath }); - const repoB = new SqlocalMessageRepository(dbB, { deviceId: 1 }); - const out = await repoB.loadRecent( - { kind: "channel", channel: ChannelNumber.Primary }, - 10, - ); - expect(out.map((m) => m.id)).toEqual([1, 2]); - }); - }, -); diff --git a/packages/sdk-storage-sqlocal/tsconfig.json b/packages/sdk-storage-sqlocal/tsconfig.json deleted file mode 100644 index b01917932..000000000 --- a/packages/sdk-storage-sqlocal/tsconfig.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "include": ["mod.ts", "src"] -} diff --git a/packages/sdk-storage-sqlocal/vitest.browser.config.ts b/packages/sdk-storage-sqlocal/vitest.browser.config.ts deleted file mode 100644 index aeafe36ff..000000000 --- a/packages/sdk-storage-sqlocal/vitest.browser.config.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { defineProject } from "vitest/config"; - -/** - * Browser-mode tests for the OPFS-backed SQLite path. - * - * Runs separately from the Node `vitest run` so CI can opt in (and the - * Playwright browser binary download isn't a hard requirement for the - * fast unit-test loop). - * - * Run with: - * pnpm --filter @meshtastic/sdk-storage-sqlocal test:browser - * - * Requires `@vitest/browser` + Playwright. Install with: - * pnpm add -D -w @vitest/browser playwright - */ -export default defineProject({ - test: { - name: "@meshtastic/sdk-storage-sqlocal:browser", - include: ["src/**/*.browser.test.ts", "tests/**/*.browser.test.ts"], - browser: { - enabled: true, - provider: "playwright", - headless: true, - instances: [{ browser: "chromium" }], - }, - }, -}); diff --git a/packages/sdk-storage-sqlocal/vitest.config.ts b/packages/sdk-storage-sqlocal/vitest.config.ts deleted file mode 100644 index 7a938780c..000000000 --- a/packages/sdk-storage-sqlocal/vitest.config.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { defineProject } from "vitest/config"; - -export default defineProject({ - test: { - name: "@meshtastic/sdk-storage-sqlocal", - environment: "node", - include: ["src/**/*.test.ts", "tests/**/*.test.ts"], - // Browser-mode tests run via vitest.browser.config.ts so they don't - // execute under the Node runner where OPFS is unavailable. - exclude: ["**/*.browser.test.ts", "**/node_modules/**"], - }, -}); diff --git a/packages/sdk/README.md b/packages/sdk/README.md deleted file mode 100644 index 1727ffc14..000000000 --- a/packages/sdk/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# @meshtastic/sdk - -Domain-driven SDK for Meshtastic devices. Feature slices with signals-backed reactive state. - -Replaces `@meshtastic/core`. During migration a shim layer re-exports the legacy `MeshDevice` class so existing consumers keep building — see `src/shim/`. - -## Install - -```sh -pnpm add @meshtastic/sdk @meshtastic/transport-web-serial -``` - -## Quickstart - -```ts -import { MeshClient } from "@meshtastic/sdk"; -import { TransportWebSerial } from "@meshtastic/transport-web-serial"; - -const transport = await TransportWebSerial.create({ baudRate: 115200 }); -const client = new MeshClient({ transport }); -await client.connect(); - -client.chat.send({ text: "hello mesh" }); -console.log(client.nodes.list.value); -``` - -See the repo root [README](../../README.md) for architecture and feature slice layout. - -## Layout - -``` -src/ - core/ # shared kernel: client, transport, event-bus, queue, xmodem, signals, logging, packet-codec - features/ # DDD feature slices (device, chat, nodes, channels, config, telemetry, position, traceroute, files) - shim/ # legacy MeshDevice compatibility exports (removed in Phase C) -``` - -## License - -GPL-3.0-only. diff --git a/packages/sdk/mod.ts b/packages/sdk/mod.ts deleted file mode 100644 index 0b7f7116e..000000000 --- a/packages/sdk/mod.ts +++ /dev/null @@ -1,182 +0,0 @@ -// Main entry -export { MeshClient } from "./src/core/client/MeshClient.ts"; -export type { - ConnectionProgress, - ConnectionProgressCounters, - MeshClientOptions, -} from "./src/core/client/MeshClient.ts"; -export { MeshRegistry } from "./src/core/registry/MeshRegistry.ts"; -export type { - ConnectionId, - RegistryEntry, -} from "./src/core/registry/MeshRegistry.ts"; - -// Constants & errors -export { Constants } from "./src/core/constants/index.ts"; -export { - FirmwareTooOldError, - HandshakeTimeoutError, - MeshError, - PacketTooLargeError, - TransportClosedError, -} from "./src/core/errors/MeshError.ts"; - -// Shared signal primitives -export { - createStore, - SignalMap, - toReadonly, -} from "./src/core/signals/createStore.ts"; -export type { ReadonlySignal } from "./src/core/signals/createStore.ts"; - -// Logging -export { createLogger } from "./src/core/logging/logger.ts"; - -// Identifiers -export { generatePacketId } from "./src/core/identifiers/PacketId.ts"; - -// Event bus (advanced consumers) -export { EventBus } from "./src/core/event-bus/EventBus.ts"; - -// Packet codec streams (transport implementations) -export { fromDeviceStream } from "./src/core/packet-codec/fromDevice.ts"; -export { toDeviceStream } from "./src/core/packet-codec/toDevice.ts"; - -// Queue + Xmodem (advanced) -export { Queue } from "./src/core/queue/Queue.ts"; -export { Xmodem } from "./src/core/xmodem/Xmodem.ts"; - -// Transport interface -export type { - DeviceOutput, - HttpRetryConfig, - Transport, -} from "./src/core/transport/Transport.ts"; -export { DeviceStatusEnum } from "./src/core/transport/Transport.ts"; - -// Commonly-used runtime enums exported directly for ergonomic access. -export { ChannelNumber, Emitter, EmitterScope } from "./src/core/types.ts"; -export type { - Destination, - LogEvent, - LogEventPacket, - PacketDestination, - PacketError, - PacketMetadata, - QueueItem, -} from "./src/core/types.ts"; - -// Cross-cutting types kept under the Types namespace for consumers that -// already reference legacy enums/interfaces. Imported via the wrapper to -// dodge a tsdown dts emitter glitch on bare `export * as` namespaces. -import * as Types from "./src/types-namespace.ts"; -export { Types }; - -// Protobuf (re-export) -export * as Protobuf from "@meshtastic/protobufs"; - -// Feature slice clients + domain types -export { DeviceClient } from "./src/features/device/index.ts"; -export type { Device } from "./src/features/device/index.ts"; -export { - ABS_MIN_FIRMWARE_VERSION, - firmwareAtLeast, - firmwareSupport, - MIN_FIRMWARE_VERSION, -} from "./src/features/device/domain/FirmwareVersion.ts"; -export type { FirmwareSupport } from "./src/features/device/domain/FirmwareVersion.ts"; -export type { UnlockOptions } from "./src/features/device/application/LockdownService.ts"; - -export { ChatClient } from "./src/features/chat/index.ts"; -export type { - ChatClientOptions, - ChatDrafts, - ChatUnread, - ConversationKey, - DraftRepository, - Message, - MessageDeliveryPatch, - MessageRepository, - RetentionPolicy, - SendTextError, - SendTextInput, -} from "./src/features/chat/index.ts"; -export { - conversationKeyString, - EmptyMessageError, - InMemoryDraftRepository, - InMemoryMessageRepository, - inferConversation, - MessageState, - MessageTooLongError, - parseConversationKey, -} from "./src/features/chat/index.ts"; - -export { - isUnheardOnCurrentLora, - NodesClient, -} from "./src/features/nodes/index.ts"; -export type { - Node, - NodeError, - NodeErrorType, - NodesClientOptions, - NodesRepository, -} from "./src/features/nodes/index.ts"; -export { InMemoryNodesRepository } from "./src/features/nodes/index.ts"; - -export { ChannelsClient } from "./src/features/channels/index.ts"; -export type { - BeaconJoinOption, - Channel, - MeshBeaconOffer, -} from "./src/features/channels/index.ts"; -export { - beaconJoinChannelSet, - beaconJoinOption, - isBeaconAlreadyJoined, -} from "./src/features/channels/index.ts"; - -export { - CANNED_MESSAGES_MAX_BYTES, - ConfigClient, - ConfigEditor, - RINGTONE_MAX_BYTES, -} from "./src/features/config/index.ts"; -export type { - ModuleConfig, - ModuleConfigSection, - RadioConfig, - RadioConfigSection, -} from "./src/features/config/index.ts"; - -export { - InMemoryTelemetryRepository, - TelemetryClient, -} from "./src/features/telemetry/index.ts"; -export type { - TelemetryClientOptions, - TelemetryKind, - TelemetryReading, - TelemetryRepository, - TelemetryRetentionPolicy, -} from "./src/features/telemetry/index.ts"; - -export { PositionClient } from "./src/features/position/index.ts"; -export type { Position } from "./src/features/position/index.ts"; - -export { TraceRouteClient } from "./src/features/traceroute/index.ts"; -export type { TraceRoute } from "./src/features/traceroute/index.ts"; - -export { FilesClient } from "./src/features/files/index.ts"; -export type { - FileTransfer, - TransferStatus, -} from "./src/features/files/index.ts"; - -// Phase-A legacy shims (removed in Phase C) -export { MeshDevice } from "./src/shim/legacyMeshDevice.ts"; -// Same workaround as Types — go through a wrapper to dodge tsdown's dts -// emitter bug on `export * as`. -import * as Utils from "./src/shim/legacyUtils.ts"; -export { Utils }; diff --git a/packages/sdk/package.json b/packages/sdk/package.json deleted file mode 100644 index 02690737d..000000000 --- a/packages/sdk/package.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "name": "@meshtastic/sdk", - "version": "1.0.0", - "description": "Domain-driven SDK for Meshtastic devices. Feature slices (device/chat/nodes/channels/config/telemetry/position/traceroute/files) with signals-backed reactive state. Replaces @meshtastic/core.", - "license": "GPL-3.0-only", - "repository": { - "type": "git", - "url": "git+https://github.com/meshtastic/web.git", - "directory": "packages/sdk" - }, - "files": [ - "package.json", - "README.md", - "LICENSE", - "dist" - ], - "type": "module", - "main": "./dist/mod.js", - "module": "./dist/mod.js", - "types": "./dist/mod.d.ts", - "exports": { - ".": { - "types": "./dist/mod.d.ts", - "default": "./mod.ts" - }, - "./transport": { - "types": "./dist/transport.d.ts", - "default": "./src/core/transport/index.ts" - }, - "./protobuf": { - "types": "./dist/protobuf.d.ts", - "default": "./src/core/protobuf/index.ts" - }, - "./testing": { - "types": "./dist/testing.d.ts", - "default": "./src/core/testing/index.ts" - } - }, - "scripts": { - "preinstall": "npx only-allow pnpm", - "prepack": "cp ../../LICENSE ./LICENSE", - "clean": "rm -rf dist LICENSE", - "build:npm": "tsdown && node ./scripts/rename-dts.mjs", - "publish:npm": "pnpm clean && pnpm build:npm && pnpm publish --access public --no-git-checks", - "prepare:jsr": "rm -rf dist && pnpm dlx pkg-to-jsr", - "publish:jsr": "pnpm run prepack && pnpm prepare:jsr && deno publish --allow-dirty --no-check", - "test": "vitest run" - }, - "dependencies": { - "@bufbuild/protobuf": "^2.16.0", - "@meshtastic/protobufs": "jsr:^2.8.1", - "@preact/signals-core": "^1.14.4", - "better-result": "^3.0.1", - "crc": "npm:crc@^4.3.2", - "ste-simple-events": "^4.0.0", - "tslog": "^5.2.0" - }, - "tsdown": { - "clean": true, - "dts": true, - "entry": { - "mod": "mod.ts", - "protobuf": "src/core/protobuf/index.ts", - "testing": "src/core/testing/index.ts", - "transport": "src/core/transport/index.ts" - }, - "format": [ - "esm" - ], - "minify": false, - "platform": "browser", - "report": false, - "sourcemap": false, - "splitting": false, - "target": "esnext", - "treeshake": true - }, - "jsrExclude": [ - "src/**/*.test.ts", - "tests" - ], - "jsrInclude": [ - "mod.ts", - "src", - "README.md", - "LICENSE" - ] -} diff --git a/packages/sdk/scripts/rename-dts.mjs b/packages/sdk/scripts/rename-dts.mjs deleted file mode 100644 index 3a28adfc4..000000000 --- a/packages/sdk/scripts/rename-dts.mjs +++ /dev/null @@ -1,213 +0,0 @@ -#!/usr/bin/env node -/** - * Postbuild step that fixes three tsdown dts emitter glitches: - * - * 1. Renames hashed entry-point dts outputs (e.g. `mod-.d.ts`) to - * their canonical names. tsdown emits hashes for multi-entry builds - * even with `splitting: false`. - * - * 2. Inlines internal chunk dts files (e.g. `Transport-.d.ts`) into - * each entry-point dts. Downstream dts bundlers (rolldown) can't follow - * cross-chunk re-exports — they read the entry dts only and report - * "Missing export" for any identifier originally declared in a chunk. - * Inlining the chunk content + rewriting the import-letter aliases - * (`i as Transport`) produces a self-contained entry dts. - * - * 3. Patches `mod.d.ts` to declare the synthetic namespace identifiers - * that tsdown references but never defines. The `export * as Types - * from "..."` and `export * as Utils from "..."` patterns in mod.ts - * end up in the dist as `_d_exports as Types` re-exports - * without an accompanying `declare namespace ...` block. - */ - -import { - existsSync, - readdirSync, - readFileSync, - renameSync, - statSync, - unlinkSync, - writeFileSync, -} from "node:fs"; -import { join } from "node:path"; - -const distDir = new URL("../dist", import.meta.url).pathname; - -const KNOWN_ENTRIES = ["mod", "transport", "protobuf", "testing"]; - -const TYPES_MEMBERS = { - values: ["ChannelNumber", "DeviceStatusEnum", "Emitter", "EmitterScope"], - types: [ - "Destination", - "DeviceOutput", - "HttpRetryConfig", - "LogEvent", - "LogEventPacket", - "PacketDestination", - "PacketError", - "PacketMetadata", - "QueueItem", - "Transport", - ], -}; - -const UTILS_MEMBERS = { - values: ["EventBus", "Queue", "Xmodem", "fromDeviceStream", "toDeviceStream"], - types: [], - aliases: { EventSystem: "EventBus" }, -}; - -function renameEntries() { - const files = readdirSync(distDir); - for (const f of files) { - const match = f.match(/^([A-Za-z]+)-[A-Za-z0-9_-]+\.d\.ts$/); - if (!match) continue; - const entry = match[1]; - if (!KNOWN_ENTRIES.includes(entry)) continue; - - const target = `${entry}.d.ts`; - const src = join(distDir, f); - const dst = join(distDir, target); - - try { - statSync(dst); - continue; - } catch { - // canonical file doesn't exist — go ahead - } - renameSync(src, dst); - } -} - -// Match: import { i as Transport, n as DeviceStatusEnum, ... } from "./Foo-hash.js"; -const CHUNK_IMPORT_RE = - /^import\s*\{([^}]+)\}\s*from\s*"\.\/([A-Za-z]+-[A-Za-z0-9_-]+)\.js";\s*$/m; - -function inlineChunks(entryPath) { - if (!existsSync(entryPath)) return; - let body = readFileSync(entryPath, "utf8"); - const seen = new Set(); - - while (true) { - const match = body.match(CHUNK_IMPORT_RE); - if (!match) break; - const [importLine, names, chunkBase] = match; - const chunkPath = join(distDir, `${chunkBase}.d.ts`); - if (!existsSync(chunkPath)) { - // Strip the import to avoid infinite loop - body = body.replace(importLine, ""); - continue; - } - seen.add(chunkPath); - - let chunkBody = readFileSync(chunkPath, "utf8"); - - // The chunk ends with: export { Transport as i, DeviceStatusEnum as n, ... }; - // Parse the export aliases so we can rewrite the entry's import bindings. - const exportMatch = chunkBody.match(/^export\s*\{([^}]+)\};\s*$/m); - const aliasMap = new Map(); // letter -> original - if (exportMatch) { - for (const part of exportMatch[1].split(",")) { - const m = part.trim().match(/^(\w+)\s+as\s+(\w+)$/); - if (m) aliasMap.set(m[2], m[1]); - } - // Strip the export line — declarations stay, exports go. - chunkBody = chunkBody.replace(exportMatch[0], ""); - } - - // Rewrite each `letter as Original` import → just `Original` (chunk - // declares it under that name once we've inlined). - const renames = []; - for (const part of names.split(",")) { - const m = part.trim().match(/^(\w+)\s+as\s+(\w+)$/); - if (m) renames.push([m[1], m[2]]); // [letter, original] - } - - body = body.replace(importLine, chunkBody.trim() + "\n"); - - // Inside the now-inlined chunk text, identifiers were declared under - // their original names already (declare class Transport, etc.) — no - // letter rewriting needed inside. - } - - writeFileSync(entryPath, body, "utf8"); -} - -function inlineAllEntries() { - for (const entry of KNOWN_ENTRIES) { - inlineChunks(join(distDir, `${entry}.d.ts`)); - } -} - -function deleteOrphanedChunks() { - const files = readdirSync(distDir); - for (const f of files) { - if (!f.endsWith(".d.ts")) continue; - const match = f.match(/^([A-Za-z]+)-[A-Za-z0-9_-]+\.d\.ts$/); - if (!match) continue; - if (KNOWN_ENTRIES.includes(match[1])) continue; - // Check no entry still references this chunk - let referenced = false; - for (const entry of KNOWN_ENTRIES) { - const p = join(distDir, `${entry}.d.ts`); - if (!existsSync(p)) continue; - if ( - readFileSync(p, "utf8").includes(`./${f.replace(/\.d\.ts$/, ".js")}`) - ) { - referenced = true; - break; - } - } - if (!referenced) unlinkSync(join(distDir, f)); - } -} - -function patchSyntheticNamespaces() { - const modPath = join(distDir, "mod.d.ts"); - let body; - try { - body = readFileSync(modPath, "utf8"); - } catch { - return; - } - - // Strip the synthetic namespace aliases from the export statement. - body = body.replace(/[A-Za-z_]+_d_exports as Types,?\s*/g, ""); - body = body.replace(/[A-Za-z_]+_d_exports as Utils,?\s*/g, ""); - - // Strip `type` modifiers from re-exports inside `export { ... };` lines. - // tsdown's downstream consumers (rolldown dts) drop the `type` modifier - // on imports; they then look for value exports under the same name and - // hit "Missing export" when we re-export as `type X`. Stripping the - // modifier keeps the bindings recognized as both value and type - // (interfaces/types still work; rolldown treats them as namespace-only). - body = body.replace(/export\s*\{([^}]+)\}\s*;/g, (_match, list) => { - const cleaned = list.replace(/\btype\s+/g, ""); - return `export {${cleaned}};`; - }); - - // Append explicit namespace declarations. - const blocks = []; - - blocks.push("declare namespace Types {"); - for (const v of TYPES_MEMBERS.values) blocks.push(` export { ${v} };`); - for (const t of TYPES_MEMBERS.types) blocks.push(` export type { ${t} };`); - blocks.push("}"); - blocks.push("export { Types };"); - - blocks.push("declare namespace Utils {"); - for (const v of UTILS_MEMBERS.values) blocks.push(` export { ${v} };`); - for (const [alias, target] of Object.entries(UTILS_MEMBERS.aliases ?? {})) { - blocks.push(` export { ${target} as ${alias} };`); - } - blocks.push("}"); - blocks.push("export { Utils };"); - - body = `${body.trimEnd()}\n\n${blocks.join("\n")}\n`; - writeFileSync(modPath, body, "utf8"); -} - -renameEntries(); -inlineAllEntries(); -patchSyntheticNamespaces(); -deleteOrphanedChunks(); diff --git a/packages/sdk/src/core/client/MeshClient.handshake.test.ts b/packages/sdk/src/core/client/MeshClient.handshake.test.ts deleted file mode 100644 index 15f9df93e..000000000 --- a/packages/sdk/src/core/client/MeshClient.handshake.test.ts +++ /dev/null @@ -1,228 +0,0 @@ -import { create, fromBinary } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { - FirmwareTooOldError, - HandshakeTimeoutError, -} from "../errors/MeshError.ts"; -import { createFakeTransport } from "../testing/createFakeTransport.ts"; -import { DeviceStatusEnum } from "../transport/Transport.ts"; -import { MeshClient } from "./MeshClient.ts"; -import { - CONFIG_NONCE, - HANDSHAKE_IDLE_TIMEOUT_MS, - HANDSHAKE_STAGE_MAX_MS, - HEARTBEAT_INTERVAL_MS, - NODEDB_NONCE, -} from "./handshake.ts"; - -const decodeSent = (sent: Uint8Array[]) => - sent.map((bytes) => fromBinary(Protobuf.Mesh.ToRadioSchema, bytes)); - -const wantConfigIds = (sent: Uint8Array[]) => - decodeSent(sent) - .filter((m) => m.payloadVariant.case === "wantConfigId") - .map((m) => m.payloadVariant.value); - -const heartbeatNonces = (sent: Uint8Array[]) => - decodeSent(sent).flatMap((m) => - m.payloadVariant.case === "heartbeat" ? [m.payloadVariant.value.nonce] : [], - ); - -describe("MeshClient handshake", () => { - beforeEach(() => { - vi.useFakeTimers(); - }); - - afterEach(() => { - vi.useRealTimers(); - }); - - async function setup() { - const fake = createFakeTransport(); - const client = new MeshClient({ transport: fake.transport }); - const done = client.configure(); - done.catch(() => {}); - await vi.advanceTimersByTimeAsync(500); - return { ...fake, client, done }; - } - - it("asks for config first, then the NodeDB after a heartbeat", async () => { - const { client, respond, sent, done } = await setup(); - expect(wantConfigIds(sent)).toEqual([CONFIG_NONCE]); - - respond.withMyNodeInfo({ myNodeNum: 0x1234 }); - - respond.withConfigCompleteId(CONFIG_NONCE); - await vi.advanceTimersByTimeAsync(1_000); - - const kinds = decodeSent(sent).map((m) => m.payloadVariant.case); - // "packet" is the set-time admin message sent when my_info arrives. - expect(kinds).toEqual([ - "wantConfigId", - "packet", - "heartbeat", - "wantConfigId", - ]); - expect(wantConfigIds(sent)).toEqual([CONFIG_NONCE, NODEDB_NONCE]); - expect(client.device.status.value).toBe(DeviceStatusEnum.DeviceConfiguring); - - respond.withConfigCompleteId(NODEDB_NONCE); - await vi.advanceTimersByTimeAsync(10); - await expect(done).resolves.toBe(NODEDB_NONCE); - expect(client.device.status.value).toBe(DeviceStatusEnum.DeviceConfigured); - }); - - it("ignores a config_complete_id that does not match the stage", async () => { - const { client, respond, sent } = await setup(); - respond.withConfigCompleteId(NODEDB_NONCE); - respond.withConfigCompleteId(12345); - await vi.advanceTimersByTimeAsync(1_000); - expect(wantConfigIds(sent)).toEqual([CONFIG_NONCE]); - expect(client.device.status.value).toBe(DeviceStatusEnum.DeviceConfiguring); - }); - - it("sets the device clock when my_info arrives", async () => { - const { respond, sent } = await setup(); - respond.withMyNodeInfo({ myNodeNum: 0x1234 }); - await vi.advanceTimersByTimeAsync(1_000); - - const packets = decodeSent(sent).flatMap((m) => - m.payloadVariant.case === "packet" ? [m.payloadVariant.value] : [], - ); - expect(packets).toHaveLength(1); - const packet = packets[0]!; - expect(packet.to).toBe(0x1234); - expect(packet.wantAck).toBe(false); - if (packet.payloadVariant.case !== "decoded") throw new Error("encrypted"); - const admin = fromBinary( - Protobuf.Admin.AdminMessageSchema, - packet.payloadVariant.value.payload, - ); - expect(admin.payloadVariant.case).toBe("setTimeOnly"); - }); - - it("fails on a stall without asking again in the same session", async () => { - const { sent, done } = await setup(); - await vi.advanceTimersByTimeAsync(HANDSHAKE_IDLE_TIMEOUT_MS); - await expect(done).rejects.toBeInstanceOf(HandshakeTimeoutError); - expect(wantConfigIds(sent)).toEqual([CONFIG_NONCE]); - }); - - it("is not kept alive by live mesh traffic", async () => { - const { respond, done } = await setup(); - for (let i = 0; i < 4; i++) { - await vi.advanceTimersByTimeAsync(HANDSHAKE_IDLE_TIMEOUT_MS / 4); - respond.withMeshPacket( - create(Protobuf.Mesh.MeshPacketSchema, { from: 7 }), - ); - } - await expect(done).rejects.toBeInstanceOf(HandshakeTimeoutError); - }); - - it("fails a stage that runs past its hard cap", async () => { - const { respond, done } = await setup(); - let elapsed = 0; - let num = 1; - while (elapsed <= HANDSHAKE_STAGE_MAX_MS) { - await vi.advanceTimersByTimeAsync(HANDSHAKE_IDLE_TIMEOUT_MS - 1_000); - elapsed += HANDSHAKE_IDLE_TIMEOUT_MS - 1_000; - respond.withNodeInfo({ num: num++ }); - } - await expect(done).rejects.toBeInstanceOf(HandshakeTimeoutError); - }); - - it("fails the config stage when my_info never arrived", async () => { - const { respond, sent, done } = await setup(); - respond.withConfigCompleteId(CONFIG_NONCE); - await vi.advanceTimersByTimeAsync(1_000); - await expect(done).rejects.toBeInstanceOf(HandshakeTimeoutError); - expect(wantConfigIds(sent)).toEqual([CONFIG_NONCE]); - }); - - it("keeps waiting while frames keep arriving", async () => { - const { respond, sent, done } = await setup(); - for (let i = 0; i < 5; i++) { - await vi.advanceTimersByTimeAsync(HANDSHAKE_IDLE_TIMEOUT_MS - 1_000); - respond.withNodeInfo({ num: i + 1 }); - } - await vi.advanceTimersByTimeAsync(10); - expect(wantConfigIds(sent)).toEqual([CONFIG_NONCE]); - let settled = false; - done.then( - () => (settled = true), - () => (settled = true), - ); - await vi.advanceTimersByTimeAsync(0); - expect(settled).toBe(false); - }); - - it("sends counting heartbeats from 2 once configured", async () => { - const { respond, sent } = await setup(); - respond.withMyNodeInfo({ myNodeNum: 0x1234 }); - respond.withConfigCompleteId(CONFIG_NONCE); - await vi.advanceTimersByTimeAsync(1_000); - respond.withConfigCompleteId(NODEDB_NONCE); - await vi.advanceTimersByTimeAsync(HEARTBEAT_INTERVAL_MS * 2 + 1_000); - - const nonces = heartbeatNonces(sent); - expect(nonces).toEqual([2, 3, 4]); - expect(nonces).not.toContain(0); - expect(nonces).not.toContain(1); - }); - - it("restarts from the config stage when the device reboots", async () => { - const { client, respond, sent } = await setup(); - respond.withMyNodeInfo({ myNodeNum: 0x1234 }); - respond.withConfigCompleteId(CONFIG_NONCE); - await vi.advanceTimersByTimeAsync(1_000); - respond.withConfigCompleteId(NODEDB_NONCE); - await vi.advanceTimersByTimeAsync(10); - expect(client.device.status.value).toBe(DeviceStatusEnum.DeviceConfigured); - - respond.withRaw( - create(Protobuf.Mesh.FromRadioSchema, { - payloadVariant: { case: "rebooted", value: true }, - }), - ); - await vi.advanceTimersByTimeAsync(500); - expect(wantConfigIds(sent)).toEqual([ - CONFIG_NONCE, - NODEDB_NONCE, - CONFIG_NONCE, - ]); - expect(client.device.status.value).toBe(DeviceStatusEnum.DeviceConfiguring); - }); - - it("refuses firmware older than the absolute minimum", async () => { - const { client, respond, done } = await setup(); - respond.withRaw( - create(Protobuf.Mesh.FromRadioSchema, { - payloadVariant: { - case: "metadata", - value: { firmwareVersion: "2.3.2.abc" }, - }, - }), - ); - await vi.advanceTimersByTimeAsync(10); - await expect(done).rejects.toBeInstanceOf(FirmwareTooOldError); - expect(client.device.firmwareSupport.value).toBe("tooOld"); - }); - - it("does not take a remote node's metadata as this device's", async () => { - const { client } = await setup(); - client.events.onDeviceMetadataPacket.dispatch({ - id: 1, - from: 0x99, - to: 0, - type: "direct", - channel: 0, - rxTime: new Date(), - data: create(Protobuf.Mesh.DeviceMetadataSchema, { - firmwareVersion: "2.3.2", - }), - }); - expect(client.device.metadata.value).toBeUndefined(); - expect(client.device.firmwareSupport.value).toBe("unknown"); - }); -}); diff --git a/packages/sdk/src/core/client/MeshClient.progress.test.ts b/packages/sdk/src/core/client/MeshClient.progress.test.ts deleted file mode 100644 index 9fd7d9b4c..000000000 --- a/packages/sdk/src/core/client/MeshClient.progress.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import { createFakeTransport } from "../testing/createFakeTransport.ts"; -import { MeshClient } from "./MeshClient.ts"; -import { CONFIG_NONCE, NODEDB_NONCE } from "./handshake.ts"; - -describe("MeshClient.progress", () => { - afterEach(() => { - vi.useRealTimers(); - }); - - it("starts in the idle phase before configure() is called", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - expect(client.progress.value.phase).toBe("idle"); - }); - - it("flips to configuring with empty counters when configure() runs", async () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - client.configure().catch(() => {}); - expect(client.progress.value.phase).toBe("configuring"); - expect(client.progress.value).toEqual({ - phase: "configuring", - received: { - config: 0, - modules: 0, - channels: 0, - nodes: 0, - myInfo: false, - metadata: false, - }, - }); - }); - - it("tallies inbound packets onto the configuring counters", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - client.configure().catch(() => {}); - - client.events.onConfigPacket.dispatch( - create(Protobuf.Config.ConfigSchema, {}), - ); - client.events.onConfigPacket.dispatch( - create(Protobuf.Config.ConfigSchema, {}), - ); - client.events.onChannelPacket.dispatch( - create(Protobuf.Channel.ChannelSchema, {}), - ); - client.events.onNodeInfoPacket.dispatch( - create(Protobuf.Mesh.NodeInfoSchema, {}), - ); - client.events.onMyNodeInfo.dispatch( - create(Protobuf.Mesh.MyNodeInfoSchema, {}), - ); - - const cur = client.progress.value; - if (cur.phase !== "configuring") - throw new Error("expected configuring phase"); - expect(cur.received.config).toBe(2); - expect(cur.received.channels).toBe(1); - expect(cur.received.nodes).toBe(1); - expect(cur.received.myInfo).toBe(true); - expect(cur.received.modules).toBe(0); - }); - - it("flips to configured only after the NodeDB stage completes", async () => { - vi.useFakeTimers(); - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport, heartbeatIntervalMs: false }); - client.configure().catch(() => {}); - client.events.onConfigPacket.dispatch( - create(Protobuf.Config.ConfigSchema, {}), - ); - client.events.onMyNodeInfo.dispatch( - create(Protobuf.Mesh.MyNodeInfoSchema, { myNodeNum: 0x1234 }), - ); - client.events.onConfigComplete.dispatch(CONFIG_NONCE); - expect(client.progress.value.phase).toBe("configuring"); - - await vi.advanceTimersByTimeAsync(1_000); - client.events.onConfigComplete.dispatch(NODEDB_NONCE); - - const cur = client.progress.value; - expect(cur.phase).toBe("configured"); - if (cur.phase !== "configured") throw new Error("unreachable"); - expect(cur.received.config).toBe(1); - }); - - it("ignores packets that arrive while idle (post-completion)", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - // not calling configure() — phase is idle - client.events.onConfigPacket.dispatch( - create(Protobuf.Config.ConfigSchema, {}), - ); - expect(client.progress.value.phase).toBe("idle"); - }); - - it("resets counters when configure() runs again", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - client.configure().catch(() => {}); - client.events.onConfigPacket.dispatch( - create(Protobuf.Config.ConfigSchema, {}), - ); - client.events.onConfigComplete.dispatch(CONFIG_NONCE); - client.configure().catch(() => {}); - expect(client.progress.value).toEqual({ - phase: "configuring", - received: { - config: 0, - modules: 0, - channels: 0, - nodes: 0, - myInfo: false, - metadata: false, - }, - }); - }); -}); diff --git a/packages/sdk/src/core/client/MeshClient.storageScope.test.ts b/packages/sdk/src/core/client/MeshClient.storageScope.test.ts deleted file mode 100644 index 41d0b0139..000000000 --- a/packages/sdk/src/core/client/MeshClient.storageScope.test.ts +++ /dev/null @@ -1,311 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { describe, expect, it, vi } from "vitest"; -import { InMemoryDraftRepository } from "../../features/chat/infrastructure/repositories/InMemoryDraftRepository.ts"; -import { InMemoryMessageRepository } from "../../features/chat/infrastructure/repositories/InMemoryMessageRepository.ts"; -import type { Message } from "../../features/chat/domain/Message.ts"; -import { MessageState } from "../../features/chat/domain/MessageState.ts"; -import { InMemoryNodesRepository } from "../../features/nodes/infrastructure/repositories/InMemoryNodesRepository.ts"; -import { InMemoryTelemetryRepository } from "../../features/telemetry/infrastructure/repositories/InMemoryTelemetryRepository.ts"; -import { createFakeTransport } from "../testing/createFakeTransport.ts"; -import { ChannelNumber } from "../types.ts"; -import { MeshClient } from "./MeshClient.ts"; - -const NODE_A = 0x0a0a0a0a; -const NODE_B = 0x0b0b0b0b; -const UNKNOWN = -1; -const PRIMARY = { kind: "channel", channel: ChannelNumber.Primary } as const; - -/** - * Test repository that keeps one in-memory repository per scope and routes - * every call to the one `setScope` last selected, like the sqlocal adapters - * do with their `device_id` column. - */ -function scoped(initial: number, make: () => T) { - const byScope = new Map(); - let scope = initial; - const at = (s: number): T => { - let repo = byScope.get(s); - if (!repo) { - repo = make(); - byScope.set(s, repo); - } - return repo; - }; - const repo = new Proxy({} as T & { setScope(s: number): void }, { - get(_, prop) { - if (prop === "setScope") return (s: number) => (scope = s); - const target = at(scope); - const value = Reflect.get(target, prop); - return typeof value === "function" ? value.bind(target) : value; - }, - }); - return { repo, at, scope: () => scope }; -} - -function message(id: number, text: string): Message { - return { - id, - from: 1, - to: 0xffffffff, - channel: ChannelNumber.Primary, - rxTime: new Date(id * 1000), - type: "broadcast", - text, - state: MessageState.Ack, - }; -} - -function battery(nodeNum: number, level: number) { - return { - nodeNum, - time: new Date(level * 1000), - kind: "deviceMetrics" as const, - value: create(Protobuf.Telemetry.DeviceMetricsSchema, { - batteryLevel: level, - }), - }; -} - -async function seed( - repos: ReturnType["repos"], - scope: number, - tag: string, - level: number, -) { - await repos.messages.at(scope).append(message(level, `${tag} message`)); - await repos.drafts.at(scope).save(PRIMARY, `${tag} draft`); - await repos.nodes - .at(scope) - .upsert({ num: level, isFavorite: false, isIgnored: false }); - await repos.telemetry.at(scope).append(battery(42, level)); -} - -function setup(options: { opened: number; nodeNum?: number }) { - const repos = { - messages: scoped(options.opened, () => new InMemoryMessageRepository()), - drafts: scoped(options.opened, () => new InMemoryDraftRepository()), - nodes: scoped(options.opened, () => new InMemoryNodesRepository()), - telemetry: scoped(options.opened, () => new InMemoryTelemetryRepository()), - }; - const fake = createFakeTransport(); - const build = () => - new MeshClient({ - transport: fake.transport, - heartbeatIntervalMs: false, - storageScope: "node", - storageNodeNum: options.nodeNum, - chat: { - repository: repos.messages.repo, - draftRepository: repos.drafts.repo, - }, - nodes: { repository: repos.nodes.repo }, - telemetry: { repository: repos.telemetry.repo }, - }); - return { repos, fake, build }; -} - -const tick = () => new Promise((r) => setTimeout(r, 10)); - -function view(client: MeshClient) { - return { - messages: client.chat.messages(ChannelNumber.Primary), - draft: client.chat.drafts.get(PRIMARY), - history: client.telemetry.history(42), - latest: client.telemetry.latest(42), - }; -} - -function snapshot(client: MeshClient, v: ReturnType) { - return { - messages: v.messages.value.map((m) => m.text), - draft: v.draft.value, - nodes: client.nodes.list.value.map((n) => n.num), - history: v.history.value.map( - (r) => (r.value as { batteryLevel?: number }).batteryLevel, - ), - latest: (v.latest.value?.value as { batteryLevel?: number } | undefined) - ?.batteryLevel, - }; -} - -describe("MeshClient storage scope", () => { - it("rescopes to the node my_info reports and reloads everything from it", async () => { - const { repos, fake, build } = setup({ opened: NODE_A, nodeNum: NODE_A }); - await seed(repos, NODE_A, "A", 10); - await seed(repos, NODE_B, "B", 20); - - const client = build(); - const v = view(client); - await tick(); - expect(snapshot(client, v)).toEqual({ - messages: ["A message"], - draft: "A draft", - nodes: [10], - history: [10], - latest: 10, - }); - - fake.respond.withMyNodeInfo({ myNodeNum: NODE_B }); - await tick(); - // The same signals now carry the new node's history. - expect(snapshot(client, v)).toEqual({ - messages: ["B message"], - draft: "B draft", - nodes: [20], - history: [20], - latest: 20, - }); - - // Later writes land in the new scope and leave the old one alone. - client.chat.drafts.set(PRIMARY, "B edited"); - await tick(); - expect(repos.drafts.scope()).toBe(NODE_B); - expect(await repos.drafts.at(NODE_B).load(PRIMARY)).toBe("B edited"); - expect(await repos.drafts.at(NODE_A).load(PRIMARY)).toBe("A draft"); - expect(repos.messages.scope()).toBe(NODE_B); - expect(repos.nodes.scope()).toBe(NODE_B); - expect(repos.telemetry.scope()).toBe(NODE_B); - }); - - it("opens the node's history once my_info names it when the node was unknown", async () => { - const { repos, fake, build } = setup({ opened: UNKNOWN }); - await seed(repos, NODE_A, "A", 10); - - const client = build(); - const v = view(client); - await tick(); - expect(snapshot(client, v)).toEqual({ - messages: [], - draft: "", - nodes: [], - history: [], - latest: undefined, - }); - - fake.respond.withMyNodeInfo({ myNodeNum: NODE_A }); - await tick(); - expect(snapshot(client, v)).toEqual({ - messages: ["A message"], - draft: "A draft", - nodes: [10], - history: [10], - latest: 10, - }); - }); - - it("keeps its state when my_info reports the node it was opened for", async () => { - const { repos, fake, build } = setup({ opened: NODE_A, nodeNum: NODE_A }); - await seed(repos, NODE_A, "A", 10); - - const client = build(); - const rescope = vi.spyOn(client, "rescopeStorage"); - client.chat.drafts.set(PRIMARY, "typing"); - fake.respond.withMyNodeInfo({ myNodeNum: NODE_A }); - // A reboot re-runs the handshake and sends my_info again. - fake.respond.withMyNodeInfo({ myNodeNum: NODE_A }); - await tick(); - - expect(rescope).not.toHaveBeenCalled(); - expect(client.chat.drafts.get(PRIMARY).value).toBe("typing"); - }); - - it("rescopes once when my_info repeats a new node", async () => { - const { fake, build } = setup({ opened: UNKNOWN }); - const client = build(); - const rescope = vi.spyOn(client, "rescopeStorage"); - fake.respond.withMyNodeInfo({ myNodeNum: NODE_A }); - fake.respond.withMyNodeInfo({ myNodeNum: NODE_A }); - await tick(); - expect(rescope).toHaveBeenCalledTimes(1); - expect(rescope).toHaveBeenCalledWith(NODE_A); - }); - - it("drops an old-scope load that finishes after the rescope", async () => { - const { repos, fake, build } = setup({ opened: NODE_A, nodeNum: NODE_A }); - await seed(repos, NODE_A, "A", 10); - await seed(repos, NODE_B, "B", 20); - - let release!: () => void; - const gate = new Promise((r) => (release = r)); - const slowA = repos.messages.at(NODE_A); - const loadRecent = slowA.loadRecent.bind(slowA); - slowA.loadRecent = async (key, limit) => { - await gate; - return loadRecent(key, limit); - }; - - const client = build(); - const messages = client.chat.messages(ChannelNumber.Primary); - fake.respond.withMyNodeInfo({ myNodeNum: NODE_B }); - await tick(); - expect(messages.value.map((m) => m.text)).toEqual(["B message"]); - - release(); - await tick(); - expect(messages.value.map((m) => m.text)).toEqual(["B message"]); - }); - - it("refiles sent direct messages in the new scope", async () => { - const { repos, fake, build } = setup({ opened: UNKNOWN }); - const refileA = vi.spyOn(repos.messages.at(NODE_A), "refileSentDirect"); - const refileUnknown = vi.spyOn( - repos.messages.at(UNKNOWN), - "refileSentDirect", - ); - build(); - fake.respond.withMyNodeInfo({ myNodeNum: NODE_A }); - await tick(); - expect(refileA).toHaveBeenCalledWith(NODE_A); - expect(refileUnknown).not.toHaveBeenCalled(); - }); - - it("never rescopes without storageScope", async () => { - const fake = createFakeTransport(); - const client = new MeshClient({ - transport: fake.transport, - heartbeatIntervalMs: false, - }); - const rescope = vi.spyOn(client, "rescopeStorage"); - fake.respond.withMyNodeInfo({ myNodeNum: NODE_A }); - await tick(); - expect(rescope).not.toHaveBeenCalled(); - }); - - it("keeps working with the in-memory repositories", async () => { - const fake = createFakeTransport(); - const client = new MeshClient({ - transport: fake.transport, - heartbeatIntervalMs: false, - storageScope: "node", - }); - const messages = client.chat.messages(ChannelNumber.Primary); - fake.respond.withMyNodeInfo({ myNodeNum: NODE_A }); - await tick(); - - client.chat.drafts.set(PRIMARY, "hello"); - fake.respond.withMeshPacket( - create(Protobuf.Mesh.MeshPacketSchema, { - from: 7, - to: 0xffffffff, - id: 99, - rxTime: 1, - payloadVariant: { - case: "decoded", - value: { - portnum: Protobuf.Portnums.PortNum.TEXT_MESSAGE_APP, - payload: new TextEncoder().encode("hi"), - }, - }, - }), - ); - await tick(); - expect(messages.value.map((m) => m.text)).toEqual(["hi"]); - - // A rescope with nothing to scope reloads what the session stored. - client.rescopeStorage(NODE_B); - await tick(); - expect(messages.value.map((m) => m.text)).toEqual(["hi"]); - expect(client.chat.drafts.get(PRIMARY).value).toBe("hello"); - }); -}); diff --git a/packages/sdk/src/core/client/MeshClient.ts b/packages/sdk/src/core/client/MeshClient.ts deleted file mode 100644 index ee49d0ba8..000000000 --- a/packages/sdk/src/core/client/MeshClient.ts +++ /dev/null @@ -1,635 +0,0 @@ -import { create, toBinary } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import type { Logger } from "tslog"; -import { Constants } from "../constants/index.ts"; -import { EventBus } from "../event-bus/EventBus.ts"; -import { - FirmwareTooOldError, - HandshakeTimeoutError, - PacketTooLargeError, -} from "../errors/MeshError.ts"; -import { firmwareSupport } from "../../features/device/domain/FirmwareVersion.ts"; -import { generatePacketId } from "../identifiers/PacketId.ts"; -import { createLogger } from "../logging/logger.ts"; -import { decodePacket } from "../packet-codec/decodePacket.ts"; -import { Queue } from "../queue/Queue.ts"; -import { createStore, type ReadonlySignal } from "../signals/createStore.ts"; -import type { Transport } from "../transport/Transport.ts"; -import { DeviceStatusEnum } from "../transport/Transport.ts"; -import { - ChannelNumber, - type Destination, - Emitter, - type PacketMetadata, -} from "../types.ts"; -import { Xmodem } from "../xmodem/Xmodem.ts"; -import { - CONFIG_NONCE, - FIRST_HEARTBEAT_NONCE, - HANDSHAKE_FRAME_CASES, - HANDSHAKE_IDLE_TIMEOUT_MS, - HANDSHAKE_SETTLE_MS, - HANDSHAKE_STAGE_MAX_MS, - HEARTBEAT_INTERVAL_MS, - NODEDB_NONCE, - sleep, -} from "./handshake.ts"; -import { ChatClient } from "../../features/chat/index.ts"; -import { ChannelsClient } from "../../features/channels/index.ts"; -import { ConfigClient } from "../../features/config/index.ts"; -import { DeviceClient } from "../../features/device/index.ts"; -import { FilesClient } from "../../features/files/index.ts"; -import { NodesClient } from "../../features/nodes/index.ts"; -import { PositionClient } from "../../features/position/index.ts"; -import { TelemetryClient } from "../../features/telemetry/index.ts"; -import type { TelemetryClientOptions } from "../../features/telemetry/index.ts"; -import { TraceRouteClient } from "../../features/traceroute/index.ts"; - -import type { ChatClientOptions } from "../../features/chat/ChatClient.ts"; -import type { NodesClientOptions } from "../../features/nodes/NodesClient.ts"; - -export interface MeshClientOptions { - transport: Transport; - configId?: number; - logger?: Logger; - chat?: ChatClientOptions; - nodes?: NodesClientOptions; - telemetry?: TelemetryClientOptions; - /** - * How the chat, draft, nodes and telemetry repositories are scoped. With - * `"node"` they keep one history per radio, whatever the transport: as - * soon as the handshake's my_info names the radio, the client calls - * {@link MeshClient.rescopeStorage} with its node number, unless the - * repositories were already opened for that node (`storageNodeNum`). - * my_info is the first handshake frame, so this happens before the NodeDB - * and any message arrives. Left out, the repositories are never rescoped. - */ - storageScope?: "node"; - /** - * The node number the repositories were opened for, when the caller knows - * it (e.g. saved from an earlier connection). Only read with - * `storageScope: "node"`. - */ - storageNodeNum?: number; - /** - * Keep-alive interval once the handshake completes. Defaults to - * {@link HEARTBEAT_INTERVAL_MS}; `false` disables the automatic heartbeat. - */ - heartbeatIntervalMs?: number | false; -} - -type HandshakeStage = "idle" | "config" | "settling" | "nodedb" | "complete"; - -/** - * Per-section / per-event tally of what has streamed in since the most - * recent `configure()` call. UI surfaces use this for live "received X - * channels, Y nodes" feedback during the handshake. - */ -export interface ConnectionProgressCounters { - config: number; - modules: number; - channels: number; - nodes: number; - myInfo: boolean; - metadata: boolean; -} - -/** - * Connection progress signal shape. The state machine moves - * `idle → configuring → configured` once `configure()` runs and the - * device finishes both handshake stages. - */ -export type ConnectionProgress = - | { phase: "idle" } - | { phase: "configuring"; received: ConnectionProgressCounters } - | { phase: "configured"; received: ConnectionProgressCounters }; - -const EMPTY_COUNTERS: ConnectionProgressCounters = { - config: 0, - modules: 0, - channels: 0, - nodes: 0, - myInfo: false, - metadata: false, -}; - -/** - * Orchestrator for a single connected Meshtastic device. - * - * Owns the transport, event bus, queue, and xmodem instances. Exposes one - * client per feature slice; slice clients consume events from the bus and - * publish signal-backed state that UI layers subscribe to. - */ -export class MeshClient { - public readonly log: Logger; - public readonly transport: Transport; - public readonly events: EventBus; - public readonly queue: Queue; - public readonly xModem: Xmodem; - public configId: number; - - public readonly device: DeviceClient; - public readonly chat: ChatClient; - public readonly nodes: NodesClient; - public readonly channels: ChannelsClient; - public readonly config: ConfigClient; - public readonly telemetry: TelemetryClient; - public readonly position: PositionClient; - public readonly traceroute: TraceRouteClient; - public readonly files: FilesClient; - - /** - * Live connection-handshake progress. Resets to `configuring` with empty - * counters when `configure()` is called; tallies each inbound config / - * module / channel / node packet; flips to `configured` when the device - * sends `configCompleteId`. - */ - public readonly progress: ReadonlySignal; - private readonly progressStore = createStore({ - phase: "idle", - }); - - private _heartbeatIntervalId: ReturnType | undefined; - private readonly heartbeatIntervalMs: number | false; - private heartbeatNonce = FIRST_HEARTBEAT_NONCE; - private storageNodeNum: number | undefined; - - private handshakeStage: HandshakeStage = "idle"; - private handshakeTimer: ReturnType | undefined; - private handshakeStageTimer: ReturnType | undefined; - private handshakeHasMyInfo = false; - private handshakeTimeSent = false; - private handshakeWaiters: { - resolve: (nonce: number) => void; - reject: (error: unknown) => void; - }[] = []; - - constructor(options: MeshClientOptions) { - this.log = options.logger ?? createLogger("MeshClient"); - this.transport = options.transport; - this.events = new EventBus(); - this.queue = new Queue(); - this.xModem = new Xmodem(this.sendRaw.bind(this)); - this.configId = options.configId ?? generatePacketId(); - this.heartbeatIntervalMs = - options.heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS; - this.storageNodeNum = options.storageNodeNum; - - // Subscribed before the slice clients so the repositories already point - // at the new scope when their own my_info handlers run (ChatClient - // refiles sent direct messages there). The handler only runs once a frame - // arrives, after the slices below exist. - if (options.storageScope === "node") { - this.events.onMyNodeInfo.subscribe((info) => { - if (info.myNodeNum <= 0 || info.myNodeNum === this.storageNodeNum) - return; - this.rescopeStorage(info.myNodeNum); - }); - } - - this.device = new DeviceClient(this); - this.chat = new ChatClient(this, options.chat); - this.nodes = new NodesClient(this, options.nodes); - this.channels = new ChannelsClient(this); - this.config = new ConfigClient(this); - this.telemetry = new TelemetryClient(this, options.telemetry); - this.position = new PositionClient(this); - this.traceroute = new TraceRouteClient(this); - this.files = new FilesClient(this); - - this.progress = this.progressStore.read; - this.wireProgressTracking(); - this.wireHandshake(); - - this.events.onDeviceStatus.subscribe((status) => { - if (status === DeviceStatusEnum.DeviceDisconnected) { - this.stopHeartbeat(); - this.failHandshake(new Error("Device connection lost")); - this.complete(); - } - }); - - this.transport.fromDevice.pipeTo(decodePacket(this)); - } - - public get myNodeNum(): number { - return this.device.myNodeNum.value ?? 0; - } - - /** - * Points every slice's repositories at the history stored for `nodeNum` - * and reloads from it what the slices had loaded (open conversations, - * drafts, the node list, telemetry), dropping what they held for the old - * scope. Signals already handed out stay valid. Repositories without a - * `setScope` (the in-memory defaults) keep their contents. - */ - public rescopeStorage(nodeNum: number): void { - this.log.debug( - Emitter[Emitter.Configure], - `Storage scope ${this.storageNodeNum ?? "none"} -> ${nodeNum}`, - ); - this.storageNodeNum = nodeNum; - this.chat.rescope(nodeNum); - this.nodes.rescope(nodeNum); - this.telemetry.rescope(nodeNum); - } - - /** - * Run the two-stage handshake. Resolves once the device has sent both - * config and NodeDB; rejects with {@link HandshakeTimeoutError} if it stops - * responding. - */ - public async connect(): Promise { - this.updateDeviceStatus(DeviceStatusEnum.DeviceConnecting); - await this.configure(); - } - - /** - * Start (or restart, e.g. after `rebooted`) the handshake. Calling it while - * a handshake is already running restarts it; every pending caller settles - * when the restarted handshake does. - */ - public configure(): Promise { - this.log.debug( - Emitter[Emitter.Configure], - "⚙️ Requesting device configuration", - ); - this.stopHeartbeat(); - this.updateDeviceStatus(DeviceStatusEnum.DeviceConfiguring); - this.progressStore.write.value = { - phase: "configuring", - received: { ...EMPTY_COUNTERS }, - }; - - const done = new Promise((resolve, reject) => { - this.handshakeWaiters.push({ resolve, reject }); - }); - this.handshakeTimeSent = false; - this.handshakeHasMyInfo = false; - this.startHandshakeStage("config"); - return done; - } - - private startHandshakeStage(stage: "config" | "nodedb"): void { - this.handshakeStage = stage; - this.sendWantConfig(stage === "config" ? CONFIG_NONCE : NODEDB_NONCE); - this.armHandshakeTimer(); - if (this.handshakeStageTimer !== undefined) { - clearTimeout(this.handshakeStageTimer); - } - this.handshakeStageTimer = setTimeout( - () => this.onHandshakeStall(), - HANDSHAKE_STAGE_MAX_MS, - ); - } - - private sendWantConfig(nonce: number): void { - const toRadio = create(Protobuf.Mesh.ToRadioSchema, { - payloadVariant: { case: "wantConfigId", value: nonce }, - }); - this.sendRaw(toBinary(Protobuf.Mesh.ToRadioSchema, toRadio), undefined, { - expectAck: false, - }).catch((e: unknown) => this.failHandshake(e)); - } - - private armHandshakeTimer(): void { - if (this.handshakeTimer !== undefined) clearTimeout(this.handshakeTimer); - this.handshakeTimer = setTimeout( - () => this.onHandshakeStall(), - HANDSHAKE_IDLE_TIMEOUT_MS, - ); - } - - private clearHandshakeTimer(): void { - if (this.handshakeTimer !== undefined) { - clearTimeout(this.handshakeTimer); - this.handshakeTimer = undefined; - } - if (this.handshakeStageTimer !== undefined) { - clearTimeout(this.handshakeStageTimer); - this.handshakeStageTimer = undefined; - } - } - - private onHandshakeStall(): void { - const stage = this.handshakeStage; - if (stage !== "config" && stage !== "nodedb") return; - this.log.warn( - Emitter[Emitter.Configure], - `⚠️ Handshake stalled in the ${stage} stage`, - ); - this.failHandshake(new HandshakeTimeoutError(stage)); - } - - private failHandshake(error: unknown): void { - this.clearHandshakeTimer(); - if (this.handshakeStage === "complete" || this.handshakeStage === "idle") { - return; - } - this.handshakeStage = "idle"; - const waiters = this.handshakeWaiters; - this.handshakeWaiters = []; - for (const w of waiters) w.reject(error); - } - - private finishHandshake(): void { - this.clearHandshakeTimer(); - this.handshakeStage = "complete"; - const cur = this.progressStore.read.value; - const received = - cur.phase === "configuring" ? cur.received : { ...EMPTY_COUNTERS }; - this.progressStore.write.value = { phase: "configured", received }; - this.updateDeviceStatus(DeviceStatusEnum.DeviceConfigured); - if (this.heartbeatIntervalMs !== false) { - this.setHeartbeatInterval(this.heartbeatIntervalMs); - } - const waiters = this.handshakeWaiters; - this.handshakeWaiters = []; - for (const w of waiters) w.resolve(NODEDB_NONCE); - } - - private wireHandshake(): void { - // Only handshake frames prove the handshake is progressing; live mesh - // traffic would otherwise keep a stalled handshake alive forever. - this.events.onFromRadio.subscribe((fromRadio) => { - if ( - (this.handshakeStage === "config" || - this.handshakeStage === "nodedb") && - HANDSHAKE_FRAME_CASES.has(fromRadio.payloadVariant.case ?? "") - ) { - this.armHandshakeTimer(); - } - }); - - // Set the clock as soon as the device identifies itself, so firmware can - // timestamp the backlog it replays during the handshake. - this.events.onMyNodeInfo.subscribe((info) => { - if (this.handshakeStage === "config") this.handshakeHasMyInfo = true; - if (this.handshakeStage !== "config" || this.handshakeTimeSent) return; - this.handshakeTimeSent = true; - this.sendSetTimeOnly(info.myNodeNum); - }); - - // Refuse firmware older than the Android app's absolute minimum. - this.events.onDeviceMetadataPacket.subscribe((packet) => { - if (this.handshakeStage !== "config" || packet.from !== 0) return; - const version = packet.data.firmwareVersion; - if (firmwareSupport(version) !== "tooOld") return; - this.log.error( - Emitter[Emitter.Configure], - `Firmware ${version} is too old for this client`, - ); - this.failHandshake(new FirmwareTooOldError(version)); - this.disconnect().catch(() => {}); - }); - - this.events.onConfigComplete.subscribe((nonce) => { - if (this.handshakeStage === "config" && nonce === CONFIG_NONCE) { - if (!this.handshakeHasMyInfo) { - // my_info was lost; without it the session has no identity. - this.log.warn( - Emitter[Emitter.Configure], - "⚠️ Config stage completed without my_info", - ); - this.failHandshake(new HandshakeTimeoutError("config")); - return; - } - this.handshakeStage = "settling"; - this.clearHandshakeTimer(); - void this.settleBetweenStages(); - } else if (this.handshakeStage === "nodedb" && nonce === NODEDB_NONCE) { - this.finishHandshake(); - } else { - this.log.debug( - Emitter[Emitter.Configure], - `Ignoring config_complete_id ${nonce} in stage ${this.handshakeStage}`, - ); - } - }); - } - - private async settleBetweenStages(): Promise { - await sleep(HANDSHAKE_SETTLE_MS); - if (this.handshakeStage !== "settling") return; - this.heartbeat().catch(() => { - // best effort; the NodeDB request below re-arms the stall guard - }); - await sleep(HANDSHAKE_SETTLE_MS); - if (this.handshakeStage !== "settling") return; - this.startHandshakeStage("nodedb"); - } - - private sendSetTimeOnly(myNodeNum: number): void { - const admin = create(Protobuf.Admin.AdminMessageSchema, { - payloadVariant: { - case: "setTimeOnly", - value: Math.floor(Date.now() / 1000), - }, - }); - const meshPacket = create(Protobuf.Mesh.MeshPacketSchema, { - payloadVariant: { - case: "decoded", - value: { - payload: toBinary(Protobuf.Admin.AdminMessageSchema, admin), - portnum: Protobuf.Portnums.PortNum.ADMIN_APP, - }, - }, - from: myNodeNum, - to: myNodeNum, - id: generatePacketId(), - }); - const toRadio = create(Protobuf.Mesh.ToRadioSchema, { - payloadVariant: { case: "packet", value: meshPacket }, - }); - this.sendRaw( - toBinary(Protobuf.Mesh.ToRadioSchema, toRadio), - meshPacket.id, - { - expectAck: false, - }, - ).catch((e: unknown) => { - this.log.warn(Emitter[Emitter.Configure], "⚠️ Unable to set time", e); - }); - } - - /** - * Subscribe progress counters to the relevant inbound events. Each - * subscriber bumps the matching field on the current `configuring` - * snapshot; `onConfigComplete` flips the phase to `configured`. - * - * Outside of an active handshake (phase=idle) inbound packets are - * ignored — they belong to a later session that re-runs configure(). - */ - private wireProgressTracking(): void { - const bump = (field: keyof ConnectionProgressCounters): void => { - const cur = this.progressStore.read.value; - if (cur.phase !== "configuring") return; - const next: ConnectionProgressCounters = { - ...cur.received, - [field]: - typeof cur.received[field] === "number" - ? cur.received[field] + 1 - : true, - } as ConnectionProgressCounters; - this.progressStore.write.value = { phase: "configuring", received: next }; - }; - - this.events.onConfigPacket.subscribe(() => bump("config")); - this.events.onModuleConfigPacket.subscribe(() => bump("modules")); - this.events.onChannelPacket.subscribe(() => bump("channels")); - this.events.onNodeInfoPacket.subscribe(() => bump("nodes")); - this.events.onMyNodeInfo.subscribe(() => bump("myInfo")); - this.events.onDeviceMetadataPacket.subscribe(() => bump("metadata")); - } - - public heartbeat(): Promise { - this.log.debug(Emitter[Emitter.Ping], "❤️ Send heartbeat ping to radio"); - const nonce = this.heartbeatNonce; - this.heartbeatNonce = - nonce >= 0xffffffff ? FIRST_HEARTBEAT_NONCE : nonce + 1; - const toRadio = create(Protobuf.Mesh.ToRadioSchema, { - payloadVariant: { case: "heartbeat", value: { nonce } }, - }); - return this.sendRaw( - toBinary(Protobuf.Mesh.ToRadioSchema, toRadio), - undefined, - { - expectAck: false, - }, - ); - } - - public setHeartbeatInterval(interval: number): void { - this.stopHeartbeat(); - this._heartbeatIntervalId = setInterval(() => { - this.heartbeat().catch((err: Error) => { - this.log.error( - Emitter[Emitter.Ping], - `⚠️ Unable to send heartbeat: ${err.message}`, - ); - }); - }, interval); - } - - private stopHeartbeat(): void { - if (this._heartbeatIntervalId !== undefined) { - clearInterval(this._heartbeatIntervalId); - this._heartbeatIntervalId = undefined; - } - } - - public updateDeviceStatus(status: DeviceStatusEnum): void { - if (status !== this.device.status.value) { - this.events.onDeviceStatus.dispatch(status); - } - } - - /** - * Low-level send: wraps an arbitrary payload in a MeshPacket → ToRadio and - * returns the ack promise from the queue. Feature slices delegate here. - */ - public async sendPacket( - byteData: Uint8Array, - portNum: Protobuf.Portnums.PortNum, - destination: Destination, - channel: ChannelNumber = ChannelNumber.Primary, - wantAck = true, - wantResponse = true, - echoResponse = false, - replyId?: number, - emoji?: number, - packetId?: number, - ): Promise { - this.log.trace( - Emitter[Emitter.SendPacket], - `📤 Sending ${Protobuf.Portnums.PortNum[portNum]} to ${destination}`, - ); - - const myNum = this.myNodeNum; - const meshPacket = create(Protobuf.Mesh.MeshPacketSchema, { - payloadVariant: { - case: "decoded", - value: { - payload: byteData, - portnum: portNum, - wantResponse, - emoji, - replyId, - dest: 0, - requestId: 0, - source: 0, - }, - }, - from: myNum, - to: - destination === "broadcast" - ? Constants.broadcastNum - : destination === "self" - ? myNum - : destination, - id: packetId ?? generatePacketId(), - wantAck, - channel, - }); - - const toRadioMessage = create(Protobuf.Mesh.ToRadioSchema, { - payloadVariant: { case: "packet", value: meshPacket }, - }); - - if (echoResponse) { - meshPacket.rxTime = Math.trunc(Date.now() / 1000); - this.events.onMeshPacket.dispatch(meshPacket); - } - return await this.sendRaw( - toBinary(Protobuf.Mesh.ToRadioSchema, toRadioMessage), - meshPacket.id, - ); - } - - /** - * Queue a ToRadio frame. Resolves on the device's ack, or as soon as the - * frame is written when `expectAck` is false (the device never acks - * heartbeats, `want_config_id`, or packets sent without `want_ack`). - */ - public async sendRaw( - toRadio: Uint8Array, - id: number = generatePacketId(), - { expectAck = true }: { expectAck?: boolean } = {}, - ): Promise { - if (toRadio.length > 512) { - throw new PacketTooLargeError(toRadio.length); - } - const settled = this.queue.push({ id, data: toRadio }, { expectAck }); - await this.queue.processQueue(this.transport.toDevice); - return settled; - } - - /** - * Dispatch a `PacketMetadata` echo for locally-composed messages. - */ - public echoLocalMessage( - portnum: Protobuf.Portnums.PortNum, - data: T, - metadata: Omit, "data">, - ): void { - // Reserved for use-cases that need to optimistically reflect outbound into stores. - // Slice use-cases may call bus dispatchers directly; provided here for symmetry. - void portnum; - void data; - void metadata; - } - - public complete(): void { - this.queue.clear(); - } - - public async disconnect(): Promise { - this.log.debug(Emitter[Emitter.Disconnect], "🔌 Disconnecting from device"); - this.stopHeartbeat(); - this.failHandshake(new Error("Device connection lost")); - this.complete(); - await this.transport.toDevice.close(); - await this.transport.disconnect(); - this.updateDeviceStatus(DeviceStatusEnum.DeviceDisconnected); - } -} diff --git a/packages/sdk/src/core/client/handshake.ts b/packages/sdk/src/core/client/handshake.ts deleted file mode 100644 index 18bd265aa..000000000 --- a/packages/sdk/src/core/client/handshake.ts +++ /dev/null @@ -1,55 +0,0 @@ -/** - * PhoneAPI handshake constants, shared with the Android client and the - * Kotlin SDK. - * - * The handshake runs in two stages. Stage one asks for config only (my_info, - * metadata, region presets, config, module config, channels); stage two asks - * for the NodeDB only. Firmware treats these two `want_config_id` values - * specially, so they must not be replaced by random ids. - */ -export const CONFIG_NONCE = 69420; -export const NODEDB_NONCE = 69421; - -/** Pause on each side of the heartbeat sent between the two stages. */ -export const HANDSHAKE_SETTLE_MS = 100; - -/** - * A stage fails if the device goes this long without sending a handshake - * frame. Each handshake frame re-arms the timer, so a large NodeDB never - * trips it while it streams; live mesh traffic does not, so a lost frame - * can't keep a stalled handshake alive. A stall fails the handshake rather - * than resending `want_config_id` in the same session, which the Android - * client found can wedge firmware; callers recover by reopening the - * transport. - */ -export const HANDSHAKE_IDLE_TIMEOUT_MS = 15_000; - -/** Hard cap on one stage, however long frames keep arriving (as Android). */ -export const HANDSHAKE_STAGE_MAX_MS = 10 * HANDSHAKE_IDLE_TIMEOUT_MS; - -/** FromRadio variants that count as handshake progress. */ -export const HANDSHAKE_FRAME_CASES: ReadonlySet = new Set([ - "myInfo", - "nodeInfo", - "config", - "moduleConfig", - "channel", - "metadata", - "fileInfo", - "deviceuiConfig", - "regionPresets", - "configCompleteId", -]); - -export const HEARTBEAT_INTERVAL_MS = 30_000; - -/** - * Heartbeat nonces start at 2 and count up. Firmware 2.7.23+ treats nonce 1 - * as a request to broadcast this node's NodeInfo across the mesh, and drops - * a ToRadio write identical to the previous one, so a fixed nonce of 0 is - * not a reliable keep-alive either. - */ -export const FIRST_HEARTBEAT_NONCE = 2; - -export const sleep = (ms: number): Promise => - new Promise((resolve) => setTimeout(resolve, ms)); diff --git a/packages/sdk/src/core/client/index.ts b/packages/sdk/src/core/client/index.ts deleted file mode 100644 index 623febc01..000000000 --- a/packages/sdk/src/core/client/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { MeshClient } from "./MeshClient.ts"; -export type { MeshClientOptions } from "./MeshClient.ts"; diff --git a/packages/sdk/src/core/constants/index.ts b/packages/sdk/src/core/constants/index.ts deleted file mode 100644 index 0af040951..000000000 --- a/packages/sdk/src/core/constants/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -const broadcastNum = 0xffffffff; - -const minFwVer = 2.2; - -export const Constants = { - broadcastNum, - minFwVer, -} as const; diff --git a/packages/sdk/src/core/errors/MeshError.ts b/packages/sdk/src/core/errors/MeshError.ts deleted file mode 100644 index 6d5233d06..000000000 --- a/packages/sdk/src/core/errors/MeshError.ts +++ /dev/null @@ -1,34 +0,0 @@ -export class MeshError extends Error { - constructor(message: string, options?: ErrorOptions) { - super(message, options); - this.name = "MeshError"; - } -} - -export class TransportClosedError extends MeshError { - constructor() { - super("Transport is closed"); - this.name = "TransportClosedError"; - } -} - -export class PacketTooLargeError extends MeshError { - constructor(size: number) { - super(`Message longer than 512 bytes (got ${size}), it will not be sent!`); - this.name = "PacketTooLargeError"; - } -} - -export class FirmwareTooOldError extends MeshError { - constructor(public readonly firmwareVersion: string) { - super(`Firmware ${firmwareVersion} is too old for this client`); - this.name = "FirmwareTooOldError"; - } -} - -export class HandshakeTimeoutError extends MeshError { - constructor(public readonly stage: "config" | "nodedb") { - super(`Device stopped responding during the ${stage} handshake stage`); - this.name = "HandshakeTimeoutError"; - } -} diff --git a/packages/sdk/src/core/event-bus/EventBus.test.ts b/packages/sdk/src/core/event-bus/EventBus.test.ts deleted file mode 100644 index 926aa730c..000000000 --- a/packages/sdk/src/core/event-bus/EventBus.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { EventBus } from "./EventBus.ts"; - -describe("EventBus", () => { - it("delivers dispatched payloads to subscribers", () => { - const bus = new EventBus(); - const received: number[] = []; - bus.onConfigComplete.subscribe((id) => received.push(id)); - bus.onConfigComplete.dispatch(42); - bus.onConfigComplete.dispatch(43); - expect(received).toEqual([42, 43]); - }); - - it("unsubscribe stops future delivery", () => { - const bus = new EventBus(); - const received: number[] = []; - const unsub = bus.onConfigComplete.subscribe((id) => received.push(id)); - bus.onConfigComplete.dispatch(1); - unsub(); - bus.onConfigComplete.dispatch(2); - expect(received).toEqual([1]); - }); - - it("channels are independent", () => { - const bus = new EventBus(); - const msgs: string[] = []; - const heartbeats: Date[] = []; - bus.onMessagePacket.subscribe((m) => msgs.push(m.data)); - bus.onMeshHeartbeat.subscribe((d) => heartbeats.push(d)); - bus.onMeshHeartbeat.dispatch(new Date(0)); - expect(msgs).toEqual([]); - expect(heartbeats.length).toBe(1); - }); -}); diff --git a/packages/sdk/src/core/event-bus/EventBus.ts b/packages/sdk/src/core/event-bus/EventBus.ts deleted file mode 100644 index f67997628..000000000 --- a/packages/sdk/src/core/event-bus/EventBus.ts +++ /dev/null @@ -1,158 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; -import { SimpleEventDispatcher } from "ste-simple-events"; -import type { DeviceStatusEnum } from "../transport/Transport.ts"; -import type { - LogEventPacket, - PacketMetadata, - UnhandledPayload, -} from "../types.ts"; - -/** The value of one FromRadio payload variant. */ -export type FromRadioValue< - C extends Protobuf.Mesh.FromRadio["payloadVariant"]["case"], -> = Extract["value"]; - -/** - * Typed event bus. Ports the former `EventSystem` into the SDK. - * - * Slice infrastructure subscribes here and materializes signals. External code - * should prefer slice stores over raw bus subscriptions. - */ -export class EventBus { - public readonly onLogEvent = new SimpleEventDispatcher(); - public readonly onFromRadio = - new SimpleEventDispatcher(); - public readonly onMeshPacket = - new SimpleEventDispatcher(); - public readonly onMyNodeInfo = - new SimpleEventDispatcher(); - public readonly onNodeInfoPacket = - new SimpleEventDispatcher(); - public readonly onChannelPacket = - new SimpleEventDispatcher(); - public readonly onConfigPacket = - new SimpleEventDispatcher(); - public readonly onModuleConfigPacket = - new SimpleEventDispatcher(); - public readonly onAtakPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onMessagePacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onRemoteHardwarePacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onPositionPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onUserPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onRoutingPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onDeviceMetadataPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onCannedMessageModulePacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onWaypointPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onAudioPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onDetectionSensorPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onPingPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onIpTunnelPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onPaxcounterPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onSerialPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onStoreForwardPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onRangeTestPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onTelemetryPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onZpsPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onSimulatorPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onTraceRoutePacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onNeighborInfoPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onAtakPluginPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onMapReportPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onPrivatePacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onAtakForwarderPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - /** Every decoded admin message, before it is routed by variant. */ - public readonly onAdminPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onNodeStatusPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onMeshBeaconPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onKeyVerificationPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onAlertPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - /** Decoded packets on a portnum the SDK has no specific handler for. */ - public readonly onUnhandledPacket = new SimpleEventDispatcher< - PacketMetadata - >(); - public readonly onLockdownStatus = - new SimpleEventDispatcher(); - public readonly onRegionPresets = - new SimpleEventDispatcher(); - public readonly onDeviceUiConfig: SimpleEventDispatcher< - FromRadioValue<"deviceuiConfig"> - > = new SimpleEventDispatcher(); - public readonly onFileInfo = - new SimpleEventDispatcher(); - public readonly onClientNotificationPacket = - new SimpleEventDispatcher(); - public readonly onDeviceStatus = - new SimpleEventDispatcher(); - public readonly onLogRecord = - new SimpleEventDispatcher(); - public readonly onMeshHeartbeat = new SimpleEventDispatcher(); - public readonly onDeviceDebugLog = new SimpleEventDispatcher(); - public readonly onPendingSettingsChange = - new SimpleEventDispatcher(); - public readonly onQueueStatus = - new SimpleEventDispatcher(); - public readonly onConfigComplete = new SimpleEventDispatcher(); - public readonly onRebooted = new SimpleEventDispatcher(); -} diff --git a/packages/sdk/src/core/event-bus/index.ts b/packages/sdk/src/core/event-bus/index.ts deleted file mode 100644 index d34e82f30..000000000 --- a/packages/sdk/src/core/event-bus/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { EventBus } from "./EventBus.ts"; diff --git a/packages/sdk/src/core/identifiers/PacketId.ts b/packages/sdk/src/core/identifiers/PacketId.ts deleted file mode 100644 index eef82651b..000000000 --- a/packages/sdk/src/core/identifiers/PacketId.ts +++ /dev/null @@ -1,7 +0,0 @@ -export function generatePacketId(): number { - const seed = crypto.getRandomValues(new Uint32Array(1)); - if (!seed[0]) { - throw new Error("Cannot generate CSPRN"); - } - return Math.floor(seed[0] * 2 ** -32 * 1e9); -} diff --git a/packages/sdk/src/core/logging/logger.ts b/packages/sdk/src/core/logging/logger.ts deleted file mode 100644 index 2c3c0fae4..000000000 --- a/packages/sdk/src/core/logging/logger.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { Logger } from "tslog"; - -const prettyLogTemplate = - "{{hh}}:{{MM}}:{{ss}}:{{ms}}\t{{logLevelName}}\t[{{name}}]\t"; - -/** - * Minimum log level. Default is `info` (3). Lifts to `debug` (2) when: - * - `localStorage["mesh-debug"] === "1"` in a browser context, or - * - `process.env.MESH_DEBUG === "1"` in a Node / Bun / Deno context. - * - * Read once per `createLogger` call so the flag can be flipped at any - * time and new sub-loggers will pick it up; existing logger instances - * keep their level unless the caller explicitly resets it. - */ -function defaultMinLevel(): number { - try { - if ( - typeof globalThis !== "undefined" && - typeof (globalThis as { localStorage?: Storage }).localStorage !== - "undefined" && - (globalThis as { localStorage: Storage }).localStorage.getItem( - "mesh-debug", - ) === "1" - ) { - return 2; - } - } catch { - // localStorage access can throw in private mode / sandboxed iframes. - } - if ( - typeof globalThis !== "undefined" && - (globalThis as { process?: { env?: Record } }) - .process?.env?.MESH_DEBUG === "1" - ) { - return 2; - } - return 3; -} - -export function createLogger( - name: string, - options?: { minLevel?: number }, -): Logger { - return new Logger({ - name, - pretty: { template: prettyLogTemplate }, - minLevel: options?.minLevel ?? defaultMinLevel(), - }); -} - -export type { Logger }; diff --git a/packages/sdk/src/core/packet-codec/decodePacket.test.ts b/packages/sdk/src/core/packet-codec/decodePacket.test.ts deleted file mode 100644 index 836f4ac3b..000000000 --- a/packages/sdk/src/core/packet-codec/decodePacket.test.ts +++ /dev/null @@ -1,226 +0,0 @@ -import { create, toBinary } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { describe, expect, it, vi } from "vitest"; -import { MeshClient } from "../client/MeshClient.ts"; -import type { PacketMetadata } from "../types.ts"; -import { createFakeTransport } from "../testing/createFakeTransport.ts"; -import { decodePacket, hopsAway } from "./decodePacket.ts"; - -const flush = () => new Promise((resolve) => setTimeout(resolve, 10)); - -function setup() { - const fake = createFakeTransport(); - const client = new MeshClient({ - transport: fake.transport, - heartbeatIntervalMs: false, - }); - return { ...fake, client }; -} - -let nextId = 1; - -function dataPacket( - portnum: Protobuf.Portnums.PortNum, - payload: Uint8Array, - init: { id?: number; rxTime?: number } = {}, -) { - return create(Protobuf.Mesh.MeshPacketSchema, { - from: 0x10, - to: 0xffffffff, - id: init.id ?? nextId++, - rxTime: init.rxTime, - payloadVariant: { case: "decoded", value: { portnum, payload } }, - }); -} - -describe("decodePacket", () => { - it("records lockdown status and region presets on the device slice", async () => { - const { client, respond } = setup(); - respond.withRaw( - create(Protobuf.Mesh.FromRadioSchema, { - payloadVariant: { - case: "lockdownStatus", - value: { state: Protobuf.Mesh.LockdownStatus_State.LOCKED }, - }, - }), - ); - respond.withRaw( - create(Protobuf.Mesh.FromRadioSchema, { - payloadVariant: { case: "regionPresets", value: {} }, - }), - ); - await flush(); - expect(client.device.lockdownStatus.value?.state).toBe( - Protobuf.Mesh.LockdownStatus_State.LOCKED, - ); - expect(client.device.regionPresets.value).toBeDefined(); - }); - - it("decodes node status and mesh beacon packets", async () => { - const { client, respond } = setup(); - const statuses: string[] = []; - const beacons: string[] = []; - client.events.onNodeStatusPacket.subscribe((p) => - statuses.push(p.data.status), - ); - client.events.onMeshBeaconPacket.subscribe((p) => - beacons.push(p.data.message), - ); - - respond.withMeshPacket( - dataPacket( - Protobuf.Portnums.PortNum.NODE_STATUS_APP, - toBinary( - Protobuf.Mesh.StatusMessageSchema, - create(Protobuf.Mesh.StatusMessageSchema, { status: "on the hill" }), - ), - ), - ); - respond.withMeshPacket( - dataPacket( - Protobuf.Portnums.PortNum.MESH_BEACON_APP, - toBinary( - Protobuf.MeshBeacon.MeshBeaconSchema, - create(Protobuf.MeshBeacon.MeshBeaconSchema, { message: "join us" }), - ), - ), - ); - await flush(); - expect(statuses).toEqual(["on the hill"]); - expect(beacons).toEqual(["join us"]); - }); - - it("passes packets on unknown portnums through instead of dropping them", async () => { - const { client, respond } = setup(); - const seen: Protobuf.Portnums.PortNum[] = []; - client.events.onUnhandledPacket.subscribe((p) => seen.push(p.data.portnum)); - - respond.withMeshPacket( - dataPacket(Protobuf.Portnums.PortNum.PAGING_APP, new Uint8Array([1, 2])), - ); - const unknownPort = 400 as Protobuf.Portnums.PortNum; - respond.withMeshPacket(dataPacket(unknownPort, new Uint8Array([3]))); - await flush(); - expect(seen).toEqual([Protobuf.Portnums.PortNum.PAGING_APP, unknownPort]); - }); - - it("drops a packet it has already delivered", async () => { - const { client, respond } = setup(); - const alerts: string[] = []; - client.events.onAlertPacket.subscribe((p) => alerts.push(p.data)); - const payload = new TextEncoder().encode("smoke"); - - respond.withMeshPacket( - dataPacket(Protobuf.Portnums.PortNum.ALERT_APP, payload, { id: 99 }), - ); - respond.withMeshPacket( - dataPacket(Protobuf.Portnums.PortNum.ALERT_APP, payload, { id: 99 }), - ); - respond.withMeshPacket( - dataPacket(Protobuf.Portnums.PortNum.ALERT_APP, payload, { id: 100 }), - ); - await flush(); - expect(alerts).toEqual(["smoke", "smoke"]); - }); - - it("stamps packets without rx_time with the time they arrived", async () => { - const { client, respond } = setup(); - const times: number[] = []; - client.events.onAlertPacket.subscribe((p) => - times.push(p.rxTime.getTime()), - ); - const before = Date.now(); - - respond.withMeshPacket( - dataPacket(Protobuf.Portnums.PortNum.ALERT_APP, new Uint8Array()), - ); - respond.withMeshPacket( - dataPacket(Protobuf.Portnums.PortNum.ALERT_APP, new Uint8Array(), { - rxTime: 1_700_000_000, - }), - ); - await flush(); - expect(times[0]).toBeGreaterThanOrEqual(before); - expect(times[1]).toBe(1_700_000_000_000); - }); - - it("carries how the radio heard a packet, keeping 0 dB apart from no reading", async () => { - const { client, respond } = setup(); - const heard: PacketMetadata[] = []; - client.events.onMessagePacket.subscribe((p) => heard.push(p)); - const text = new TextEncoder().encode("hi"); - - respond.withMeshPacket( - create(Protobuf.Mesh.MeshPacketSchema, { - ...dataPacket(Protobuf.Portnums.PortNum.TEXT_MESSAGE_APP, text), - rxSnr: 0, - rxRssi: -90, - hopStart: 3, - hopLimit: 3, - transportMechanism: - Protobuf.Mesh.MeshPacket_TransportMechanism.TRANSPORT_LORA, - }), - ); - respond.withMeshPacket( - create(Protobuf.Mesh.MeshPacketSchema, { - ...dataPacket(Protobuf.Portnums.PortNum.TEXT_MESSAGE_APP, text), - hopStart: 3, - hopLimit: 1, - viaMqtt: true, - transportMechanism: - Protobuf.Mesh.MeshPacket_TransportMechanism.TRANSPORT_MQTT, - }), - ); - await flush(); - - expect(heard[0]).toMatchObject({ rxSnr: 0, rxRssi: -90, hopsAway: 0 }); - expect(heard[1]).toMatchObject({ - rxSnr: undefined, - rxRssi: undefined, - hopsAway: 2, - viaMqtt: true, - transportMechanism: - Protobuf.Mesh.MeshPacket_TransportMechanism.TRANSPORT_MQTT, - }); - }); -}); - -describe("hopsAway", () => { - it("is hop_start minus hop_limit", () => { - expect(hopsAway(3, 3)).toBe(0); - expect(hopsAway(7, 4)).toBe(3); - }); - - it("is unknown without a hop_start or with hop_limit above it", () => { - expect(hopsAway(0, 3)).toBeUndefined(); - expect(hopsAway(2, 3)).toBeUndefined(); - }); -}); - -describe("decodePacket pacing", () => { - it("pauses once a frame budget has passed so the page can repaint", async () => { - const now = vi.spyOn(performance, "now").mockReturnValue(0); - const client = new MeshClient({ - transport: createFakeTransport().transport, - }); - const writer = decodePacket(client).getWriter(); - const debug = { type: "debug", data: "" } as const; - - // Within the budget: no pause. - await writer.write(debug); - - // Past the budget: the write waits for a macrotask. - now.mockReturnValue(20); - let settled = false; - const pending = writer.write(debug).then(() => { - settled = true; - }); - await Promise.resolve(); - await Promise.resolve(); - expect(settled).toBe(false); - - await pending; - expect(settled).toBe(true); - now.mockRestore(); - }); -}); diff --git a/packages/sdk/src/core/packet-codec/decodePacket.ts b/packages/sdk/src/core/packet-codec/decodePacket.ts deleted file mode 100644 index 6f42cdec4..000000000 --- a/packages/sdk/src/core/packet-codec/decodePacket.ts +++ /dev/null @@ -1,737 +0,0 @@ -import { fromBinary } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import type { Logger } from "tslog"; -import { Constants } from "../constants/index.ts"; -import type { EventBus } from "../event-bus/EventBus.ts"; -import type { Queue } from "../queue/Queue.ts"; -import type { DeviceOutput } from "../transport/Transport.ts"; -import { DeviceStatusEnum } from "../transport/Transport.ts"; -import { ChannelNumber, Emitter, type PacketMetadata } from "../types.ts"; -import type { Xmodem } from "../xmodem/Xmodem.ts"; - -/** - * A minimal client-shape surface that the packet decoder writes into. - * MeshClient and the legacy MeshDevice shim both implement this. - */ -export interface PacketSink { - log: Logger; - events: EventBus; - queue: Queue; - xModem: Xmodem; - configId: number; - readonly myNodeNum: number; - updateDeviceStatus(status: DeviceStatusEnum): void; - configure(): Promise; -} - -/** How many recent packet keys are remembered for duplicate detection. */ -const RECENT_PACKET_CAPACITY = 256; -/** How long decoding may run before yielding so the page can repaint. */ -const FRAME_BUDGET_MS = 16; - -/** - * Remembers the most recent `(from, to, channel, id)` keys. Firmware 2.8 - * replays each node's cached packets with a stable id after every handshake, - * so a reconnect would otherwise deliver the same packets again. - */ -class RecentPackets { - private readonly keys = new Set(); - - /** True if the packet was already seen; records it otherwise. */ - public seen(packet: Protobuf.Mesh.MeshPacket): boolean { - if (packet.id === 0) return false; - const key = `${packet.from}:${packet.to}:${packet.channel}:${packet.id}`; - if (this.keys.has(key)) return true; - this.keys.add(key); - if (this.keys.size > RECENT_PACKET_CAPACITY) { - const oldest = this.keys.values().next().value; - if (oldest !== undefined) this.keys.delete(oldest); - } - return false; - } -} - -/** - * Writable stream that consumes framed DeviceOutput chunks, decodes FromRadio - * protobufs, routes MeshPackets through their portnums, and dispatches typed - * events on the provided EventBus. - */ -export const decodePacket = ( - sink: PacketSink, -): WritableStream => { - const recent = new RecentPackets(); - let lastYield = performance.now(); - // A large read (e.g. the NodeDB download) decodes many frames back to - // back; pausing once per frame budget lets the page repaint, so progress - // UI counts up instead of jumping at the end. - const yieldToRenderer = (): Promise | undefined => { - const now = performance.now(); - if (now - lastYield < FRAME_BUDGET_MS) return undefined; - lastYield = now; - return new Promise((resolve) => setTimeout(resolve, 0)).then(() => { - lastYield = performance.now(); - }); - }; - - const handle = (chunk: DeviceOutput): void => { - switch (chunk.type) { - case "status": { - const { status, reason } = chunk.data; - sink.updateDeviceStatus(status); - sink.log.info( - Emitter[Emitter.ConnectionStatus], - `🔗 ${DeviceStatusEnum[status]} ${reason ? `(${reason})` : ""}`, - ); - break; - } - case "debug": { - break; - } - case "packet": { - let decodedMessage: Protobuf.Mesh.FromRadio; - try { - decodedMessage = fromBinary( - Protobuf.Mesh.FromRadioSchema, - chunk.data, - ); - } catch (e) { - sink.log.error( - Emitter[Emitter.HandleFromRadio], - "⚠️ Received undecodable packet", - e, - ); - break; - } - sink.events.onFromRadio.dispatch(decodedMessage); - - switch (decodedMessage.payloadVariant.case) { - case "packet": { - if (recent.seen(decodedMessage.payloadVariant.value)) { - sink.log.trace( - Emitter[Emitter.HandleFromRadio], - `Dropping duplicate packet ${decodedMessage.payloadVariant.value.id}`, - ); - break; - } - try { - handleMeshPacket(sink, decodedMessage.payloadVariant.value); - } catch (e) { - sink.log.error( - Emitter[Emitter.HandleFromRadio], - "⚠️ Unable to handle mesh packet", - e, - ); - } - break; - } - case "myInfo": { - sink.events.onMyNodeInfo.dispatch( - decodedMessage.payloadVariant.value, - ); - sink.log.info( - Emitter[Emitter.HandleFromRadio], - "📱 Received Node info for this device", - ); - break; - } - case "nodeInfo": { - sink.log.info( - Emitter[Emitter.HandleFromRadio], - `📱 Received Node Info packet for node: ${decodedMessage.payloadVariant.value.num}`, - ); - sink.events.onNodeInfoPacket.dispatch( - decodedMessage.payloadVariant.value, - ); - - if (decodedMessage.payloadVariant.value.position) { - sink.events.onPositionPacket.dispatch({ - id: decodedMessage.id, - rxTime: new Date(), - from: decodedMessage.payloadVariant.value.num, - to: decodedMessage.payloadVariant.value.num, - type: "direct", - channel: ChannelNumber.Primary, - data: decodedMessage.payloadVariant.value.position, - }); - } - - if (decodedMessage.payloadVariant.value.user) { - sink.events.onUserPacket.dispatch({ - id: decodedMessage.id, - rxTime: new Date(), - from: decodedMessage.payloadVariant.value.num, - to: decodedMessage.payloadVariant.value.num, - type: "direct", - channel: ChannelNumber.Primary, - data: decodedMessage.payloadVariant.value.user, - }); - } - break; - } - case "config": { - if (decodedMessage.payloadVariant.value.payloadVariant.case) { - sink.log.trace( - Emitter[Emitter.HandleFromRadio], - `💾 Received Config packet of variant: ${decodedMessage.payloadVariant.value.payloadVariant.case}`, - ); - } else { - sink.log.warn( - Emitter[Emitter.HandleFromRadio], - "⚠️ Received Config packet of variant: UNK", - ); - } - sink.events.onConfigPacket.dispatch( - decodedMessage.payloadVariant.value, - ); - break; - } - case "logRecord": { - sink.log.trace( - Emitter[Emitter.HandleFromRadio], - "Received onLogRecord", - ); - sink.events.onLogRecord.dispatch( - decodedMessage.payloadVariant.value, - ); - break; - } - case "configCompleteId": { - sink.log.info( - Emitter[Emitter.HandleFromRadio], - `⚙️ Received config complete id: ${decodedMessage.payloadVariant.value}`, - ); - // MeshClient matches the id against the handshake stage and - // marks the device configured after the final stage. - sink.events.onConfigComplete.dispatch( - decodedMessage.payloadVariant.value, - ); - break; - } - case "rebooted": { - sink.events.onRebooted.dispatch(); - sink.configure().catch((e: unknown) => { - sink.log.warn( - Emitter[Emitter.HandleFromRadio], - "⚠️ Handshake after reboot failed", - e, - ); - }); - break; - } - case "moduleConfig": { - if (decodedMessage.payloadVariant.value.payloadVariant.case) { - sink.log.trace( - Emitter[Emitter.HandleFromRadio], - `💾 Received Module Config packet of variant: ${decodedMessage.payloadVariant.value.payloadVariant.case}`, - ); - } else { - sink.log.warn( - Emitter[Emitter.HandleFromRadio], - "⚠️ Received Module Config packet of variant: UNK", - ); - } - sink.events.onModuleConfigPacket.dispatch( - decodedMessage.payloadVariant.value, - ); - break; - } - case "channel": { - sink.log.trace( - Emitter[Emitter.HandleFromRadio], - `🔐 Received Channel: ${decodedMessage.payloadVariant.value.index}`, - ); - sink.events.onChannelPacket.dispatch( - decodedMessage.payloadVariant.value, - ); - break; - } - case "queueStatus": { - sink.log.trace( - Emitter[Emitter.HandleFromRadio], - `🚧 Received Queue Status: last status: ${decodedMessage.payloadVariant.value.res}, free entries: ${decodedMessage.payloadVariant.value.free} out of ${decodedMessage.payloadVariant.value.maxlen}`, - ); - sink.events.onQueueStatus.dispatch( - decodedMessage.payloadVariant.value, - ); - break; - } - case "xmodemPacket": { - sink.xModem.handlePacket(decodedMessage.payloadVariant.value); - break; - } - case "metadata": { - sink.log.debug( - Emitter[Emitter.GetMetadata], - "🏷️ Received metadata packet", - ); - sink.events.onDeviceMetadataPacket.dispatch({ - id: decodedMessage.id, - rxTime: new Date(), - from: 0, - to: 0, - type: "direct", - channel: ChannelNumber.Primary, - data: decodedMessage.payloadVariant.value, - }); - break; - } - case "mqttClientProxyMessage": { - break; - } - case "clientNotification": { - sink.log.trace( - Emitter[Emitter.HandleFromRadio], - `📣 Received ClientNotification: ${decodedMessage.payloadVariant.value.message}`, - ); - sink.events.onClientNotificationPacket.dispatch( - decodedMessage.payloadVariant.value, - ); - break; - } - case "lockdownStatus": { - // Arrives right after config_complete_id on lockdown builds. - // While locked, metadata is zeroed and channels and NodeDB are - // withheld until the client unlocks and re-runs the handshake. - sink.log.info( - Emitter[Emitter.HandleFromRadio], - `🔒 Received lockdown status: ${Protobuf.Mesh.LockdownStatus_State[decodedMessage.payloadVariant.value.state]}`, - ); - sink.events.onLockdownStatus.dispatch( - decodedMessage.payloadVariant.value, - ); - break; - } - case "regionPresets": { - sink.events.onRegionPresets.dispatch( - decodedMessage.payloadVariant.value, - ); - break; - } - case "deviceuiConfig": { - sink.events.onDeviceUiConfig.dispatch( - decodedMessage.payloadVariant.value, - ); - break; - } - case "fileInfo": { - sink.events.onFileInfo.dispatch( - decodedMessage.payloadVariant.value, - ); - break; - } - default: { - sink.log.warn( - Emitter[Emitter.HandleFromRadio], - `⚠️ Unhandled payload variant: ${decodedMessage.payloadVariant.case}`, - ); - } - } - } - } - }; - - return new WritableStream({ - write(chunk) { - handle(chunk); - return yieldToRenderer(); - }, - }); -}; - -function handleMeshPacket( - sink: PacketSink, - meshPacket: Protobuf.Mesh.MeshPacket, -): void { - sink.events.onMeshPacket.dispatch(meshPacket); - if (meshPacket.from !== sink.myNodeNum) { - sink.events.onMeshHeartbeat.dispatch(new Date()); - } - - switch (meshPacket.payloadVariant.case) { - case "decoded": { - handleDecodedPacket(sink, meshPacket.payloadVariant.value, meshPacket); - break; - } - case "encrypted": { - sink.log.debug( - Emitter[Emitter.HandleMeshPacket], - "🔐 Device received encrypted data packet, ignoring.", - ); - break; - } - default: - throw new Error(`Unhandled case ${meshPacket.payloadVariant.case}`); - } -} - -/** - * Hops the packet took, from hop_start and hop_limit. Unknown when hop_start - * is 0 (firmware older than 2.3, which didn't set it) or hop_limit is above it. - */ -export function hopsAway( - hopStart: number, - hopLimit: number, -): number | undefined { - if (hopStart === 0 || hopLimit > hopStart) return undefined; - return hopStart - hopLimit; -} - -/** - * How our radio heard the packet. rx_snr is a plain proto3 float, so 0 can - * mean either a 0 dB reading or no reading at all; rx_rssi is optional and - * only set when the radio measured the packet, so it tells the two apart. - */ -function radioMetadata(meshPacket: Protobuf.Mesh.MeshPacket) { - const measured = meshPacket.rxRssi !== undefined || meshPacket.rxSnr !== 0; - return { - rxSnr: measured ? meshPacket.rxSnr : undefined, - rxRssi: meshPacket.rxRssi, - hopsAway: hopsAway(meshPacket.hopStart, meshPacket.hopLimit), - viaMqtt: meshPacket.viaMqtt, - transportMechanism: meshPacket.transportMechanism, - }; -} - -function handleDecodedPacket( - sink: PacketSink, - dataPacket: Protobuf.Mesh.Data, - meshPacket: Protobuf.Mesh.MeshPacket, -) { - const packetMetadata: Omit, "data"> = { - id: meshPacket.id, - // rx_time is optional since protobufs 2.8.0. Unset means the device had - // no wall-clock time, so the time it reached us is the best estimate. - rxTime: meshPacket.rxTime ? new Date(meshPacket.rxTime * 1000) : new Date(), - type: meshPacket.to === Constants.broadcastNum ? "broadcast" : "direct", - from: meshPacket.from, - to: meshPacket.to, - channel: meshPacket.channel, - requestId: dataPacket.requestId || undefined, - xeddsaSigned: meshPacket.xeddsaSigned, - ackProofStatus: meshPacket.ackProofStatus, - ...radioMetadata(meshPacket), - }; - - sink.log.trace( - Emitter[Emitter.HandleMeshPacket], - `📦 Received ${Protobuf.Portnums.PortNum[dataPacket.portnum]} packet`, - ); - - switch (dataPacket.portnum) { - case Protobuf.Portnums.PortNum.TEXT_MESSAGE_APP: { - sink.events.onMessagePacket.dispatch({ - ...packetMetadata, - data: new TextDecoder().decode(dataPacket.payload), - }); - break; - } - case Protobuf.Portnums.PortNum.REMOTE_HARDWARE_APP: { - sink.events.onRemoteHardwarePacket.dispatch({ - ...packetMetadata, - data: fromBinary( - Protobuf.RemoteHardware.HardwareMessageSchema, - dataPacket.payload, - ), - }); - break; - } - case Protobuf.Portnums.PortNum.POSITION_APP: { - sink.events.onPositionPacket.dispatch({ - ...packetMetadata, - data: fromBinary(Protobuf.Mesh.PositionSchema, dataPacket.payload), - }); - break; - } - case Protobuf.Portnums.PortNum.NODEINFO_APP: { - sink.events.onUserPacket.dispatch({ - ...packetMetadata, - data: fromBinary(Protobuf.Mesh.UserSchema, dataPacket.payload), - }); - break; - } - case Protobuf.Portnums.PortNum.ROUTING_APP: { - const routingPacket = fromBinary( - Protobuf.Mesh.RoutingSchema, - dataPacket.payload, - ); - sink.events.onRoutingPacket.dispatch({ - ...packetMetadata, - data: routingPacket, - }); - switch (routingPacket.variant.case) { - case "errorReason": { - if ( - routingPacket.variant.value === Protobuf.Mesh.Routing_Error.NONE - ) { - sink.queue.processAck(dataPacket.requestId); - } else { - sink.queue.processError({ - id: dataPacket.requestId, - error: routingPacket.variant.value, - }); - } - break; - } - case "routeReply": - case "routeRequest": - break; - default: - sink.log.warn( - Emitter[Emitter.HandleMeshPacket], - `⚠️ Routing packet ${meshPacket.id} has no variant set`, - ); - } - break; - } - case Protobuf.Portnums.PortNum.ADMIN_APP: { - const adminMessage = fromBinary( - Protobuf.Admin.AdminMessageSchema, - dataPacket.payload, - ); - sink.events.onAdminPacket.dispatch({ - ...packetMetadata, - data: adminMessage, - }); - switch (adminMessage.payloadVariant.case) { - case "getChannelResponse": { - sink.events.onChannelPacket.dispatch( - adminMessage.payloadVariant.value, - ); - break; - } - case "getOwnerResponse": { - sink.events.onUserPacket.dispatch({ - ...packetMetadata, - data: adminMessage.payloadVariant.value, - }); - break; - } - case "getConfigResponse": { - sink.events.onConfigPacket.dispatch( - adminMessage.payloadVariant.value, - ); - break; - } - case "getModuleConfigResponse": { - sink.events.onModuleConfigPacket.dispatch( - adminMessage.payloadVariant.value, - ); - break; - } - case "getDeviceMetadataResponse": { - sink.log.debug( - Emitter[Emitter.GetMetadata], - `🏷️ Received metadata packet from ${dataPacket.source}`, - ); - sink.events.onDeviceMetadataPacket.dispatch({ - ...packetMetadata, - data: adminMessage.payloadVariant.value, - }); - break; - } - case "getCannedMessageModuleMessagesResponse": { - sink.log.debug( - Emitter[Emitter.GetMetadata], - "🥫 Received CannedMessage Module Messages response packet", - ); - sink.events.onCannedMessageModulePacket.dispatch({ - ...packetMetadata, - data: adminMessage.payloadVariant.value, - }); - break; - } - case "getRingtoneResponse": { - // ConfigClient reads it from onAdminPacket above. - sink.log.debug( - Emitter[Emitter.HandleMeshPacket], - "🔔 Received ringtone response packet", - ); - break; - } - default: { - sink.log.error( - Emitter[Emitter.HandleMeshPacket], - `⚠️ Received unhandled AdminMessage, type ${ - adminMessage.payloadVariant.case ?? "undefined" - }`, - dataPacket.payload, - ); - } - } - break; - } - case Protobuf.Portnums.PortNum.WAYPOINT_APP: { - sink.events.onWaypointPacket.dispatch({ - ...packetMetadata, - data: fromBinary(Protobuf.Mesh.WaypointSchema, dataPacket.payload), - }); - break; - } - case Protobuf.Portnums.PortNum.AUDIO_APP: { - sink.events.onAudioPacket.dispatch({ - ...packetMetadata, - data: dataPacket.payload, - }); - break; - } - case Protobuf.Portnums.PortNum.DETECTION_SENSOR_APP: { - sink.events.onDetectionSensorPacket.dispatch({ - ...packetMetadata, - data: dataPacket.payload, - }); - break; - } - case Protobuf.Portnums.PortNum.REPLY_APP: { - sink.events.onPingPacket.dispatch({ - ...packetMetadata, - data: dataPacket.payload, - }); - break; - } - case Protobuf.Portnums.PortNum.IP_TUNNEL_APP: { - sink.events.onIpTunnelPacket.dispatch({ - ...packetMetadata, - data: dataPacket.payload, - }); - break; - } - case Protobuf.Portnums.PortNum.PAXCOUNTER_APP: { - sink.events.onPaxcounterPacket.dispatch({ - ...packetMetadata, - data: fromBinary(Protobuf.PaxCount.PaxcountSchema, dataPacket.payload), - }); - break; - } - case Protobuf.Portnums.PortNum.SERIAL_APP: { - sink.events.onSerialPacket.dispatch({ - ...packetMetadata, - data: dataPacket.payload, - }); - break; - } - case Protobuf.Portnums.PortNum.STORE_FORWARD_APP: { - sink.events.onStoreForwardPacket.dispatch({ - ...packetMetadata, - data: dataPacket.payload, - }); - break; - } - case Protobuf.Portnums.PortNum.RANGE_TEST_APP: { - sink.events.onRangeTestPacket.dispatch({ - ...packetMetadata, - data: dataPacket.payload, - }); - break; - } - case Protobuf.Portnums.PortNum.TELEMETRY_APP: { - sink.events.onTelemetryPacket.dispatch({ - ...packetMetadata, - data: fromBinary( - Protobuf.Telemetry.TelemetrySchema, - dataPacket.payload, - ), - }); - break; - } - case Protobuf.Portnums.PortNum.ZPS_APP: { - sink.events.onZpsPacket.dispatch({ - ...packetMetadata, - data: dataPacket.payload, - }); - break; - } - case Protobuf.Portnums.PortNum.SIMULATOR_APP: { - sink.events.onSimulatorPacket.dispatch({ - ...packetMetadata, - data: dataPacket.payload, - }); - break; - } - case Protobuf.Portnums.PortNum.TRACEROUTE_APP: { - sink.events.onTraceRoutePacket.dispatch({ - ...packetMetadata, - data: fromBinary( - Protobuf.Mesh.RouteDiscoverySchema, - dataPacket.payload, - ), - }); - break; - } - case Protobuf.Portnums.PortNum.NEIGHBORINFO_APP: { - sink.events.onNeighborInfoPacket.dispatch({ - ...packetMetadata, - data: fromBinary(Protobuf.Mesh.NeighborInfoSchema, dataPacket.payload), - }); - break; - } - case Protobuf.Portnums.PortNum.ATAK_PLUGIN: { - sink.events.onAtakPluginPacket.dispatch({ - ...packetMetadata, - data: dataPacket.payload, - }); - break; - } - case Protobuf.Portnums.PortNum.MAP_REPORT_APP: { - sink.events.onMapReportPacket.dispatch({ - ...packetMetadata, - data: dataPacket.payload, - }); - break; - } - case Protobuf.Portnums.PortNum.PRIVATE_APP: { - sink.events.onPrivatePacket.dispatch({ - ...packetMetadata, - data: dataPacket.payload, - }); - break; - } - case Protobuf.Portnums.PortNum.ATAK_FORWARDER: { - sink.events.onAtakForwarderPacket.dispatch({ - ...packetMetadata, - data: dataPacket.payload, - }); - break; - } - case Protobuf.Portnums.PortNum.NODE_STATUS_APP: { - sink.events.onNodeStatusPacket.dispatch({ - ...packetMetadata, - data: fromBinary(Protobuf.Mesh.StatusMessageSchema, dataPacket.payload), - }); - break; - } - case Protobuf.Portnums.PortNum.MESH_BEACON_APP: { - sink.events.onMeshBeaconPacket.dispatch({ - ...packetMetadata, - data: fromBinary( - Protobuf.MeshBeacon.MeshBeaconSchema, - dataPacket.payload, - ), - }); - break; - } - case Protobuf.Portnums.PortNum.KEY_VERIFICATION_APP: { - sink.events.onKeyVerificationPacket.dispatch({ - ...packetMetadata, - data: fromBinary( - Protobuf.Mesh.KeyVerificationSchema, - dataPacket.payload, - ), - }); - break; - } - case Protobuf.Portnums.PortNum.ALERT_APP: { - sink.events.onAlertPacket.dispatch({ - ...packetMetadata, - data: new TextDecoder().decode(dataPacket.payload), - }); - break; - } - default: - // Newer firmware adds portnums faster than clients learn them; hand - // the raw payload on rather than dropping the packet. - sink.events.onUnhandledPacket.dispatch({ - ...packetMetadata, - data: { portnum: dataPacket.portnum, payload: dataPacket.payload }, - }); - } -} diff --git a/packages/sdk/src/core/packet-codec/fromDevice.test.ts b/packages/sdk/src/core/packet-codec/fromDevice.test.ts deleted file mode 100644 index 7c0ff6a81..000000000 --- a/packages/sdk/src/core/packet-codec/fromDevice.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { describe, expect, it } from "vitest"; -import type { DeviceOutput } from "../transport/Transport.ts"; -import { fromDeviceStream } from "./fromDevice.ts"; - -const frame = (payload: number[]): number[] => [ - 0x94, - 0xc3, - payload.length >> 8, - payload.length & 0xff, - ...payload, -]; - -async function parse(chunks: number[][]): Promise { - const stream = new ReadableStream({ - start(controller) { - for (const chunk of chunks) controller.enqueue(new Uint8Array(chunk)); - controller.close(); - }, - }).pipeThrough(fromDeviceStream()); - const out: DeviceOutput[] = []; - for await (const item of stream as unknown as AsyncIterable) { - out.push(item); - } - return out; -} - -const packets = (out: DeviceOutput[]) => - out - .filter((o) => o.type === "packet") - .map((o) => Array.from(o.data as Uint8Array)); - -describe("fromDeviceStream", () => { - it("emits a framed packet", async () => { - expect(packets(await parse([frame([1, 2, 3])]))).toEqual([[1, 2, 3]]); - }); - - it("keeps a packet whose payload contains 0x94 0xC3", async () => { - // e.g. a NodeInfo whose public key happens to contain the header bytes - const payload = [18, 6, 0x10, 0x94, 0xc3, 0x00, 0x7f, 0x01]; - const next = [8, 1]; - const out = await parse([[...frame(payload), ...frame(next)]]); - expect(packets(out)).toEqual([payload, next]); - }); - - it("reassembles frames split across chunks, including the header", async () => { - const bytes = [...frame([5, 6, 7, 8]), ...frame([9])]; - const chunks = bytes.map((b) => [b]); // one byte per chunk - expect(packets(await parse(chunks))).toEqual([[5, 6, 7, 8], [9]]); - }); - - it("emits debug text before a frame", async () => { - const text = Array.from(new TextEncoder().encode("INFO boot\n")); - const out = await parse([[...text, ...frame([1])]]); - expect(out[0]).toEqual({ type: "debug", data: "INFO boot\n" }); - expect(packets(out)).toEqual([[1]]); - }); - - it("skips a header that claims more than the maximum length", async () => { - // 0x94 0xC3 followed by a bogus 0xFFFF length must not swallow the stream - const out = await parse([[0x94, 0xc3, 0xff, 0xff, ...frame([4, 2])]]); - expect(packets(out)).toEqual([[4, 2]]); - }); - - it("waits for the rest of a frame instead of dropping it", async () => { - const bytes = frame([1, 2, 3, 4, 5]); - expect(packets(await parse([bytes.slice(0, 6), bytes.slice(6)]))).toEqual([ - [1, 2, 3, 4, 5], - ]); - }); - - it("parses a large NodeDB burst", async () => { - const payloads = Array.from({ length: 300 }, (_, i) => - Array.from({ length: 120 }, (_, j) => (i * 31 + j * 7) & 0xff), - ); - const bytes = payloads.flatMap(frame); - const chunks: number[][] = []; - for (let i = 0; i < bytes.length; i += 64) { - chunks.push(bytes.slice(i, i + 64)); - } - expect(packets(await parse(chunks))).toEqual(payloads); - }); -}); diff --git a/packages/sdk/src/core/packet-codec/fromDevice.ts b/packages/sdk/src/core/packet-codec/fromDevice.ts deleted file mode 100644 index 3b4fcf303..000000000 --- a/packages/sdk/src/core/packet-codec/fromDevice.ts +++ /dev/null @@ -1,96 +0,0 @@ -import type { DeviceOutput } from "../transport/Transport.ts"; - -const START1 = 0x94; -const START2 = 0xc3; -const HEADER_LENGTH = 4; -/** Firmware's MAX_TO_FROM_RADIO_SIZE: no real frame is longer than this. */ -const MAX_PACKET_LENGTH = 512; - -/** Index of the next `0x94 0xC3` header, or -1. */ -function findHeader(buffer: Uint8Array): number { - for (let i = 0; i < buffer.length - 1; i++) { - if (buffer[i] === START1 && buffer[i + 1] === START2) return i; - } - return -1; -} - -/** `a` followed by `b`, without copying when either is empty. */ -function concat(a: Uint8Array, b: Uint8Array): Uint8Array { - if (a.length === 0) return b; - if (b.length === 0) return a; - const out = new Uint8Array(a.length + b.length); - out.set(a); - out.set(b, a.length); - return out; -} - -/** - * Transforms a raw byte stream from the device into typed DeviceOutput chunks - * by parsing the 0x94 0xC3 framing header and length prefix. - * - * The length prefix is trusted for frames up to the firmware's maximum - * packet size. The payload itself is never scanned for a header: it is - * binary (keys, ids), so `0x94 0xC3` occurs inside valid packets. A header - * claiming more than the maximum is treated as noise and skipped, so the - * parser resynchronises on the next real header instead of waiting for - * bytes that will never come. - */ -export const fromDeviceStream: () => TransformStream< - Uint8Array, - DeviceOutput -> = () => { - let buffer: Uint8Array = new Uint8Array(0); - const textDecoder = new TextDecoder(); - - const emitDebug = ( - bytes: Uint8Array, - controller: TransformStreamDefaultController, - ) => { - if (bytes.length) { - controller.enqueue({ - type: "debug", - data: textDecoder.decode(bytes, { stream: true }), - }); - } - }; - - return new TransformStream({ - transform(chunk: Uint8Array, controller): void { - buffer = concat(buffer, chunk); - - while (buffer.length > 0) { - const start = findHeader(buffer); - if (start === -1) { - // No header yet. Flush the text, keeping a trailing 0x94 that may - // be the first half of a header split across chunks. - const keep = buffer[buffer.length - 1] === START1 ? 1 : 0; - emitDebug(buffer.subarray(0, buffer.length - keep), controller); - buffer = buffer.slice(buffer.length - keep); - return; - } - - if (start > 0) { - emitDebug(buffer.subarray(0, start), controller); - buffer = buffer.subarray(start); - } - - if (buffer.length < HEADER_LENGTH) return; - - const length = ((buffer[2] ?? 0) << 8) | (buffer[3] ?? 0); - if (length > MAX_PACKET_LENGTH) { - // Not a real header (e.g. 0x94 0xC3 inside debug text); skip it. - buffer = buffer.subarray(1); - continue; - } - - if (buffer.length < HEADER_LENGTH + length) return; - - controller.enqueue({ - type: "packet", - data: buffer.slice(HEADER_LENGTH, HEADER_LENGTH + length), - }); - buffer = buffer.subarray(HEADER_LENGTH + length); - } - }, - }); -}; diff --git a/packages/sdk/src/core/packet-codec/index.ts b/packages/sdk/src/core/packet-codec/index.ts deleted file mode 100644 index 07c048650..000000000 --- a/packages/sdk/src/core/packet-codec/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { fromDeviceStream } from "./fromDevice.ts"; -export { toDeviceStream } from "./toDevice.ts"; -export { decodePacket } from "./decodePacket.ts"; -export type { PacketSink } from "./decodePacket.ts"; diff --git a/packages/sdk/src/core/packet-codec/toDevice.ts b/packages/sdk/src/core/packet-codec/toDevice.ts deleted file mode 100644 index b7bdbf080..000000000 --- a/packages/sdk/src/core/packet-codec/toDevice.ts +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Pads outbound packets with the 0x94 0xC3 framing header and length prefix. - */ -export const toDeviceStream: () => TransformStream< - Uint8Array, - Uint8Array -> = () => { - return new TransformStream({ - transform(chunk: Uint8Array, controller): void { - const bufLen = chunk.length; - const header = new Uint8Array([ - 0x94, - 0xc3, - (bufLen >> 8) & 0xff, - bufLen & 0xff, - ]); - controller.enqueue(new Uint8Array([...header, ...chunk])); - }, - }); -}; diff --git a/packages/sdk/src/core/protobuf/index.ts b/packages/sdk/src/core/protobuf/index.ts deleted file mode 100644 index a3a0ce0a4..000000000 --- a/packages/sdk/src/core/protobuf/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * as Protobuf from "@meshtastic/protobufs"; diff --git a/packages/sdk/src/core/queue/Queue.ts b/packages/sdk/src/core/queue/Queue.ts deleted file mode 100644 index e450f2e8c..000000000 --- a/packages/sdk/src/core/queue/Queue.ts +++ /dev/null @@ -1,156 +0,0 @@ -import { fromBinary } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { SimpleEventDispatcher } from "ste-simple-events"; -import type { PacketError, QueueItem } from "../types.ts"; - -export class Queue { - private queue: QueueItem[] = []; - private lock = false; - private ackNotifier = new SimpleEventDispatcher(); - private errorNotifier = new SimpleEventDispatcher(); - private timeout: number; - /** Resolvers for items the device never acks; settled once written. */ - private unackedResolvers = new Map void>(); - - constructor() { - this.timeout = 60000; - } - - public getState(): QueueItem[] { - return this.queue; - } - - public clear(): void { - this.queue = []; - this.unackedResolvers.clear(); - } - - /** - * Queues a ToRadio frame. With `expectAck: false` (heartbeat, - * want_config_id, packets sent without want_ack) the promise resolves as - * soon as the frame is written, because the device never acks it. - */ - public push( - item: Omit, - { expectAck = true }: { expectAck?: boolean } = {}, - ): Promise { - const queueItem: QueueItem = { - ...item, - sent: false, - added: new Date(), - promise: new Promise((resolve, reject) => { - if (!expectAck) { - this.unackedResolvers.set(item.id, resolve); - } - this.ackNotifier.subscribe((id) => { - if (item.id === id) { - this.remove(item.id); - resolve(id); - } - }); - this.errorNotifier.subscribe((e) => { - if (item.id === e.id) { - this.remove(item.id); - reject(e); - } - }); - setTimeout(() => { - if (this.queue.findIndex((qi) => qi.id === item.id) !== -1) { - this.remove(item.id); - const decoded = fromBinary(Protobuf.Mesh.ToRadioSchema, item.data); - - if ( - decoded.payloadVariant.case === "heartbeat" || - decoded.payloadVariant.case === "wantConfigId" - ) { - resolve(item.id); - return; - } - - console.warn( - `Packet ${item.id} of type ${decoded.payloadVariant.case} timed out`, - ); - - reject({ - id: item.id, - error: Protobuf.Mesh.Routing_Error.TIMEOUT, - }); - } - }, this.timeout); - }), - }; - this.queue.push(queueItem); - return queueItem.promise; - } - - public remove(id: number): void { - if (this.lock) { - setTimeout(() => this.remove(id), 100); - return; - } - this.queue = this.queue.filter((item) => item.id !== id); - } - - public processAck(id: number): void { - this.ackNotifier.dispatch(id); - } - - public processError(e: PacketError): void { - console.error( - `Error received for packet ${e.id}: ${Protobuf.Mesh.Routing_Error[e.error]}`, - ); - this.errorNotifier.dispatch(e); - } - - public wait(id: number): Promise { - const queueItem = this.queue.find((qi) => qi.id === id); - if (!queueItem) { - throw new Error("Packet does not exist"); - } - return queueItem.promise; - } - - public async processQueue( - outputStream: WritableStream, - ): Promise { - if (this.lock) { - return; - } - - this.lock = true; - const writer = outputStream.getWriter(); - - try { - while (this.queue.filter((p) => !p.sent).length > 0) { - const item = this.queue.filter((p) => !p.sent)[0]; - if (item) { - await new Promise((resolve) => setTimeout(resolve, 200)); - try { - await writer.write(item.data); - item.sent = true; - const resolveUnacked = this.unackedResolvers.get(item.id); - if (resolveUnacked) { - this.unackedResolvers.delete(item.id); - this.queue = this.queue.filter((qi) => qi.id !== item.id); - resolveUnacked(item.id); - } - } catch (error) { - const err = error as { code?: string }; - if ( - err?.code === "ECONNRESET" || - err?.code === "ERR_INVALID_STATE" - ) { - writer.releaseLock(); - this.lock = false; - throw error; - } - console.error(`Error sending packet ${item.id}`, error); - } - } - } - } finally { - writer.releaseLock(); - this.lock = false; - } - } -} diff --git a/packages/sdk/src/core/registry/MeshRegistry.test.ts b/packages/sdk/src/core/registry/MeshRegistry.test.ts deleted file mode 100644 index 9a62d0943..000000000 --- a/packages/sdk/src/core/registry/MeshRegistry.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { createFakeTransport } from "../testing/createFakeTransport.ts"; -import { MeshRegistry } from "./MeshRegistry.ts"; - -describe("MeshRegistry", () => { - it("creates clients keyed by id and emits a snapshot", () => { - const reg = new MeshRegistry(); - const seen: number[] = []; - reg.list.subscribe((entries) => seen.push(entries.length)); - - const { transport: t1 } = createFakeTransport(); - const { transport: t2 } = createFakeTransport(); - - reg.create(1, { transport: t1 }); - reg.create(2, { transport: t2 }); - - expect(reg.size).toBe(2); - expect(reg.get(1)).toBeDefined(); - expect(reg.get(42)).toBeUndefined(); - expect(seen).toEqual([1, 2]); - }); - - it("auto-activates the first client and allows switching", () => { - const reg = new MeshRegistry(); - expect(reg.activeId.value).toBeNull(); - - const { transport: t1 } = createFakeTransport(); - const { transport: t2 } = createFakeTransport(); - reg.create(1, { transport: t1 }); - expect(reg.activeId.value).toBe(1); - - reg.create(2, { transport: t2 }); - expect(reg.activeId.value).toBe(1); - - reg.setActive(2); - expect(reg.activeId.value).toBe(2); - expect(reg.active.value).toBe(reg.get(2)); - }); - - it("rejects duplicate ids", () => { - const reg = new MeshRegistry(); - const { transport } = createFakeTransport(); - reg.create(1, { transport }); - expect(() => - reg.create(1, { transport: createFakeTransport().transport }), - ).toThrow(); - }); - - it("remove disconnects the client and falls back to another active id", async () => { - const reg = new MeshRegistry(); - reg.create(1, { transport: createFakeTransport().transport }); - reg.create(2, { transport: createFakeTransport().transport }); - reg.setActive(1); - await reg.remove(1); - expect(reg.size).toBe(1); - expect(reg.activeId.value).toBe(2); - }); -}); diff --git a/packages/sdk/src/core/registry/MeshRegistry.ts b/packages/sdk/src/core/registry/MeshRegistry.ts deleted file mode 100644 index 8e503275e..000000000 --- a/packages/sdk/src/core/registry/MeshRegistry.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { type Signal, signal } from "@preact/signals-core"; -import { MeshClient, type MeshClientOptions } from "../client/MeshClient.ts"; -import { type ReadonlySignal, toReadonly } from "../signals/createStore.ts"; - -export type ConnectionId = number; - -export interface RegistryEntry { - readonly id: ConnectionId; - readonly client: MeshClient; -} - -/** - * Manages multiple `MeshClient` instances keyed by connection id. - * - * Use this when an application holds more than one device connection at a - * time (e.g. multi-radio UIs). Single-device consumers can ignore this and - * instantiate `MeshClient` directly. - */ -export class MeshRegistry { - private readonly clients = new Map(); - private readonly backing: Signal>; - private readonly activeSignal: Signal; - private readonly activeIdSignal: Signal; - - public readonly list: ReadonlySignal>; - public readonly active: ReadonlySignal; - public readonly activeId: ReadonlySignal; - - constructor() { - this.backing = signal>([]); - this.activeSignal = signal(undefined); - this.activeIdSignal = signal(null); - this.list = toReadonly(this.backing); - this.active = toReadonly(this.activeSignal); - this.activeId = toReadonly(this.activeIdSignal); - } - - public create(id: ConnectionId, options: MeshClientOptions): MeshClient { - if (this.clients.has(id)) { - throw new Error(`MeshRegistry already has a client for id ${id}`); - } - const client = new MeshClient(options); - return this.adopt(id, client); - } - - /** - * Registers an externally-constructed MeshClient under the given id. Useful - * when the client was produced by a legacy shim (e.g. the Phase-A MeshDevice - * wrapper) and must coexist with the registry during migration. - */ - public register(id: ConnectionId, client: MeshClient): MeshClient { - if (this.clients.has(id)) { - throw new Error(`MeshRegistry already has a client for id ${id}`); - } - return this.adopt(id, client); - } - - private adopt(id: ConnectionId, client: MeshClient): MeshClient { - this.clients.set(id, client); - this.snapshot(); - if (this.activeIdSignal.value === null) { - this.setActive(id); - } - return client; - } - - public get(id: ConnectionId): MeshClient | undefined { - return this.clients.get(id); - } - - public has(id: ConnectionId): boolean { - return this.clients.has(id); - } - - public setActive(id: ConnectionId | null): void { - if (id === null) { - this.activeIdSignal.value = null; - this.activeSignal.value = undefined; - return; - } - const client = this.clients.get(id); - if (!client) { - throw new Error(`MeshRegistry has no client for id ${id}`); - } - this.activeIdSignal.value = id; - this.activeSignal.value = client; - } - - public async remove(id: ConnectionId): Promise { - const client = this.clients.get(id); - if (!client) return; - await client.disconnect().catch(() => {}); - this.unregister(id); - } - - /** - * Removes the mapping without disconnecting the client. Use when the caller - * has already torn down the transport itself (e.g. the legacy useConnections - * flow in packages/web). - */ - public unregister(id: ConnectionId): void { - if (!this.clients.has(id)) return; - this.clients.delete(id); - if (this.activeIdSignal.value === id) { - const next = this.clients.keys().next(); - this.setActive(next.done ? null : (next.value as ConnectionId)); - } - this.snapshot(); - } - - public get size(): number { - return this.clients.size; - } - - private snapshot(): void { - this.backing.value = Array.from(this.clients.entries()).map( - ([id, client]) => ({ - id, - client, - }), - ); - } -} diff --git a/packages/sdk/src/core/registry/index.ts b/packages/sdk/src/core/registry/index.ts deleted file mode 100644 index 690d0f246..000000000 --- a/packages/sdk/src/core/registry/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { MeshRegistry } from "./MeshRegistry.ts"; -export type { ConnectionId, RegistryEntry } from "./MeshRegistry.ts"; diff --git a/packages/sdk/src/core/signals/createStore.test.ts b/packages/sdk/src/core/signals/createStore.test.ts deleted file mode 100644 index 7349caeef..000000000 --- a/packages/sdk/src/core/signals/createStore.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { SignalMap, createStore, toReadonly } from "./createStore.ts"; - -describe("createStore", () => { - it("exposes initial value through the readable facade", () => { - const store = createStore(7); - expect(store.read.value).toBe(7); - }); - - it("propagates writes to subscribers", () => { - const store = createStore("a"); - const seen: string[] = []; - const unsubscribe = store.read.subscribe((v) => seen.push(v)); - store.write.value = "b"; - store.write.value = "c"; - unsubscribe(); - store.write.value = "d"; - expect(seen).toEqual(["b", "c"]); - }); - - it("peek does not register a reactive read", () => { - const store = createStore(1); - expect(store.read.peek()).toBe(1); - store.write.value = 2; - expect(store.read.peek()).toBe(2); - }); -}); - -describe("SignalMap", () => { - it("emits a new snapshot on each mutation", () => { - const map = new SignalMap(); - const seen: ReadonlyArray[] = []; - map.read.subscribe((v) => seen.push(v)); - - map.set(1, "one"); - map.set(2, "two"); - map.delete(1); - - expect(seen.length).toBe(3); - expect(seen[2]).toEqual(["two"]); - expect(map.size).toBe(1); - expect(map.get(2)).toBe("two"); - }); - - it("clear is a no-op when already empty", () => { - const map = new SignalMap(); - let calls = 0; - map.read.subscribe(() => calls++); - map.clear(); - expect(calls).toBe(0); - }); -}); - -describe("toReadonly", () => { - it("wraps a preact signal without exposing mutation", () => { - const store = createStore(0); - const readonly = toReadonly(store.write); - expect(readonly.value).toBe(0); - store.write.value = 99; - expect(readonly.value).toBe(99); - }); -}); diff --git a/packages/sdk/src/core/signals/createStore.ts b/packages/sdk/src/core/signals/createStore.ts deleted file mode 100644 index 55b3cd4a0..000000000 --- a/packages/sdk/src/core/signals/createStore.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { - type ReadonlySignal as PreactReadonlySignal, - type Signal, - signal, -} from "@preact/signals-core"; - -/** - * Reactive read-only view of a signal. - * - * Compatible with React's useSyncExternalStore contract: consumers subscribe - * for change notifications and call `value` / `peek()` to read. - */ -export interface ReadonlySignal { - readonly value: T; - peek(): T; - subscribe(listener: (value: T) => void): () => void; -} - -/** - * Wraps a preact signal into the SDK's ReadonlySignal interface. The listener - * is invoked asynchronously on every change. Returns both the writable signal - * (for slice-internal use) and the readable facade (for external consumption). - */ -export function createStore(initial: T): { - write: Signal; - read: ReadonlySignal; -} { - const write = signal(initial); - return { write, read: toReadonly(write) }; -} - -export function toReadonly( - s: Signal | PreactReadonlySignal, -): ReadonlySignal { - return { - get value() { - return s.value; - }, - peek: () => s.peek(), - subscribe: (listener) => { - let first = true; - return s.subscribe((v) => { - if (first) { - first = false; - return; - } - listener(v); - }); - }, - }; -} - -/** - * Keyed collection built on a single backing signal, emitting a new array - * snapshot on each mutation. Sufficient for nodes/messages where consumers - * subscribe to the whole list and filter locally. - */ -export class SignalMap { - private readonly inner: Map = new Map(); - private readonly backing: Signal>; - public readonly read: ReadonlySignal>; - - constructor() { - this.backing = signal>([]); - this.read = toReadonly(this.backing); - } - - get(key: K): V | undefined { - return this.inner.get(key); - } - - has(key: K): boolean { - return this.inner.has(key); - } - - set(key: K, value: V): void { - this.inner.set(key, value); - this.backing.value = Array.from(this.inner.values()); - } - - delete(key: K): boolean { - const removed = this.inner.delete(key); - if (removed) { - this.backing.value = Array.from(this.inner.values()); - } - return removed; - } - - clear(): void { - if (this.inner.size === 0) { - return; - } - this.inner.clear(); - this.backing.value = []; - } - - get size(): number { - return this.inner.size; - } -} diff --git a/packages/sdk/src/core/signals/index.ts b/packages/sdk/src/core/signals/index.ts deleted file mode 100644 index 7496248a4..000000000 --- a/packages/sdk/src/core/signals/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { createStore, SignalMap, toReadonly } from "./createStore.ts"; -export type { ReadonlySignal } from "./createStore.ts"; diff --git a/packages/sdk/src/core/testing/createFakeTransport.ts b/packages/sdk/src/core/testing/createFakeTransport.ts deleted file mode 100644 index 706e3f659..000000000 --- a/packages/sdk/src/core/testing/createFakeTransport.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { create, toBinary } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { toDeviceStream } from "../packet-codec/toDevice.ts"; -import { fromDeviceStream } from "../packet-codec/fromDevice.ts"; -import type { Transport } from "../transport/Transport.ts"; - -export interface FakeTransportHandle { - transport: Transport; - respond: FakeResponder; - /** Exposes what the client has written to the device (already unframed). */ - sent: Uint8Array[]; - /** Closes the simulated connection. */ - close(): Promise; -} - -type MyNodeInfoInit = Parameters< - typeof create ->[1]; -type NodeInfoInit = Parameters< - typeof create ->[1]; - -export interface FakeResponder { - withMyNodeInfo(info: MyNodeInfoInit & { myNodeNum: number }): void; - withNodeInfo(info: NodeInfoInit & { num: number }): void; - withConfigCompleteId(id: number): void; - withMeshPacket(packet: Protobuf.Mesh.MeshPacket): void; - withRaw(fromRadio: Protobuf.Mesh.FromRadio): void; -} - -/** - * In-memory Transport implementation for tests. The client reads framed bytes - * from `fromDevice` and writes framed bytes to `toDevice`; the responder - * enqueues `FromRadio` messages that get framed and delivered to the client. - */ -export function createFakeTransport(): FakeTransportHandle { - const sent: Uint8Array[] = []; - let fromDeviceController: - | ReadableStreamDefaultController - | undefined; - - const fromDeviceRaw = new ReadableStream({ - start(controller) { - fromDeviceController = controller; - }, - }); - - const toDevice = new WritableStream({ - write(chunk) { - // Strip 0x94 0xC3 framing to record the raw ToRadio bytes. - if (chunk[0] === 0x94 && chunk[1] === 0xc3) { - const msb = chunk[2] ?? 0; - const lsb = chunk[3] ?? 0; - sent.push(chunk.subarray(4, 4 + (msb << 8) + lsb)); - } else { - sent.push(chunk); - } - }, - }); - - const fromDevice = fromDeviceRaw.pipeThrough(fromDeviceStream()); - - const framed = new WritableStream({ - write(chunk) { - fromDeviceController?.enqueue(chunk); - }, - }); - const responderFrame = toDeviceStream(); - responderFrame.readable.pipeTo(framed).catch(() => { - // stream closed - }); - const responderWriter = responderFrame.writable.getWriter(); - - function enqueueFromRadio(message: Protobuf.Mesh.FromRadio): void { - const bytes = toBinary(Protobuf.Mesh.FromRadioSchema, message); - responderWriter.write(bytes); - } - - const respond: FakeResponder = { - withMyNodeInfo(partial) { - enqueueFromRadio( - create(Protobuf.Mesh.FromRadioSchema, { - payloadVariant: { - case: "myInfo", - value: create(Protobuf.Mesh.MyNodeInfoSchema, partial), - }, - }), - ); - }, - withNodeInfo(partial) { - enqueueFromRadio( - create(Protobuf.Mesh.FromRadioSchema, { - payloadVariant: { - case: "nodeInfo", - value: create(Protobuf.Mesh.NodeInfoSchema, partial), - }, - }), - ); - }, - withConfigCompleteId(id) { - enqueueFromRadio( - create(Protobuf.Mesh.FromRadioSchema, { - payloadVariant: { case: "configCompleteId", value: id }, - }), - ); - }, - withMeshPacket(packet) { - enqueueFromRadio( - create(Protobuf.Mesh.FromRadioSchema, { - payloadVariant: { case: "packet", value: packet }, - }), - ); - }, - withRaw(fromRadio) { - enqueueFromRadio(fromRadio); - }, - }; - - const transport: Transport = { - toDevice, - fromDevice, - async disconnect() { - try { - fromDeviceController?.close(); - } catch { - // already closed - } - }, - }; - - return { - transport, - respond, - sent, - async close() { - await responderWriter.close().catch(() => {}); - await transport.disconnect(); - }, - }; -} diff --git a/packages/sdk/src/core/testing/index.ts b/packages/sdk/src/core/testing/index.ts deleted file mode 100644 index e6c482a73..000000000 --- a/packages/sdk/src/core/testing/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -export { createFakeTransport } from "./createFakeTransport.ts"; -export { - type AdminMessageInterceptor, - type HeldSend, - interceptAdminMessages, -} from "./interceptAdminMessages.ts"; -export type { - FakeResponder, - FakeTransportHandle, -} from "./createFakeTransport.ts"; diff --git a/packages/sdk/src/core/testing/interceptAdminMessages.ts b/packages/sdk/src/core/testing/interceptAdminMessages.ts deleted file mode 100644 index 81cea27f9..000000000 --- a/packages/sdk/src/core/testing/interceptAdminMessages.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { fromBinary } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import type { MeshClient } from "../client/MeshClient.ts"; - -type AdminCase = NonNullable< - Protobuf.Admin.AdminMessage["payloadVariant"]["case"] ->; -type ConfigVariant = Protobuf.Config.Config["payloadVariant"]; -type ModuleConfigVariant = Protobuf.ModuleConfig.ModuleConfig["payloadVariant"]; -type ConfigCase = NonNullable; -type ModuleConfigCase = NonNullable; -type ConfigValue = Extract< - ConfigVariant, - { case: K } ->["value"]; -type ModuleConfigValue = Extract< - ModuleConfigVariant, - { case: K } ->["value"]; - -export interface HeldSend { - /** Resolves once the send is being held. */ - reached: Promise; - release(): void; -} - -export interface AdminMessageInterceptor { - /** Every admin message sent, decoded, in order. */ - sent: Protobuf.Admin.AdminMessage[]; - cases(): (AdminCase | undefined)[]; - /** Hold the next send of `adminCase` open until released. */ - hold(adminCase: AdminCase): HeldSend; - /** Make the next send of `adminCase` fail. */ - failNext(adminCase: AdminCase): void; - sentConfig(section: K): ConfigValue | undefined; - sentModuleConfig( - section: K, - ): ModuleConfigValue | undefined; -} - -/** - * Replace `client.sendPacket` so a test can see the admin messages a commit - * sends, and pause or fail individual sends. - */ -export function interceptAdminMessages( - client: MeshClient, -): AdminMessageInterceptor { - const sent: Protobuf.Admin.AdminMessage[] = []; - const holds: { - adminCase: AdminCase; - onReached: () => void; - released: Promise; - }[] = []; - const failures: AdminCase[] = []; - - client.sendPacket = (async (payload: Uint8Array) => { - const admin = fromBinary(Protobuf.Admin.AdminMessageSchema, payload); - sent.push(admin); - const adminCase = admin.payloadVariant.case; - - const failure = failures.indexOf(adminCase as AdminCase); - if (failure !== -1) { - failures.splice(failure, 1); - throw new Error(`send failed: ${adminCase}`); - } - - const index = holds.findIndex((h) => h.adminCase === adminCase); - const hold = index === -1 ? undefined : holds.splice(index, 1)[0]; - if (hold) { - hold.onReached(); - await hold.released; - } - return 1; - }) as MeshClient["sendPacket"]; - - return { - sent, - cases: () => sent.map((admin) => admin.payloadVariant.case), - hold(adminCase) { - let onReached!: () => void; - let release!: () => void; - const reached = new Promise((resolve) => { - onReached = resolve; - }); - const released = new Promise((resolve) => { - release = resolve; - }); - holds.push({ adminCase, onReached, released }); - return { reached, release }; - }, - failNext(adminCase) { - failures.push(adminCase); - }, - sentConfig(section: K) { - for (const admin of sent) { - if (admin.payloadVariant.case !== "setConfig") continue; - const variant = admin.payloadVariant.value.payloadVariant; - if (variant.case === section) { - return variant.value as ConfigValue; - } - } - return undefined; - }, - sentModuleConfig(section: K) { - for (const admin of sent) { - if (admin.payloadVariant.case !== "setModuleConfig") continue; - const variant = admin.payloadVariant.value.payloadVariant; - if (variant.case === section) { - return variant.value as ModuleConfigValue; - } - } - return undefined; - }, - }; -} diff --git a/packages/sdk/src/core/transport/Transport.ts b/packages/sdk/src/core/transport/Transport.ts deleted file mode 100644 index d95eb749e..000000000 --- a/packages/sdk/src/core/transport/Transport.ts +++ /dev/null @@ -1,40 +0,0 @@ -export enum DeviceStatusEnum { - DeviceRestarting = 1, - DeviceDisconnected = 2, - DeviceConnecting = 3, - DeviceReconnecting = 4, - DeviceConnected = 5, - DeviceConfiguring = 6, - DeviceConfigured = 7, - DeviceError = 8, -} - -interface Packet { - type: "packet"; - data: Uint8Array; -} - -interface DebugLog { - type: "debug"; - data: string; -} - -interface StatusEvent { - type: "status"; - data: { status: DeviceStatusEnum; reason?: string }; -} - -export type DeviceOutput = Packet | DebugLog | StatusEvent; - -export interface Transport { - toDevice: WritableStream; - fromDevice: ReadableStream; - disconnect(): Promise; -} - -export interface HttpRetryConfig { - maxRetries: number; - initialDelayMs: number; - maxDelayMs: number; - backoffFactor: number; -} diff --git a/packages/sdk/src/core/transport/index.ts b/packages/sdk/src/core/transport/index.ts deleted file mode 100644 index bfa129a52..000000000 --- a/packages/sdk/src/core/transport/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export type { DeviceOutput, HttpRetryConfig, Transport } from "./Transport.ts"; -export { DeviceStatusEnum } from "./Transport.ts"; diff --git a/packages/sdk/src/core/types.ts b/packages/sdk/src/core/types.ts deleted file mode 100644 index ddf8097e6..000000000 --- a/packages/sdk/src/core/types.ts +++ /dev/null @@ -1,127 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; - -export type { - DeviceOutput, - HttpRetryConfig, - Transport, -} from "./transport/Transport.ts"; -export { DeviceStatusEnum } from "./transport/Transport.ts"; - -export interface QueueItem { - id: number; - data: Uint8Array; - sent: boolean; - added: Date; - promise: Promise; -} - -export type LogEventPacket = LogEvent & { date: Date }; - -export type PacketDestination = "broadcast" | "direct"; - -export interface UnhandledPayload { - portnum: Protobuf.Portnums.PortNum; - payload: Uint8Array; -} - -export interface PacketMetadata { - id: number; - rxTime: Date; - type: PacketDestination; - from: number; - to: number; - channel: ChannelNumber; - data: T; - /** Data.request_id: the packet this one answers or acks. */ - requestId?: number; - /** The sender signed the packet with XEdDSA and the device verified it. */ - xeddsaSigned?: boolean; - /** Firmware's verdict on an ack's proof of delivery (2.8.1+). */ - ackProofStatus?: Protobuf.Mesh.MeshPacket_AckProofStatus; - /** - * SNR in dB as our radio heard the packet, or undefined when it carried no - * measurement. 0 dB is a real reading. - */ - rxSnr?: number; - /** RSSI in dBm as our radio heard the packet, or undefined when unset. */ - rxRssi?: number; - /** Hops the packet took to reach us, or undefined when it can't be told. */ - hopsAway?: number; - /** The packet reached the mesh through an MQTT gateway. */ - viaMqtt?: boolean; - /** How the packet reached our radio (LoRa, MQTT, UDP, API...). */ - transportMechanism?: Protobuf.Mesh.MeshPacket_TransportMechanism; -} - -export enum EmitterScope { - MeshDevice = 1, - SerialConnection = 2, - NodeSerialConnection = 3, - BleConnection = 4, - HttpConnection = 5, -} - -export enum Emitter { - Constructor = 0, - SendText = 1, - SendWaypoint = 2, - SendPacket = 3, - SendRaw = 4, - SetConfig = 5, - SetModuleConfig = 6, - ConfirmSetConfig = 7, - SetOwner = 8, - SetChannel = 9, - ConfirmSetChannel = 10, - ClearChannel = 11, - GetChannel = 12, - GetAllChannels = 13, - GetConfig = 14, - GetModuleConfig = 15, - GetOwner = 16, - Configure = 17, - HandleFromRadio = 18, - HandleMeshPacket = 19, - Connect = 20, - Ping = 21, - ReadFromRadio = 22, - WriteToRadio = 23, - SetDebugMode = 24, - GetMetadata = 25, - ResetNodes = 26, - Shutdown = 27, - Reboot = 28, - RebootOta = 29, - FactoryReset = 30, - EnterDfuMode = 31, - RemoveNodeByNum = 32, - SetCannedMessages = 33, - Disconnect = 34, - ConnectionStatus = 35, -} - -export interface LogEvent { - scope: EmitterScope; - emitter: Emitter; - message: string; - level: Protobuf.Mesh.LogRecord_Level; - packet?: Uint8Array; -} - -export enum ChannelNumber { - Primary = 0, - Channel1 = 1, - Channel2 = 2, - Channel3 = 3, - Channel4 = 4, - Channel5 = 5, - Channel6 = 6, - Admin = 7, -} - -export type Destination = number | "self" | "broadcast"; - -export interface PacketError { - id: number; - error: Protobuf.Mesh.Routing_Error; -} diff --git a/packages/sdk/src/core/xmodem/Xmodem.ts b/packages/sdk/src/core/xmodem/Xmodem.ts deleted file mode 100644 index 1f1055985..000000000 --- a/packages/sdk/src/core/xmodem/Xmodem.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { create, toBinary } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import crc16ccitt from "crc/calculators/crc16ccitt"; - -type XmodemProps = (toRadio: Uint8Array, id?: number) => Promise; - -export class Xmodem { - private sendRaw: XmodemProps; - private rxBuffer: Uint8Array[]; - private txBuffer: Uint8Array[]; - private textEncoder: TextEncoder; - private counter: number; - - constructor(sendRaw: XmodemProps) { - this.sendRaw = sendRaw; - this.rxBuffer = []; - this.txBuffer = []; - this.textEncoder = new TextEncoder(); - this.counter = 0; - } - - async downloadFile(filename: string): Promise { - return await this.sendCommand( - Protobuf.Xmodem.XModem_Control.STX, - this.textEncoder.encode(filename), - 0, - ); - } - - async uploadFile(filename: string, data: Uint8Array): Promise { - for (let i = 0; i < data.length; i += 128) { - this.txBuffer.push(data.slice(i, i + 128)); - } - - return await this.sendCommand( - Protobuf.Xmodem.XModem_Control.SOH, - this.textEncoder.encode(filename), - 0, - ); - } - - async sendCommand( - command: Protobuf.Xmodem.XModem_Control, - buffer?: Uint8Array, - sequence?: number, - crc16?: number, - ): Promise { - const toRadio = create(Protobuf.Mesh.ToRadioSchema, { - payloadVariant: { - case: "xmodemPacket", - value: { - buffer, - control: command, - seq: sequence, - crc16: crc16, - }, - }, - }); - return await this.sendRaw(toBinary(Protobuf.Mesh.ToRadioSchema, toRadio)); - } - - async handlePacket(packet: Protobuf.Xmodem.XModem): Promise { - await new Promise((resolve) => setTimeout(resolve, 100)); - - switch (packet.control) { - case Protobuf.Xmodem.XModem_Control.NUL: { - break; - } - case Protobuf.Xmodem.XModem_Control.SOH: { - this.counter = packet.seq; - if (this.validateCrc16(packet)) { - this.rxBuffer[this.counter] = packet.buffer; - return this.sendCommand(Protobuf.Xmodem.XModem_Control.ACK); - } - return await this.sendCommand( - Protobuf.Xmodem.XModem_Control.NAK, - undefined, - packet.seq, - ); - } - case Protobuf.Xmodem.XModem_Control.STX: { - break; - } - case Protobuf.Xmodem.XModem_Control.EOT: { - break; - } - case Protobuf.Xmodem.XModem_Control.ACK: { - this.counter++; - if (this.txBuffer[this.counter - 1]) { - return this.sendCommand( - Protobuf.Xmodem.XModem_Control.SOH, - this.txBuffer[this.counter - 1], - this.counter, - crc16ccitt(this.txBuffer[this.counter - 1] ?? new Uint8Array()), - ); - } - if (this.counter === this.txBuffer.length + 1) { - return this.sendCommand(Protobuf.Xmodem.XModem_Control.EOT); - } - this.clear(); - break; - } - case Protobuf.Xmodem.XModem_Control.NAK: { - return this.sendCommand( - Protobuf.Xmodem.XModem_Control.SOH, - this.txBuffer[this.counter], - this.counter, - crc16ccitt(this.txBuffer[this.counter - 1] ?? new Uint8Array()), - ); - } - case Protobuf.Xmodem.XModem_Control.CAN: { - this.clear(); - break; - } - case Protobuf.Xmodem.XModem_Control.CTRLZ: { - break; - } - } - - return Promise.resolve(0); - } - - validateCrc16(packet: Protobuf.Xmodem.XModem): boolean { - return crc16ccitt(packet.buffer) === packet.crc16; - } - - clear() { - this.counter = 0; - this.rxBuffer = []; - this.txBuffer = []; - } -} diff --git a/packages/sdk/src/features/channels/ChannelsClient.test.ts b/packages/sdk/src/features/channels/ChannelsClient.test.ts deleted file mode 100644 index 220632e27..000000000 --- a/packages/sdk/src/features/channels/ChannelsClient.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { describe, expect, it } from "vitest"; -import { MeshClient } from "../../core/client/MeshClient.ts"; -import { createFakeTransport } from "../../core/testing/createFakeTransport.ts"; - -describe("ChannelsClient", () => { - it("collects channels by index from onChannelPacket", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - - client.events.onChannelPacket.dispatch( - create(Protobuf.Channel.ChannelSchema, { - index: 0, - role: Protobuf.Channel.Channel_Role.PRIMARY, - }), - ); - client.events.onChannelPacket.dispatch( - create(Protobuf.Channel.ChannelSchema, { - index: 1, - role: Protobuf.Channel.Channel_Role.SECONDARY, - }), - ); - - expect(client.channels.list.value.length).toBe(2); - expect(client.channels.get(0)?.role).toBe( - Protobuf.Channel.Channel_Role.PRIMARY, - ); - expect(client.channels.get(1)?.role).toBe( - Protobuf.Channel.Channel_Role.SECONDARY, - ); - }); - - it("keeps one beacon offer per sender and skips offers without a channel", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const offer = (from: number, message: string, withChannel = true) => - client.events.onMeshBeaconPacket.dispatch({ - id: 1, - from, - to: 0xffffffff, - type: "broadcast", - channel: 0, - rxTime: new Date(), - data: create(Protobuf.MeshBeacon.MeshBeaconSchema, { - message, - offerChannel: withChannel - ? create(Protobuf.Channel.ChannelSettingsSchema, { name: "x" }) - : undefined, - }), - }); - - offer(1, "first"); - offer(2, "other"); - offer(1, "second"); - offer(3, "no channel", false); - - expect( - client.channels.beaconOffers.value.map((o) => [o.from, o.beacon.message]), - ).toEqual([ - [1, "second"], - [2, "other"], - ]); - client.channels.dismissBeaconOffer(1); - expect(client.channels.beaconOffers.value.map((o) => o.from)).toEqual([2]); - }); -}); diff --git a/packages/sdk/src/features/channels/ChannelsClient.ts b/packages/sdk/src/features/channels/ChannelsClient.ts deleted file mode 100644 index 6d5f3cbed..000000000 --- a/packages/sdk/src/features/channels/ChannelsClient.ts +++ /dev/null @@ -1,78 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; -import type { Result } from "better-result"; -import type { MeshClient } from "../../core/client/MeshClient.ts"; -import { - createStore, - type ReadonlySignal, -} from "../../core/signals/createStore.ts"; -import { - clearChannel, - getChannel, - setChannel, -} from "./application/ChannelUseCases.ts"; -import type { Channel } from "./domain/Channel.ts"; -import type { MeshBeaconOffer } from "./domain/MeshBeaconOffer.ts"; -import { ChannelMapper } from "./infrastructure/ChannelMapper.ts"; -import { ChannelsStore } from "./state/channelsStore.ts"; - -export class ChannelsClient { - private readonly client: MeshClient; - private readonly store: ChannelsStore; - public readonly list: ReadonlySignal>; - private readonly offersStore = createStore>( - [], - ); - /** - * Mesh Beacon invitations heard this session, newest first, one per - * sender. Our own beacons and beacons without a channel are skipped. - */ - public readonly beaconOffers: ReadonlySignal>; - - constructor(client: MeshClient) { - this.client = client; - this.store = new ChannelsStore(); - this.list = this.store.read; - this.beaconOffers = this.offersStore.read; - - client.events.onChannelPacket.subscribe((ch) => { - this.store.set(ch.index, ChannelMapper.fromProto(ch)); - }); - - client.events.onMeshBeaconPacket.subscribe((packet) => { - if (packet.from === client.myNodeNum) return; - if (!packet.data.offerChannel) return; - const others = this.offersStore.write - .peek() - .filter((o) => o.from !== packet.from); - this.offersStore.write.value = [ - { from: packet.from, rxTime: packet.rxTime, beacon: packet.data }, - ...others, - ]; - }); - } - - /** Forget an offer, e.g. once the user joined or dismissed it. */ - public dismissBeaconOffer(from: number): void { - this.offersStore.write.value = this.offersStore.write - .peek() - .filter((o) => o.from !== from); - } - - public get(index: number): Channel | undefined { - return this.store.get(index); - } - - public set( - channel: Protobuf.Channel.Channel, - ): Promise> { - return setChannel(this.client, channel); - } - - public requestChannel(index: number): Promise> { - return getChannel(this.client, index); - } - - public clear(index: number): Promise> { - return clearChannel(this.client, index); - } -} diff --git a/packages/sdk/src/features/channels/application/ChannelUseCases.ts b/packages/sdk/src/features/channels/application/ChannelUseCases.ts deleted file mode 100644 index 4bf9812a8..000000000 --- a/packages/sdk/src/features/channels/application/ChannelUseCases.ts +++ /dev/null @@ -1,46 +0,0 @@ -import * as Protobuf from "@meshtastic/protobufs"; -import { create } from "@bufbuild/protobuf"; -import { Result } from "better-result"; -import type { MeshClient } from "../../../core/client/MeshClient.ts"; -import { sendAdminMessage } from "../../device/infrastructure/AdminMessageSender.ts"; - -export async function setChannel( - client: MeshClient, - channel: Protobuf.Channel.Channel, -): Promise> { - try { - const id = await sendAdminMessage(client, { - case: "setChannel", - value: channel, - }); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} - -export async function getChannel( - client: MeshClient, - index: number, -): Promise> { - try { - const id = await sendAdminMessage(client, { - case: "getChannelRequest", - value: index + 1, - }); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} - -export async function clearChannel( - client: MeshClient, - index: number, -): Promise> { - const channel = create(Protobuf.Channel.ChannelSchema, { - index, - role: Protobuf.Channel.Channel_Role.DISABLED, - }); - return setChannel(client, channel); -} diff --git a/packages/sdk/src/features/channels/domain/Channel.ts b/packages/sdk/src/features/channels/domain/Channel.ts deleted file mode 100644 index 7c745ada7..000000000 --- a/packages/sdk/src/features/channels/domain/Channel.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; - -export interface Channel { - readonly index: number; - readonly role: Protobuf.Channel.Channel_Role; - readonly settings?: Protobuf.Channel.ChannelSettings; -} diff --git a/packages/sdk/src/features/channels/domain/MeshBeaconOffer.test.ts b/packages/sdk/src/features/channels/domain/MeshBeaconOffer.test.ts deleted file mode 100644 index 29874ea07..000000000 --- a/packages/sdk/src/features/channels/domain/MeshBeaconOffer.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { describe, expect, it } from "vitest"; -import { - beaconJoinChannelSet, - beaconJoinOption, - isBeaconAlreadyJoined, -} from "./MeshBeaconOffer.ts"; - -const Preset = Protobuf.Config.Config_LoRaConfig_ModemPreset; -const Region = Protobuf.Config.Config_LoRaConfig_RegionCode; - -const lora = ( - init: Omit, "$typeName"> = {}, -) => - create(Protobuf.Config.Config_LoRaConfigSchema, { - usePreset: true, - modemPreset: Preset.LONG_FAST, - region: Region.US, - ...init, - }); - -const channel = (name: string, psk = new Uint8Array([1])) => - create(Protobuf.Channel.ChannelSettingsSchema, { name, psk }); - -const beacon = ( - init: Omit, "$typeName"> = {}, -) => - create(Protobuf.MeshBeacon.MeshBeaconSchema, { - message: "join", - offerChannel: channel("Hikers", new Uint8Array([7, 7])), - ...init, - }); - -describe("beaconJoinOption", () => { - it("is none without an offered channel", () => { - expect( - beaconJoinOption(beacon({ offerChannel: undefined }), lora(), []), - ).toBe("none"); - }); - - it("adds when the offered channel hashes like the primary", () => { - const radio = [channel("Hikers")]; - expect(beaconJoinOption(beacon(), lora(), radio)).toBe("add"); - }); - - it("treats an empty name as the preset name on both sides", () => { - const offer = beacon({ offerChannel: channel("") }); - expect(beaconJoinOption(offer, lora(), [channel("")])).toBe("add"); - expect(beaconJoinOption(offer, lora(), [channel("LongFast")])).toBe("add"); - }); - - it("switches when the preset or region differ", () => { - const radio = [channel("Hikers")]; - expect( - beaconJoinOption( - beacon({ offerPreset: Preset.SHORT_FAST }), - lora(), - radio, - ), - ).toBe("switch"); - expect( - beaconJoinOption(beacon({ offerRegion: Region.EU_868 }), lora(), radio), - ).toBe("switch"); - }); - - it("switches when the radio is pinned to a slot", () => { - expect( - beaconJoinOption(beacon(), lora({ channelNum: 5 }), [channel("Hikers")]), - ).toBe("switch"); - }); - - it("switches when the names differ, since the slots may", () => { - expect(beaconJoinOption(beacon(), lora(), [channel("LongFast")])).toBe( - "switch", - ); - }); -}); - -describe("beaconJoinChannelSet", () => { - it("turns position sharing off on the offered channel", () => { - const offered = channel("Hikers"); - offered.moduleSettings = create(Protobuf.Channel.ModuleSettingsSchema, { - positionPrecision: 32, - }); - const set = beaconJoinChannelSet( - beacon({ offerChannel: offered }), - "add", - lora(), - ); - expect(set?.settings[0]?.moduleSettings?.positionPrecision).toBe(0); - expect(set?.loraConfig).toBeUndefined(); - }); - - it("switches with a fresh LoRa config carrying the offered preset", () => { - const set = beaconJoinChannelSet( - beacon({ offerPreset: Preset.MEDIUM_FAST }), - "switch", - lora({ channelNum: 9, overrideFrequency: 915 }), - ); - expect(set?.loraConfig?.modemPreset).toBe(Preset.MEDIUM_FAST); - expect(set?.loraConfig?.region).toBe(Region.US); - expect(set?.loraConfig?.channelNum).toBe(0); - expect(set?.loraConfig?.overrideFrequency).toBe(0); - }); -}); - -describe("isBeaconAlreadyJoined", () => { - it("matches a channel with the same name and key", () => { - const radio = [channel(""), channel("Hikers", new Uint8Array([7, 7]))]; - expect(isBeaconAlreadyJoined(beacon(), lora(), radio)).toBe(true); - }); - - it("does not match the same name with a different key", () => { - const radio = [channel(""), channel("Hikers", new Uint8Array([8]))]; - expect(isBeaconAlreadyJoined(beacon(), lora(), radio)).toBe(false); - }); -}); diff --git a/packages/sdk/src/features/channels/domain/MeshBeaconOffer.ts b/packages/sdk/src/features/channels/domain/MeshBeaconOffer.ts deleted file mode 100644 index e1eb45b0b..000000000 --- a/packages/sdk/src/features/channels/domain/MeshBeaconOffer.ts +++ /dev/null @@ -1,145 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; - -type LoRaConfig = Protobuf.Config.Config_LoRaConfig; -type ChannelSettings = Protobuf.Channel.ChannelSettings; -type MeshBeacon = Protobuf.MeshBeacon.MeshBeacon; - -/** A Mesh Beacon invitation heard from another node. */ -export interface MeshBeaconOffer { - readonly from: number; - readonly rxTime: Date; - readonly beacon: MeshBeacon; -} - -/** - * How an offer can be joined. "add" puts the channel in a free secondary - * slot with no reboot; "switch" retunes the radio onto the offered mesh and - * reboots it; "none" means the beacon offers no channel. - */ -export type BeaconJoinOption = "add" | "switch" | "none"; - -/** - * The name firmware hashes for the frequency slot: an empty channel name - * stands for the modem preset's name. - */ -function effectiveName( - settings: ChannelSettings | undefined, - lora: LoRaConfig, -) { - if (settings?.name) return settings.name; - const preset = - Protobuf.Config.Config_LoRaConfig_ModemPreset[lora.modemPreset]; - return (preset ?? "") - .toLowerCase() - .replace(/(^|_)([a-z])/g, (_, __, c: string) => c.toUpperCase()); -} - -const sameBytes = (a: Uint8Array, b: Uint8Array) => - a.length === b.length && a.every((v, i) => v === b[i]); - -/** A blank secondary slot left behind by a removed channel. */ -const isPlaceholder = (s: ChannelSettings) => !s.name && s.psk.length === 0; - -/** - * True when the offered channel is already on the radio: same effective name - * and key under the preset the offer would run on. - */ -export function isBeaconAlreadyJoined( - beacon: MeshBeacon, - lora: LoRaConfig | undefined, - channels: ReadonlyArray, -): boolean { - const offer = beacon.offerChannel; - if (!offer || !lora || channels.length === 0) return false; - const offerLora = create(Protobuf.Config.Config_LoRaConfigSchema, { - ...lora, - usePreset: true, - modemPreset: beacon.offerPreset ?? lora.modemPreset, - }); - const offerName = effectiveName(offer, offerLora); - return channels.some( - (s, index) => - (index === 0 || !isPlaceholder(s)) && - effectiveName(s, lora) === offerName && - sameBytes(s.psk, offer.psk), - ); -} - -/** - * Decide how to join, after the Android app's beaconJoinOption. Secondary - * channels ride the primary's frequency slot, so adding only works when the - * offered mesh is on the same slot under the same preset and region. - * - * Android computes both slots from the regional band plan. The web client - * has no band plan, so it only reports "add" when the slots are certainly - * equal: the offer advertises the radio's own slot, or both channels hash - * the same effective name. Anything else is a "switch", which costs a reboot - * but always works. - */ -export function beaconJoinOption( - beacon: MeshBeacon, - lora: LoRaConfig | undefined, - channels: ReadonlyArray, -): BeaconJoinOption { - const offer = beacon.offerChannel; - if (!offer) return "none"; - if (!lora) return "switch"; - const presetMatches = - beacon.offerPreset === undefined || - (lora.usePreset && beacon.offerPreset === lora.modemPreset); - const regionMatches = - beacon.offerRegion === Protobuf.Config.Config_LoRaConfig_RegionCode.UNSET || - beacon.offerRegion === lora.region; - if (!presetMatches || !regionMatches) return "switch"; - - const advertised = beacon.offerFrequencySlot; - if (advertised !== undefined && advertised > 0) { - return lora.channelNum === advertised ? "add" : "switch"; - } - // A radio pinned to a slot can't be compared with a hashed one. - if (lora.channelNum !== 0) return "switch"; - return effectiveName(channels[0], lora) === effectiveName(offer, lora) - ? "add" - : "switch"; -} - -/** - * The ChannelSet to hand the channel import flow. "add" carries only the - * channel. "switch" also carries a fresh LoRa config (not a copy of the - * current one, so no stale frequency or slot pin survives) with the offered - * preset and region. Position sharing is always turned off on the offered - * channel, so joining a stranger's mesh never shares our location. - */ -export function beaconJoinChannelSet( - beacon: MeshBeacon, - option: BeaconJoinOption, - lora: LoRaConfig | undefined, -): Protobuf.AppOnly.ChannelSet | undefined { - const offer = beacon.offerChannel; - if (!offer || option === "none") return undefined; - const channel = create(Protobuf.Channel.ChannelSettingsSchema, { - ...offer, - moduleSettings: create(Protobuf.Channel.ModuleSettingsSchema, { - isMuted: offer.moduleSettings?.isMuted ?? false, - positionPrecision: 0, - }), - }); - if (option === "add") { - return create(Protobuf.AppOnly.ChannelSetSchema, { settings: [channel] }); - } - const Region = Protobuf.Config.Config_LoRaConfig_RegionCode; - return create(Protobuf.AppOnly.ChannelSetSchema, { - settings: [channel], - loraConfig: create(Protobuf.Config.Config_LoRaConfigSchema, { - usePreset: true, - modemPreset: beacon.offerPreset ?? lora?.modemPreset, - // A full LoRaConfig replacement with region UNSET would stop transmit. - region: - beacon.offerRegion !== Region.UNSET ? beacon.offerRegion : lora?.region, - hopLimit: 3, - txEnabled: true, - channelNum: beacon.offerFrequencySlot ?? 0, - }), - }); -} diff --git a/packages/sdk/src/features/channels/index.ts b/packages/sdk/src/features/channels/index.ts deleted file mode 100644 index d798f1fe7..000000000 --- a/packages/sdk/src/features/channels/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -export { ChannelsClient } from "./ChannelsClient.ts"; -export type { Channel } from "./domain/Channel.ts"; -export { ChannelMapper } from "./infrastructure/ChannelMapper.ts"; -export { - beaconJoinChannelSet, - beaconJoinOption, - isBeaconAlreadyJoined, -} from "./domain/MeshBeaconOffer.ts"; -export type { - BeaconJoinOption, - MeshBeaconOffer, -} from "./domain/MeshBeaconOffer.ts"; diff --git a/packages/sdk/src/features/channels/infrastructure/ChannelMapper.ts b/packages/sdk/src/features/channels/infrastructure/ChannelMapper.ts deleted file mode 100644 index c89249add..000000000 --- a/packages/sdk/src/features/channels/infrastructure/ChannelMapper.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; -import type { Channel } from "../domain/Channel.ts"; - -export const ChannelMapper = { - fromProto(ch: Protobuf.Channel.Channel): Channel { - return { index: ch.index, role: ch.role, settings: ch.settings }; - }, -}; diff --git a/packages/sdk/src/features/channels/state/channelsStore.ts b/packages/sdk/src/features/channels/state/channelsStore.ts deleted file mode 100644 index 7b2e4c4d0..000000000 --- a/packages/sdk/src/features/channels/state/channelsStore.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { SignalMap } from "../../../core/signals/createStore.ts"; -import type { Channel } from "../domain/Channel.ts"; - -export class ChannelsStore extends SignalMap {} diff --git a/packages/sdk/src/features/chat/ChatClient.drafts.test.ts b/packages/sdk/src/features/chat/ChatClient.drafts.test.ts deleted file mode 100644 index 24abb5c3d..000000000 --- a/packages/sdk/src/features/chat/ChatClient.drafts.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { MeshClient } from "../../core/client/MeshClient.ts"; -import { createFakeTransport } from "../../core/testing/createFakeTransport.ts"; -import { ChannelNumber } from "../../core/types.ts"; -import { InMemoryDraftRepository } from "./infrastructure/repositories/InMemoryDraftRepository.ts"; - -describe("ChatClient drafts", () => { - it("starts empty and tracks set/clear via the signal", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const conv = { kind: "channel" as const, channel: ChannelNumber.Primary }; - expect(client.chat.drafts.get(conv).value).toBe(""); - - client.chat.drafts.set(conv, "wip text"); - expect(client.chat.drafts.get(conv).value).toBe("wip text"); - - client.chat.drafts.clear(conv); - expect(client.chat.drafts.get(conv).value).toBe(""); - }); - - it("hydrates from the repository on first read", async () => { - const draftRepository = new InMemoryDraftRepository(); - await draftRepository.save({ kind: "direct", peer: 42 }, "from disk"); - - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport, chat: { draftRepository } }); - const sig = client.chat.drafts.get({ kind: "direct", peer: 42 }); - expect(sig.value).toBe(""); - - await new Promise((r) => setTimeout(r, 10)); - expect(sig.value).toBe("from disk"); - }); - - it("persists draft writes to the repository", async () => { - const draftRepository = new InMemoryDraftRepository(); - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport, chat: { draftRepository } }); - - client.chat.drafts.set( - { kind: "channel", channel: ChannelNumber.Primary }, - "hello", - ); - await new Promise((r) => setTimeout(r, 5)); - expect( - await draftRepository.load({ - kind: "channel", - channel: ChannelNumber.Primary, - }), - ).toBe("hello"); - }); -}); diff --git a/packages/sdk/src/features/chat/ChatClient.persistence.test.ts b/packages/sdk/src/features/chat/ChatClient.persistence.test.ts deleted file mode 100644 index c80c70d17..000000000 --- a/packages/sdk/src/features/chat/ChatClient.persistence.test.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { MeshClient } from "../../core/client/MeshClient.ts"; -import { createFakeTransport } from "../../core/testing/createFakeTransport.ts"; -import { ChannelNumber } from "../../core/types.ts"; -import { InMemoryMessageRepository } from "./infrastructure/repositories/InMemoryMessageRepository.ts"; -import type { Message } from "./domain/Message.ts"; -import { MessageState } from "./domain/MessageState.ts"; - -function seedMessage(id: number, ms: number, text: string): Message { - return { - id, - from: 1, - to: 0xffffffff, - channel: ChannelNumber.Primary, - rxTime: new Date(ms), - type: "broadcast", - text, - state: MessageState.Ack, - }; -} - -describe("ChatClient persistence", () => { - it("hydrates messages from the repository on first subscription", async () => { - const repository = new InMemoryMessageRepository(); - await repository.appendBatch([ - seedMessage(1, 1000, "first"), - seedMessage(2, 2000, "second"), - ]); - - const { transport } = createFakeTransport(); - const client = new MeshClient({ - transport, - chat: { repository, initialLoadLimit: 50 }, - }); - - const sig = client.chat.messages(ChannelNumber.Primary); - expect(sig.value).toEqual([]); - - await new Promise((r) => setTimeout(r, 10)); - expect(sig.value.map((m) => m.text)).toEqual(["first", "second"]); - }); - - it("loadOlder paginates older messages into the front of the bucket", async () => { - const repository = new InMemoryMessageRepository(); - await repository.appendBatch([ - seedMessage(1, 1000, "oldest"), - seedMessage(2, 2000, "middle"), - seedMessage(3, 3000, "newest"), - ]); - - const { transport } = createFakeTransport(); - const client = new MeshClient({ - transport, - chat: { repository, initialLoadLimit: 1 }, - }); - - const sig = client.chat.messages(ChannelNumber.Primary); - await new Promise((r) => setTimeout(r, 10)); - expect(sig.value.map((m) => m.text)).toEqual(["newest"]); - - await client.chat.loadOlder( - { kind: "channel", channel: ChannelNumber.Primary }, - new Date(3000), - 50, - ); - expect(sig.value.map((m) => m.text)).toEqual([ - "oldest", - "middle", - "newest", - ]); - }); - - it("persists inbound messages through the repository", async () => { - const repository = new InMemoryMessageRepository(); - const { transport } = createFakeTransport(); - const client = new MeshClient({ - transport, - chat: { repository }, - }); - - client.events.onMessagePacket.dispatch({ - id: 42, - from: 7, - to: 0xffffffff, - channel: ChannelNumber.Primary, - type: "broadcast", - rxTime: new Date(), - data: "hi", - }); - - await new Promise((r) => setTimeout(r, 10)); - const persisted = await repository.loadRecent( - { kind: "channel", channel: ChannelNumber.Primary }, - 10, - ); - expect(persisted.map((m) => m.text)).toEqual(["hi"]); - }); - - it("saves a direct message we send under its recipient", async () => { - const repository = new InMemoryMessageRepository(); - const { transport, respond } = createFakeTransport(); - const client = new MeshClient({ transport, chat: { repository } }); - respond.withMyNodeInfo({ myNodeNum: 0x10 }); - await new Promise((r) => setTimeout(r, 10)); - - void client.chat.send({ text: "hi peer", destination: 0x20 }); - await new Promise((r) => setTimeout(r, 10)); - - const withPeer = await repository.loadRecent( - { kind: "direct", peer: 0x20 }, - 10, - ); - expect(withPeer.map((m) => m.text)).toEqual(["hi peer"]); - }); - - it("refiles sent direct messages an older version filed under our node", async () => { - const repository = new InMemoryMessageRepository(); - await repository.appendBatch([ - { - ...seedMessage(1, 1000, "sent earlier"), - from: 0x10, - to: 0x20, - type: "direct", - }, - ]); - const { transport, respond } = createFakeTransport(); - new MeshClient({ transport, chat: { repository } }); - - respond.withMyNodeInfo({ myNodeNum: 0x10 }); - await new Promise((r) => setTimeout(r, 10)); - - const withPeer = await repository.loadRecent( - { kind: "direct", peer: 0x20 }, - 10, - ); - expect(withPeer.map((m) => m.text)).toEqual(["sent earlier"]); - }); -}); diff --git a/packages/sdk/src/features/chat/ChatClient.send.test.ts b/packages/sdk/src/features/chat/ChatClient.send.test.ts deleted file mode 100644 index 98b2735ac..000000000 --- a/packages/sdk/src/features/chat/ChatClient.send.test.ts +++ /dev/null @@ -1,287 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import type { Result } from "better-result"; -import { describe, expect, it } from "vitest"; -import { MeshClient } from "../../core/client/MeshClient.ts"; -import { createFakeTransport } from "../../core/testing/createFakeTransport.ts"; -import { ChannelNumber } from "../../core/types.ts"; -import type { SendTextError } from "./application/SendTextUseCase.ts"; -import { MessageState } from "./domain/MessageState.ts"; - -type SendResult = Result; - -/** - * `client.chat.send` resolves only after the packet is ack'd via - * `client.queue.processAck(id)`. The fake transport doesn't drive that - * for us, so this helper polls the queue and acks any pending items - * until the send promise settles. - */ -async function withAckFlush( - client: MeshClient, - run: () => Promise, -): Promise { - const flush = setInterval(() => { - for (const item of client.queue.getState()) - client.queue.processAck(item.id); - }, 5); - try { - return await run(); - } finally { - clearInterval(flush); - } -} - -function sendBroadcast(client: MeshClient, text: string): Promise { - return withAckFlush(client, () => - client.chat.send({ - text, - destination: "broadcast", - channel: ChannelNumber.Primary, - }), - ); -} - -describe("ChatClient.send optimistic append", () => { - it("appends an outbound broadcast to the channel bucket immediately", async () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const messages = client.chat.messages(ChannelNumber.Primary); - - const result = await sendBroadcast(client, "hello mesh"); - expect(result.status).toBe("ok"); - - const stored = messages.value; - expect(stored).toHaveLength(1); - const msg = stored[0]!; - expect(msg.text).toBe("hello mesh"); - expect(msg.type).toBe("broadcast"); - expect(msg.state).toBe(MessageState.Pending); - if (result.status === "ok") expect(msg.id).toBe(result.value); - }); - - it("appends an outbound direct message to the direct bucket", async () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const peer = 12345; - const direct = client.chat.direct(peer); - - const result: SendResult = await withAckFlush(client, () => - client.chat.send({ text: "hi peer", destination: peer }), - ); - expect(result.status).toBe("ok"); - - const stored = direct.value; - expect(stored).toHaveLength(1); - expect(stored[0]!.type).toBe("direct"); - expect(stored[0]!.to).toBe(peer); - expect(stored[0]!.text).toBe("hi peer"); - }); - - it("does not double-append when an inbound packet echoes the same id", async () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const messages = client.chat.messages(ChannelNumber.Primary); - - const result = await sendBroadcast(client, "echoed"); - if (result.status !== "ok") throw new Error("unreachable"); - - // Simulate firmware looping the same packet back via fromradio. - client.events.onMessagePacket.dispatch({ - id: result.value, - from: client.myNodeNum, - to: 0xffffffff, - channel: ChannelNumber.Primary, - type: "broadcast", - rxTime: new Date(), - data: "echoed", - } as never); - - expect(messages.value).toHaveLength(1); - }); - - it("appends the optimistic message before the send promise resolves", async () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const messages = client.chat.messages(ChannelNumber.Primary); - - // Kick off the send but do NOT await yet. - const sendPromise = client.chat.send({ - text: "instant", - destination: "broadcast", - channel: ChannelNumber.Primary, - }); - - // Synchronously, the message must already be in the bucket — the - // optimistic append runs before any await in send(). - expect(messages.value).toHaveLength(1); - expect(messages.value[0]!.text).toBe("instant"); - expect(messages.value[0]!.state).toBe(MessageState.Pending); - - // Now drain the queue so the test doesn't dangle. - for (const item of client.queue.getState()) - client.queue.processAck(item.id); - await sendPromise; - }); - - it("flips outbound state to Failed when sendText returns Err", async () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const messages = client.chat.messages(ChannelNumber.Primary); - - // Empty text triggers EmptyMessageError synchronously inside sendText. - const result = await client.chat.send({ - text: "", - destination: "broadcast", - channel: ChannelNumber.Primary, - }); - expect(result.status).toBe("error"); - // Empty-text path errors before the optimistic append runs in the - // current implementation? It actually appends first — so the bucket - // should contain the placeholder with state=Failed. - expect(messages.value).toHaveLength(1); - expect(messages.value[0]!.state).toBe(MessageState.Failed); - }); - - it("marks a broadcast Delivered when the mesh acks it", async () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const messages = client.chat.messages(ChannelNumber.Primary); - - const result = await sendBroadcast(client, "ack me"); - if (result.status !== "ok") throw new Error("send failed"); - - client.events.onRoutingPacket.dispatch({ - id: result.value, - from: 0, - to: 0, - channel: 0, - type: "broadcast", - rxTime: new Date(), - data: { variant: { case: "errorReason", value: 0 } }, - } as never); - - expect(messages.value[0]!.state).toBe(MessageState.Delivered); - }); - - it("matches a routing ack to the message by request_id", async () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const messages = client.chat.messages(ChannelNumber.Primary); - - const result = await sendBroadcast(client, "ack me"); - if (result.status !== "ok") throw new Error("send failed"); - - client.events.onRoutingPacket.dispatch({ - id: 123456, - requestId: result.value, - from: 5, - to: 0, - channel: 0, - type: "direct", - rxTime: new Date(), - data: create(Protobuf.Mesh.RoutingSchema, { - variant: { - case: "errorReason", - value: Protobuf.Mesh.Routing_Error.MAX_RETRANSMIT, - }, - }), - }); - - expect(messages.value[0]!.state).toBe(MessageState.Failed); - }); - - it("keeps the strongest ack proof verdict", async () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const messages = client.chat.messages(ChannelNumber.Primary); - const Proof = Protobuf.Mesh.MeshPacket_AckProofStatus; - - const result = await sendBroadcast(client, "prove it"); - if (result.status !== "ok") throw new Error("send failed"); - const ack = (ackProofStatus: Protobuf.Mesh.MeshPacket_AckProofStatus) => - client.events.onRoutingPacket.dispatch({ - id: Math.floor(Math.random() * 1e6), - requestId: result.value, - from: 5, - to: 0, - channel: 0, - type: "direct", - rxTime: new Date(), - ackProofStatus, - data: create(Protobuf.Mesh.RoutingSchema, { - variant: { case: "errorReason", value: 0 }, - }), - }); - - ack(Proof.ACK_PROOF_INVALID); - expect(messages.value[0]!.ackProof).toBe(Proof.ACK_PROOF_INVALID); - ack(Proof.ACK_PROOF_ABSENT); - expect(messages.value[0]!.ackProof).toBe(Proof.ACK_PROOF_INVALID); - ack(Proof.ACK_PROOF_VALID); - expect(messages.value[0]!.ackProof).toBe(Proof.ACK_PROOF_VALID); - ack(Proof.ACK_PROOF_INVALID); - expect(messages.value[0]!.ackProof).toBe(Proof.ACK_PROOF_VALID); - }); - - describe("direct message delivery", () => { - async function sentDirect() { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const messages = client.chat.direct(42); - const result = await withAckFlush(client, () => - client.chat.send({ text: "hi", destination: 42 }), - ); - if (result.status !== "ok") throw new Error("send failed"); - const route = (from: number, error: Protobuf.Mesh.Routing_Error) => - client.events.onRoutingPacket.dispatch({ - id: Math.floor(Math.random() * 1e6) + 1, - requestId: result.value, - from, - to: 0, - channel: 0, - type: "direct", - rxTime: new Date(), - data: create(Protobuf.Mesh.RoutingSchema, { - variant: { case: "errorReason", value: error }, - }), - }); - return { client, messages, route }; - } - const E = Protobuf.Mesh.Routing_Error; - - it("is Delivered when a relay acks and Ack when the recipient does", async () => { - const { messages, route } = await sentDirect(); - route(7, E.NONE); - expect(messages.value[0]!.state).toBe(MessageState.Delivered); - expect(messages.value[0]!.relays).toBe(1); - route(42, E.NONE); - expect(messages.value[0]!.state).toBe(MessageState.Ack); - expect(messages.value[0]!.relays).toBe(2); - }); - - it("records why it failed, but never undoes the recipient's ack", async () => { - const { messages, route } = await sentDirect(); - route(7, E.MAX_RETRANSMIT); - expect(messages.value[0]!.state).toBe(MessageState.Failed); - expect(messages.value[0]!.routingError).toBe(E.MAX_RETRANSMIT); - route(42, E.NONE); - expect(messages.value[0]!.state).toBe(MessageState.Ack); - expect(messages.value[0]!.routingError).toBeUndefined(); - route(7, E.NO_ROUTE); - expect(messages.value[0]!.state).toBe(MessageState.Ack); - }); - - it("resends as a new message with a fresh id", async () => { - const { client, messages, route } = await sentDirect(); - route(7, E.MAX_RETRANSMIT); - const failed = messages.value[0]!; - const result = await withAckFlush(client, () => - client.chat.resend(failed), - ); - expect(result.status).toBe("ok"); - expect(messages.value).toHaveLength(1); - expect(messages.value[0]!.id).not.toBe(failed.id); - expect(messages.value[0]!.text).toBe("hi"); - }); - }); -}); diff --git a/packages/sdk/src/features/chat/ChatClient.ts b/packages/sdk/src/features/chat/ChatClient.ts deleted file mode 100644 index f2b663a74..000000000 --- a/packages/sdk/src/features/chat/ChatClient.ts +++ /dev/null @@ -1,495 +0,0 @@ -import * as Protobuf from "@meshtastic/protobufs"; -import { signal } from "@preact/signals-core"; -import type { Result } from "better-result"; -import type { MeshClient } from "../../core/client/MeshClient.ts"; -import { Constants } from "../../core/constants/index.ts"; -import { generatePacketId } from "../../core/identifiers/PacketId.ts"; -import { - type ReadonlySignal, - toReadonly, -} from "../../core/signals/createStore.ts"; -import type { ChannelNumber } from "../../core/types.ts"; -import type { DraftRepository } from "./domain/DraftRepository.ts"; -import type { Message, MessageDeliveryPatch } from "./domain/Message.ts"; -import { - type ConversationKey, - type MessageRepository, - parseConversationKey, - type RetentionPolicy, -} from "./domain/MessageRepository.ts"; -import { MessageState } from "./domain/MessageState.ts"; -import { MessageMapper } from "./infrastructure/MessageMapper.ts"; -import { InMemoryDraftRepository } from "./infrastructure/repositories/InMemoryDraftRepository.ts"; -import { InMemoryMessageRepository } from "./infrastructure/repositories/InMemoryMessageRepository.ts"; -import { - type SendTextError, - type SendTextInput, - sendText, -} from "./application/SendTextUseCase.ts"; -import { ChatStore } from "./state/chatStore.ts"; -import { DraftStore } from "./state/draftStore.ts"; - -export interface ChatClientOptions { - repository?: MessageRepository; - draftRepository?: DraftRepository; - retention?: RetentionPolicy; - /** Messages to load into the store on first subscription of a conversation. */ - initialLoadLimit?: number; -} - -/** - * Drafts namespace: per-conversation working text. Lazy-hydrates from the - * configured DraftRepository on first read; auto-clears on successful send. - */ -export interface ChatDrafts { - get(key: ConversationKey): ReadonlySignal; - set(key: ConversationKey, text: string): void; - clear(key: ConversationKey): void; -} - -/** - * Unread-counts namespace. Counts inbound messages per conversation; resets - * on `markRead(key)`. Counts are in-memory only (no persistence) — the - * recipe for persistence later is to track a `lastReadAt` timestamp per - * conversation in the message repository and compute unread on hydrate. - */ -export interface ChatUnread { - /** Map of conversation-key string -> unread count. */ - readonly byKey: ReadonlySignal>; - /** Sum of all unread counts across conversations. */ - readonly total: ReadonlySignal; - /** Unread count for a single conversation. */ - count(key: ConversationKey): ReadonlySignal; - /** Zero out the unread count for a conversation. */ - markRead(key: ConversationKey): void; -} - -/** - * Chat slice facade. Exposes message buckets keyed by channel or peer, drafts - * keyed the same way, and the `send` command for outbound text. Optional - * persistence via MessageRepository / DraftRepository. - */ -export class ChatClient { - private readonly client: MeshClient; - private readonly store: ChatStore; - private readonly draftStore: DraftStore; - private readonly repository: MessageRepository; - private readonly draftRepository: DraftRepository; - private readonly retention: RetentionPolicy | undefined; - private readonly initialLoadLimit: number; - private readonly hydrated = new Set(); - private readonly draftsHydrated = new Set(); - private readonly unreadByKey = signal>(new Map()); - /** - * Bumped on every storage rescope. A load started before the bump belongs - * to the old scope, so its result is dropped instead of being merged into - * the stores. - */ - private epoch = 0; - - public readonly drafts: ChatDrafts; - public readonly unread: ChatUnread; - - constructor(client: MeshClient, options: ChatClientOptions = {}) { - this.client = client; - this.store = new ChatStore(); - this.draftStore = new DraftStore(); - this.repository = options.repository ?? new InMemoryMessageRepository(); - this.draftRepository = - options.draftRepository ?? new InMemoryDraftRepository(); - this.retention = options.retention; - this.initialLoadLimit = options.initialLoadLimit ?? 50; - - this.drafts = { - get: (key) => this.draftFor(key), - set: (key, text) => this.setDraft(key, text), - clear: (key) => this.setDraft(key, ""), - }; - - this.unread = { - byKey: toReadonly(this.unreadByKey), - total: this.deriveTotalUnread(), - count: (key) => this.deriveUnreadCount(key), - markRead: (key) => this.markRead(key), - }; - - // Older versions filed direct messages we sent under our own node, where - // no conversation reads them. Move them once we know which node is ours. - client.events.onMyNodeInfo.subscribe((info) => { - void this.repository.refileSentDirect?.(info.myNodeNum).catch(() => {}); - }); - - client.events.onMessagePacket.subscribe((packet) => { - const message = MessageMapper.fromPacket(packet); - const conv: ConversationKey = - packet.type === "direct" && packet.to !== Constants.broadcastNum - ? { - kind: "direct", - peer: packet.from === client.myNodeNum ? packet.to : packet.from, - } - : { kind: "channel", channel: packet.channel }; - const key = this.keyFor(conv); - - // Outbound is optimistic-appended in `send()`. If the firmware later - // echoes the same packet via `fromradio`, skip the duplicate. - if (this.store.hasMessage(key, message.id)) return; - - this.store.append(key, message); - void this.persistAppend(message, conv); - - // Increment unread count when the message is inbound (not from us). The - // outbound echo of our own send doesn't count as unread. - if (packet.from !== client.myNodeNum) { - this.bumpUnread(key); - } - }); - - client.events.onRoutingPacket.subscribe((packet) => { - if (packet.data.variant.case !== "errorReason") return; - // A routing ack names the message it acks in Data.request_id; its own - // id is unrelated. - this.applyAck( - packet.requestId ?? packet.id, - packet.from, - packet.data.variant.value, - packet.ackProofStatus, - ); - }); - } - - /** - * Fold one ack or NAK into the message it answers, as the Android app's - * handleAckNak does. An ack from the addressed node means the recipient got - * it (Ack); an ack from anyone else (a relay, or the radio hearing its own - * rebroadcast) means it reached the mesh (Delivered). A NAK fails it. Once - * the recipient has acked, later acks and NAKs no longer change the state. - * - * Ack proofs keep the strongest verdict: a later ack without proof never - * clears one, and a VALID proof is still recorded after a forged ack - * settled the message. - */ - private applyAck( - id: number, - from: number, - error: Protobuf.Mesh.Routing_Error, - proof: Protobuf.Mesh.MeshPacket_AckProofStatus | undefined, - ): void { - const message = this.store.getMessage(id); - const patch: MessageDeliveryPatch = {}; - - if (message?.state !== MessageState.Ack) { - const isAck = error === Protobuf.Mesh.Routing_Error.NONE; - if (isAck) { - patch.state = - message && from === message.to - ? MessageState.Ack - : MessageState.Delivered; - patch.relays = (message?.relays ?? 0) + 1; - patch.routingError = undefined; - } else { - patch.state = MessageState.Failed; - patch.routingError = error; - } - } - - const Proof = Protobuf.Mesh.MeshPacket_AckProofStatus; - const current = message?.ackProof; - if ( - proof !== undefined && - proof !== Proof.ACK_PROOF_ABSENT && - current !== Proof.ACK_PROOF_VALID && - (current !== Proof.ACK_PROOF_INVALID || proof === Proof.ACK_PROOF_VALID) - ) { - patch.ackProof = proof; - } - - if (Object.keys(patch).length === 0) return; - this.store.updateDelivery(id, patch); - void this.repository.updateDelivery(id, patch).catch(() => {}); - } - - /** - * Send a failed (or unconfirmed) message again. The old message is removed - * and a new one, with a fresh packet id, takes its place. - */ - public async resend( - message: Pick, - ): Promise> { - this.store.remove(message.id); - void this.repository.remove(message.id).catch(() => {}); - return this.send({ - text: message.text, - destination: message.type === "direct" ? message.to : "broadcast", - channel: message.channel, - }); - } - - public messages(channel: ChannelNumber): ReadonlySignal { - this.ensureHydrated({ kind: "channel", channel }); - return this.store.messagesForChannel(channel); - } - - public direct(peer: number): ReadonlySignal { - this.ensureHydrated({ kind: "direct", peer }); - return this.store.messagesForDirect(peer); - } - - public async loadOlder( - conv: ConversationKey, - before: Date, - limit = 50, - ): Promise { - const epoch = this.epoch; - const older = await this.repository.loadBefore(conv, before, limit); - if (epoch !== this.epoch) return []; - const key = this.keyFor(conv); - for (let i = older.length - 1; i >= 0; i--) - this.store.prepend(key, older[i]!); - return older; - } - - /** - * Empties a single conversation from memory + persistence. Draft for the - * same conversation is untouched; callers invoke `drafts.clear(conv)` too - * if they want the compose box wiped. - */ - public async clearConversation(conv: ConversationKey): Promise { - const key = this.keyFor(conv); - this.store.clearBucket(key); - this.hydrated.delete(key); - try { - await this.repository.clearConversation(conv); - } catch { - // ok - } - } - - /** - * Wipes every message across every conversation for this client. - */ - public async clearAll(): Promise { - this.store.clearAll(); - this.hydrated.clear(); - try { - await this.repository.clear(); - } catch { - // ok - } - } - - /** - * Points the message and draft repositories at another storage scope and - * reloads from it every conversation and draft loaded so far. Messages, - * drafts and unread counts held for the old scope are dropped. Signals - * already handed out stay valid and update in place. - */ - public rescope(scope: number): void { - this.repository.setScope?.(scope); - this.draftRepository.setScope?.(scope); - this.epoch++; - - const conversations = [...this.hydrated]; - const drafts = [...this.draftsHydrated]; - this.store.clearAll(); - this.hydrated.clear(); - this.draftStore.reset(); - this.draftsHydrated.clear(); - if (this.unreadByKey.peek().size > 0) this.unreadByKey.value = new Map(); - - for (const key of conversations) - this.ensureHydrated(parseConversationKey(key)); - for (const key of drafts) this.draftFor(parseConversationKey(key)); - } - - public async send( - input: SendTextInput, - ): Promise> { - const conv: ConversationKey = - typeof input.destination === "number" - ? { kind: "direct", peer: input.destination } - : { kind: "channel", channel: input.channel ?? 0 }; - - // Optimistic-append BEFORE awaiting `sendText`. The send pipeline - // resolves only after `queue.processAck(id)` fires (firmware ack — - // can be 1–3 s on LoRa) and we don't want the UI to wait that long - // to render the user's own message. We pre-generate the packet id - // so the eventual routing-ack subscriber can match by id and flip - // state Pending → Ack. - // - // (The firmware does not echo own outbound text back via `fromradio` - // and `MeshClient.sendPacket(echoResponse=true)` only dispatches the - // raw `onMeshPacket` — not the per-portnum `onMessagePacket` the - // chat slice subscribes to. Hence the explicit append here.) - const packetId = generatePacketId(); - const key = this.keyFor(conv); - const message: Message = { - id: packetId, - from: this.client.myNodeNum, - to: - typeof input.destination === "number" - ? input.destination - : Constants.broadcastNum, - channel: input.channel ?? 0, - rxTime: new Date(), - type: typeof input.destination === "number" ? "direct" : "broadcast", - text: input.text, - state: MessageState.Pending, - }; - if (!this.store.hasMessage(key, packetId)) { - this.store.append(key, message); - void this.persistAppend(message, conv); - } - this.draftStore.clear(conv); - void this.draftRepository.clear(conv).catch(() => {}); - - const result = await sendText(this.client, { ...input, packetId }); - if (result.status === "error") { - // Send pipeline failed (transport closed, validation, etc.). Keep - // the optimistic message visible but mark it Failed so the user - // sees the error state next to their bubble. - // A NAK arrives as a PacketError from the queue; keep its reason. The - // routing handler has usually recorded it already. - const routingError = (result.error as { error?: unknown }).error; - const patch: MessageDeliveryPatch = { - state: MessageState.Failed, - ...(typeof routingError === "number" ? { routingError } : {}), - }; - if (this.store.getMessage(packetId)?.state !== MessageState.Ack) { - this.store.updateDelivery(packetId, patch); - void this.repository.updateDelivery(packetId, patch).catch(() => {}); - } - } - return result; - } - - private ensureHydrated(conv: ConversationKey): void { - const key = this.keyFor(conv); - if (this.hydrated.has(key)) return; - this.hydrated.add(key); - const epoch = this.epoch; - void (async () => { - try { - const recent = await this.repository.loadRecent( - conv, - this.initialLoadLimit, - ); - if (epoch !== this.epoch) return; - this.store.merge(key, recent); - } catch { - // adapter may not have history yet; safe to ignore - } - })(); - } - - private draftFor(conv: ConversationKey): ReadonlySignal { - const key = this.keyFor(conv); - if (!this.draftsHydrated.has(key)) { - this.draftsHydrated.add(key); - const epoch = this.epoch; - void (async () => { - try { - const stored = await this.draftRepository.load(conv); - if (epoch !== this.epoch) return; - if (stored) this.draftStore.set(conv, stored); - } catch { - // ok - } - })(); - } - return this.draftStore.get(conv); - } - - private setDraft(conv: ConversationKey, text: string): void { - this.draftsHydrated.add(this.keyFor(conv)); - this.draftStore.set(conv, text); - void this.draftRepository.save(conv, text).catch(() => { - // persistence failure must not break reactive flow - }); - } - - private async persistAppend( - message: Message, - conv: ConversationKey, - ): Promise { - try { - await this.repository.append(message, conv); - if (this.retention) await this.repository.prune(this.retention); - } catch (e) { - // Persistence failure must not break the reactive flow, but say so: - // otherwise the message just isn't there after a reload. - this.client.log.warn("Could not save message", message.id, e); - } - } - - private keyFor(conv: ConversationKey): string { - return conv.kind === "channel" - ? this.store.channelKey(conv.channel) - : this.store.directKey(conv.peer); - } - - private bumpUnread(key: string): void { - const next = new Map(this.unreadByKey.peek()); - next.set(key, (next.get(key) ?? 0) + 1); - this.unreadByKey.value = next; - } - - private markRead(key: ConversationKey): void { - const k = this.keyFor(key); - const current = this.unreadByKey.peek(); - if ((current.get(k) ?? 0) === 0) return; - const next = new Map(current); - next.delete(k); - this.unreadByKey.value = next; - } - - private deriveTotalUnread(): ReadonlySignal { - const src = this.unreadByKey; - return { - get value() { - let total = 0; - for (const c of src.value.values()) total += c; - return total; - }, - peek() { - let total = 0; - for (const c of src.peek().values()) total += c; - return total; - }, - subscribe(listener) { - let first = true; - return src.subscribe((m) => { - if (first) { - first = false; - return; - } - let total = 0; - for (const c of m.values()) total += c; - listener(total); - }); - }, - }; - } - - private deriveUnreadCount(key: ConversationKey): ReadonlySignal { - const k = this.keyFor(key); - const src = this.unreadByKey; - return { - get value() { - return src.value.get(k) ?? 0; - }, - peek() { - return src.peek().get(k) ?? 0; - }, - subscribe(listener) { - let first = true; - return src.subscribe((m) => { - if (first) { - first = false; - return; - } - listener(m.get(k) ?? 0); - }); - }, - }; - } -} diff --git a/packages/sdk/src/features/chat/ChatClient.unread.test.ts b/packages/sdk/src/features/chat/ChatClient.unread.test.ts deleted file mode 100644 index 396a57c7d..000000000 --- a/packages/sdk/src/features/chat/ChatClient.unread.test.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { describe, expect, it } from "vitest"; -import { MeshClient } from "../../core/client/MeshClient.ts"; -import { createFakeTransport } from "../../core/testing/createFakeTransport.ts"; -import { ChannelNumber } from "../../core/types.ts"; - -const MY_NODE = 0xdeadbeef; - -function dispatchInbound( - client: MeshClient, - opts: { - from: number; - to?: number; - channel?: ChannelNumber; - type?: "direct" | "broadcast"; - ms: number; - text?: string; - }, -): void { - client.events.onMessagePacket.dispatch({ - id: opts.ms, - from: opts.from, - to: opts.to ?? 0, - channel: opts.channel ?? ChannelNumber.Primary, - type: opts.type ?? "broadcast", - rxTime: new Date(opts.ms), - data: opts.text ?? "hi", - } as never); -} - -function setMyNode(client: MeshClient): void { - client.events.onMyNodeInfo.dispatch( - create(Protobuf.Mesh.MyNodeInfoSchema, { myNodeNum: MY_NODE }), - ); -} - -describe("ChatClient unread counts", () => { - it("starts at zero for every conversation", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - expect(client.chat.unread.total.value).toBe(0); - expect( - client.chat.unread.count({ - kind: "channel", - channel: ChannelNumber.Primary, - }).value, - ).toBe(0); - }); - - it("increments on inbound broadcast and decrements on markRead", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - setMyNode(client); - - dispatchInbound(client, { from: 100, ms: 1000 }); - dispatchInbound(client, { from: 200, ms: 2000 }); - - expect( - client.chat.unread.count({ - kind: "channel", - channel: ChannelNumber.Primary, - }).value, - ).toBe(2); - expect(client.chat.unread.total.value).toBe(2); - - client.chat.unread.markRead({ - kind: "channel", - channel: ChannelNumber.Primary, - }); - expect(client.chat.unread.total.value).toBe(0); - }); - - it("does not increment for outbound echoes (from === myNodeNum)", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - setMyNode(client); - - dispatchInbound(client, { from: MY_NODE, ms: 1000 }); - expect(client.chat.unread.total.value).toBe(0); - }); - - it("keys direct messages by peer, not channel", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - setMyNode(client); - - dispatchInbound(client, { - from: 50, - to: MY_NODE, - type: "direct", - ms: 1000, - }); - expect(client.chat.unread.count({ kind: "direct", peer: 50 }).value).toBe( - 1, - ); - expect( - client.chat.unread.count({ - kind: "channel", - channel: ChannelNumber.Primary, - }).value, - ).toBe(0); - }); -}); diff --git a/packages/sdk/src/features/chat/application/SendTextUseCase.test.ts b/packages/sdk/src/features/chat/application/SendTextUseCase.test.ts deleted file mode 100644 index 767d410ae..000000000 --- a/packages/sdk/src/features/chat/application/SendTextUseCase.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { Result } from "better-result"; -import { describe, expect, it, vi } from "vitest"; -import { - EmptyMessageError, - MessageTooLongError, - sendText, -} from "./SendTextUseCase.ts"; -import type { MeshClient } from "../../../core/client/MeshClient.ts"; - -function makeClient(sendPacket = vi.fn().mockResolvedValue(123)) { - return { - log: { debug: vi.fn() }, - sendPacket, - } as unknown as MeshClient; -} - -describe("sendText", () => { - it("rejects empty text with EmptyMessageError", async () => { - const client = makeClient(); - const result = await sendText(client, { text: "" }); - expect(Result.isError(result)).toBe(true); - if (Result.isError(result)) { - expect(result.error).toBeInstanceOf(EmptyMessageError); - } - }); - - it("rejects text that encodes to more than 228 bytes", async () => { - const client = makeClient(); - const tooLong = "a".repeat(300); - const result = await sendText(client, { text: tooLong }); - expect(Result.isError(result)).toBe(true); - if (Result.isError(result)) { - expect(result.error).toBeInstanceOf(MessageTooLongError); - } - }); - - it("encodes text and forwards to sendPacket on the TEXT_MESSAGE_APP portnum", async () => { - const sendPacket = vi.fn().mockResolvedValue(999); - const client = makeClient(sendPacket); - const result = await sendText(client, { text: "hi" }); - expect(Result.isOk(result)).toBe(true); - if (Result.isOk(result)) { - expect(result.value).toBe(999); - } - expect(sendPacket).toHaveBeenCalledTimes(1); - const args = sendPacket.mock.calls[0] ?? []; - const payload = args[0] as Uint8Array; - expect(new TextDecoder().decode(payload)).toBe("hi"); - }); -}); diff --git a/packages/sdk/src/features/chat/application/SendTextUseCase.ts b/packages/sdk/src/features/chat/application/SendTextUseCase.ts deleted file mode 100644 index 7e93d1dc4..000000000 --- a/packages/sdk/src/features/chat/application/SendTextUseCase.ts +++ /dev/null @@ -1,91 +0,0 @@ -import * as Protobuf from "@meshtastic/protobufs"; -import { Result } from "better-result"; -import type { MeshClient } from "../../../core/client/MeshClient.ts"; -import { - ChannelNumber, - type Destination, - Emitter, -} from "../../../core/types.ts"; - -export interface SendTextInput { - text: string; - destination?: Destination; - wantAck?: boolean; - channel?: ChannelNumber; - replyId?: number; - emoji?: number; - /** - * Override the auto-generated packet id. Used by callers (e.g. the - * chat slice's optimistic-append path) that need to know the id - * synchronously before the send round-trip resolves. - */ - packetId?: number; -} - -export class EmptyMessageError extends Error { - readonly _tag = "EmptyMessageError"; - constructor() { - super("Message text is empty"); - this.name = "EmptyMessageError"; - } -} - -export class MessageTooLongError extends Error { - readonly _tag = "MessageTooLongError"; - constructor(readonly byteLength: number) { - super( - `Message text encodes to ${byteLength} bytes; max payload is ~228 bytes`, - ); - this.name = "MessageTooLongError"; - } -} - -export type SendTextError = EmptyMessageError | MessageTooLongError | Error; - -/** Max safe text payload per Meshtastic firmware (leaves room for overhead in the 256-byte data payload). */ -const MAX_TEXT_BYTES = 228; - -/** - * Sends a text message. Returns a Result; the Ok variant is the packet id - * used to correlate the ack from the device. - */ -export async function sendText( - client: MeshClient, - input: SendTextInput, -): Promise> { - if (input.text.length === 0) { - return Result.err(new EmptyMessageError()); - } - - const destination = input.destination ?? "broadcast"; - const channel = input.channel ?? ChannelNumber.Primary; - const enc = new TextEncoder(); - const payload = enc.encode(input.text); - - if (payload.length > MAX_TEXT_BYTES) { - return Result.err(new MessageTooLongError(payload.length)); - } - - client.log.debug( - Emitter[Emitter.SendText], - `📤 Sending message to ${destination} on channel ${channel}`, - ); - - try { - const id = await client.sendPacket( - payload, - Protobuf.Portnums.PortNum.TEXT_MESSAGE_APP, - destination, - channel, - input.wantAck, - false, - true, - input.replyId, - input.emoji, - input.packetId, - ); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} diff --git a/packages/sdk/src/features/chat/application/SendWaypointUseCase.ts b/packages/sdk/src/features/chat/application/SendWaypointUseCase.ts deleted file mode 100644 index e0725dd94..000000000 --- a/packages/sdk/src/features/chat/application/SendWaypointUseCase.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { toBinary } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { Result } from "better-result"; -import type { MeshClient } from "../../../core/client/MeshClient.ts"; -import { generatePacketId } from "../../../core/identifiers/PacketId.ts"; -import { - ChannelNumber, - type Destination, - Emitter, -} from "../../../core/types.ts"; - -export async function sendWaypoint( - client: MeshClient, - waypoint: Protobuf.Mesh.Waypoint, - destination: Destination, - channel: ChannelNumber = ChannelNumber.Primary, -): Promise> { - client.log.debug( - Emitter[Emitter.SendWaypoint], - `📤 Sending waypoint to ${destination} on channel ${channel}`, - ); - - waypoint.id = generatePacketId(); - - try { - const id = await client.sendPacket( - toBinary(Protobuf.Mesh.WaypointSchema, waypoint), - Protobuf.Portnums.PortNum.WAYPOINT_APP, - destination, - channel, - true, - false, - ); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} diff --git a/packages/sdk/src/features/chat/domain/DraftRepository.ts b/packages/sdk/src/features/chat/domain/DraftRepository.ts deleted file mode 100644 index 5de7ea085..000000000 --- a/packages/sdk/src/features/chat/domain/DraftRepository.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { ConversationKey } from "./MessageRepository.ts"; - -/** - * Persists per-conversation draft text. Implementations can be in-memory - * (lost on reload) or backed by SQLite for users who expect drafts to - * survive a refresh. - */ -export interface DraftRepository { - load(key: ConversationKey): Promise; - save(key: ConversationKey, text: string): Promise; - clear(key: ConversationKey): Promise; - loadAll(): Promise>; - /** - * Points every later read and write at another storage scope. See - * `MessageRepository.setScope`. - */ - setScope?(scope: number): void; -} diff --git a/packages/sdk/src/features/chat/domain/Message.test.ts b/packages/sdk/src/features/chat/domain/Message.test.ts deleted file mode 100644 index 42fd00d8d..000000000 --- a/packages/sdk/src/features/chat/domain/Message.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { MessageMapper } from "../infrastructure/MessageMapper.ts"; -import { MessageState } from "./MessageState.ts"; -import { ChannelNumber } from "../../../core/types.ts"; - -describe("MessageMapper", () => { - it("projects a text PacketMetadata into the Message domain shape", () => { - const now = new Date(1_700_000_000_000); - const message = MessageMapper.fromPacket( - { - id: 1, - from: 10, - to: 20, - channel: ChannelNumber.Primary, - rxTime: now, - type: "direct", - data: "hello", - }, - MessageState.Pending, - ); - expect(message).toEqual({ - id: 1, - from: 10, - to: 20, - channel: ChannelNumber.Primary, - rxTime: now, - type: "direct", - text: "hello", - state: MessageState.Pending, - }); - }); -}); diff --git a/packages/sdk/src/features/chat/domain/Message.ts b/packages/sdk/src/features/chat/domain/Message.ts deleted file mode 100644 index 8fb288db0..000000000 --- a/packages/sdk/src/features/chat/domain/Message.ts +++ /dev/null @@ -1,45 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; -import type { ChannelNumber, PacketDestination } from "../../../core/types.ts"; -import type { MessageState } from "./MessageState.ts"; - -/** - * A text message sent or received on the mesh. - */ -export interface Message { - readonly id: number; - readonly from: number; - readonly to: number; - readonly channel: ChannelNumber; - readonly rxTime: Date; - readonly type: PacketDestination; - readonly text: string; - readonly state: MessageState; - /** Received with an XEdDSA signature the device verified. */ - readonly signed?: boolean; - /** - * Proof-of-delivery verdict from the ack (firmware 2.8.1+). VALID means the - * recipient provably got it; INVALID means the ack was forged. - */ - readonly ackProof?: Protobuf.Mesh.MeshPacket_AckProofStatus; - /** Why a Failed message failed, from the NAK or the local queue. */ - readonly routingError?: Protobuf.Mesh.Routing_Error; - /** How many acks (relays and the recipient) came back for it. */ - readonly relays?: number; - /** SNR in dB of a received message, when our radio measured it. */ - readonly snr?: number; - /** RSSI in dBm of a received message, when our radio measured it. */ - readonly rssi?: number; - /** Hops a received message took, or undefined when it can't be told. */ - readonly hopsAway?: number; - /** The message reached the mesh through an MQTT gateway. */ - readonly viaMqtt?: boolean; - /** How the message reached our radio. */ - readonly transport?: Protobuf.Mesh.MeshPacket_TransportMechanism; -} - -/** Fields an ack or NAK can change on a stored message. */ -export type MessageDeliveryPatch = { - -readonly [ - K in "state" | "ackProof" | "routingError" | "relays" - ]?: Message[K]; -}; diff --git a/packages/sdk/src/features/chat/domain/MessageRepository.ts b/packages/sdk/src/features/chat/domain/MessageRepository.ts deleted file mode 100644 index d636f747c..000000000 --- a/packages/sdk/src/features/chat/domain/MessageRepository.ts +++ /dev/null @@ -1,90 +0,0 @@ -import type { ChannelNumber } from "../../../core/types.ts"; -import type { Message, MessageDeliveryPatch } from "./Message.ts"; -import type { MessageState } from "./MessageState.ts"; - -/** - * Conversation key. Broadcast messages are keyed by channel; direct messages - * are keyed by the peer node number. - */ -export type ConversationKey = - | { kind: "channel"; channel: ChannelNumber } - | { kind: "direct"; peer: number }; - -export interface RetentionPolicy { - /** Drop anything older than this many ms. */ - olderThanMs?: number; - /** Keep at most this many messages per conversation. */ - maxPerBucket?: number; -} - -/** - * Port for persisting chat messages. Implementations live in adapter packages - * (e.g. `@meshtastic/sdk-storage-sqlocal`) or in-memory within the SDK itself. - * - * Reads are paginated so consumers can lazy-load history on scroll rather than - * rehydrating every message at boot. - */ -export interface MessageRepository { - loadRecent(key: ConversationKey, limit: number): Promise; - loadBefore( - key: ConversationKey, - cursor: Date, - limit: number, - ): Promise; - /** - * Stores a message. Pass `key` whenever it is known: a direct message we - * sent belongs to its recipient, which `message` alone can't tell apart - * from one we received. Without it the key is inferred from the sender. - */ - append(message: Message, key?: ConversationKey): Promise; - /** Stores received messages, inferring each one's conversation. */ - appendBatch(messages: ReadonlyArray): Promise; - updateState(id: number, state: MessageState): Promise; - updateDelivery(id: number, patch: MessageDeliveryPatch): Promise; - /** Deletes one message, e.g. a failed one the user resends. */ - remove(id: number): Promise; - prune(policy: RetentionPolicy): Promise; - /** Deletes every message in a single conversation. */ - clearConversation(key: ConversationKey): Promise; - /** Deletes every message for the scoped device / consumer. */ - clear(): Promise; - /** - * Moves direct messages we sent that were filed under our own node, as - * older versions did, to the conversation with their recipient. Resolves - * with how many moved. - */ - refileSentDirect?(localNodeNum: number): Promise; - /** - * Points every later read and write at another storage scope (e.g. the - * node number of the connected radio). Synchronous, so a write issued - * right after the call already lands in the new scope. Repositories with - * nothing to scope, like the in-memory one, leave it out. - */ - setScope?(scope: number): void; -} - -/** - * The conversation a received message belongs to. Wrong for a direct - * message we sent, which belongs to its recipient; callers that know the - * local node pass the key instead. - */ -export function inferConversation(message: Message): ConversationKey { - return message.type === "direct" - ? { kind: "direct", peer: message.from } - : { kind: "channel", channel: message.channel }; -} - -export function conversationKeyString(key: ConversationKey): string { - return key.kind === "channel" - ? `channel:${key.channel}` - : `direct:${key.peer}`; -} - -/** Inverse of {@link conversationKeyString}. */ -export function parseConversationKey(s: string): ConversationKey { - if (s.startsWith("channel:")) - return { kind: "channel", channel: Number(s.slice(8)) }; - if (s.startsWith("direct:")) - return { kind: "direct", peer: Number(s.slice(7)) }; - throw new Error(`Unknown conversation key format: ${s}`); -} diff --git a/packages/sdk/src/features/chat/domain/MessageState.ts b/packages/sdk/src/features/chat/domain/MessageState.ts deleted file mode 100644 index 41a2afafc..000000000 --- a/packages/sdk/src/features/chat/domain/MessageState.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * Delivery state of a message, after the Android app's MessageStatus. - * - * - Pending: handed to the radio, no ack yet ("Sending…"). - * - Delivered: acked by a relay, or the radio heard it rebroadcast. For a - * broadcast that is success; for a direct message the recipient has not - * confirmed it yet. - * - Ack: the addressed node acked it (and every inbound message). - * - Failed: a NAK or a local error; see Message.routingError. - */ -export enum MessageState { - Pending = "pending", - Delivered = "delivered", - Ack = "ack", - Failed = "failed", -} diff --git a/packages/sdk/src/features/chat/index.ts b/packages/sdk/src/features/chat/index.ts deleted file mode 100644 index 9542df10a..000000000 --- a/packages/sdk/src/features/chat/index.ts +++ /dev/null @@ -1,28 +0,0 @@ -export { ChatClient } from "./ChatClient.ts"; -export type { - ChatClientOptions, - ChatDrafts, - ChatUnread, -} from "./ChatClient.ts"; -export type { DraftRepository } from "./domain/DraftRepository.ts"; -export { InMemoryDraftRepository } from "./infrastructure/repositories/InMemoryDraftRepository.ts"; -export type { Message, MessageDeliveryPatch } from "./domain/Message.ts"; -export { MessageState } from "./domain/MessageState.ts"; -export type { - ConversationKey, - MessageRepository, - RetentionPolicy, -} from "./domain/MessageRepository.ts"; -export { - conversationKeyString, - inferConversation, - parseConversationKey, -} from "./domain/MessageRepository.ts"; -export { MessageMapper } from "./infrastructure/MessageMapper.ts"; -export { InMemoryMessageRepository } from "./infrastructure/repositories/InMemoryMessageRepository.ts"; -export { - EmptyMessageError, - MessageTooLongError, - type SendTextError, - type SendTextInput, -} from "./application/SendTextUseCase.ts"; diff --git a/packages/sdk/src/features/chat/infrastructure/MessageMapper.ts b/packages/sdk/src/features/chat/infrastructure/MessageMapper.ts deleted file mode 100644 index 464c6f060..000000000 --- a/packages/sdk/src/features/chat/infrastructure/MessageMapper.ts +++ /dev/null @@ -1,27 +0,0 @@ -import type { PacketMetadata } from "../../../core/types.ts"; -import type { Message } from "../domain/Message.ts"; -import { MessageState } from "../domain/MessageState.ts"; - -export const MessageMapper = { - fromPacket( - packet: PacketMetadata, - state: MessageState = MessageState.Ack, - ): Message { - return { - id: packet.id, - from: packet.from, - to: packet.to, - channel: packet.channel, - rxTime: packet.rxTime, - type: packet.type, - text: packet.data, - state, - signed: packet.xeddsaSigned || undefined, - snr: packet.rxSnr, - rssi: packet.rxRssi, - hopsAway: packet.hopsAway, - viaMqtt: packet.viaMqtt || undefined, - transport: packet.transportMechanism, - }; - }, -}; diff --git a/packages/sdk/src/features/chat/infrastructure/repositories/InMemoryDraftRepository.ts b/packages/sdk/src/features/chat/infrastructure/repositories/InMemoryDraftRepository.ts deleted file mode 100644 index b3fa9a0a4..000000000 --- a/packages/sdk/src/features/chat/infrastructure/repositories/InMemoryDraftRepository.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { - type ConversationKey, - conversationKeyString, -} from "../../domain/MessageRepository.ts"; -import type { DraftRepository } from "../../domain/DraftRepository.ts"; - -export class InMemoryDraftRepository implements DraftRepository { - private readonly map = new Map< - string, - { key: ConversationKey; text: string } - >(); - - async load(key: ConversationKey): Promise { - return this.map.get(conversationKeyString(key))?.text ?? ""; - } - - async save(key: ConversationKey, text: string): Promise { - if (text.length === 0) { - this.map.delete(conversationKeyString(key)); - return; - } - this.map.set(conversationKeyString(key), { key, text }); - } - - async clear(key: ConversationKey): Promise { - this.map.delete(conversationKeyString(key)); - } - - async loadAll(): Promise< - ReadonlyArray<{ key: ConversationKey; text: string }> - > { - return Array.from(this.map.values()); - } -} diff --git a/packages/sdk/src/features/chat/infrastructure/repositories/InMemoryMessageRepository.test.ts b/packages/sdk/src/features/chat/infrastructure/repositories/InMemoryMessageRepository.test.ts deleted file mode 100644 index 58760587b..000000000 --- a/packages/sdk/src/features/chat/infrastructure/repositories/InMemoryMessageRepository.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { ChannelNumber } from "../../../../core/types.ts"; -import type { Message } from "../../domain/Message.ts"; -import { MessageState } from "../../domain/MessageState.ts"; -import { InMemoryMessageRepository } from "./InMemoryMessageRepository.ts"; - -function msg(id: number, ms: number, text = "t"): Message { - return { - id, - from: 1, - to: 0xffffffff, - channel: ChannelNumber.Primary, - rxTime: new Date(ms), - type: "broadcast", - text, - state: MessageState.Ack, - }; -} - -describe("InMemoryMessageRepository", () => { - it("loadRecent returns the tail of a bucket", async () => { - const repo = new InMemoryMessageRepository(); - await repo.appendBatch([msg(1, 1000), msg(2, 2000), msg(3, 3000)]); - const out = await repo.loadRecent( - { kind: "channel", channel: ChannelNumber.Primary }, - 2, - ); - expect(out.map((m) => m.id)).toEqual([2, 3]); - }); - - it("loadBefore paginates older messages", async () => { - const repo = new InMemoryMessageRepository(); - await repo.appendBatch([ - msg(1, 1000), - msg(2, 2000), - msg(3, 3000), - msg(4, 4000), - ]); - const out = await repo.loadBefore( - { kind: "channel", channel: ChannelNumber.Primary }, - new Date(3000), - 10, - ); - expect(out.map((m) => m.id)).toEqual([1, 2]); - }); - - it("updateState mutates the matching message", async () => { - const repo = new InMemoryMessageRepository(); - await repo.append(msg(42, 1000)); - await repo.updateState(42, MessageState.Failed); - const [found] = await repo.loadRecent( - { kind: "channel", channel: ChannelNumber.Primary }, - 1, - ); - expect(found?.state).toBe(MessageState.Failed); - }); - - it("prune enforces maxPerBucket", async () => { - const repo = new InMemoryMessageRepository(); - await repo.appendBatch([ - msg(1, 1000), - msg(2, 2000), - msg(3, 3000), - msg(4, 4000), - ]); - await repo.prune({ maxPerBucket: 2 }); - const out = await repo.loadRecent( - { kind: "channel", channel: ChannelNumber.Primary }, - 10, - ); - expect(out.map((m) => m.id)).toEqual([3, 4]); - }); - - it("prune enforces olderThanMs", async () => { - const repo = new InMemoryMessageRepository(); - const now = Date.now(); - await repo.appendBatch([ - msg(1, now - 1000 * 60 * 60 * 24 * 10), - msg(2, now), - ]); - await repo.prune({ olderThanMs: 1000 * 60 * 60 * 24 }); - const out = await repo.loadRecent( - { kind: "channel", channel: ChannelNumber.Primary }, - 10, - ); - expect(out.map((m) => m.id)).toEqual([2]); - }); -}); diff --git a/packages/sdk/src/features/chat/infrastructure/repositories/InMemoryMessageRepository.ts b/packages/sdk/src/features/chat/infrastructure/repositories/InMemoryMessageRepository.ts deleted file mode 100644 index 599b49d22..000000000 --- a/packages/sdk/src/features/chat/infrastructure/repositories/InMemoryMessageRepository.ts +++ /dev/null @@ -1,132 +0,0 @@ -import type { Message, MessageDeliveryPatch } from "../../domain/Message.ts"; -import type { MessageState } from "../../domain/MessageState.ts"; -import { - type ConversationKey, - conversationKeyString, - inferConversation, - type MessageRepository, - type RetentionPolicy, -} from "../../domain/MessageRepository.ts"; - -/** - * Default in-memory MessageRepository. No persistence across reloads; useful - * for tests and for single-session apps that do not need history. - */ -export class InMemoryMessageRepository implements MessageRepository { - private readonly buckets = new Map(); - - async loadRecent(key: ConversationKey, limit: number): Promise { - const bucket = this.buckets.get(conversationKeyString(key)) ?? []; - return bucket.slice(-limit); - } - - async loadBefore( - key: ConversationKey, - cursor: Date, - limit: number, - ): Promise { - const bucket = this.buckets.get(conversationKeyString(key)) ?? []; - const idx = bucket.findIndex((m) => m.rxTime >= cursor); - const end = idx === -1 ? bucket.length : idx; - const start = Math.max(0, end - limit); - return bucket.slice(start, end); - } - - async append(message: Message, key?: ConversationKey): Promise { - this.insert( - conversationKeyString(key ?? inferConversation(message)), - message, - ); - } - - async appendBatch(messages: ReadonlyArray): Promise { - for (const message of messages) { - this.insert(conversationKeyString(inferConversation(message)), message); - } - } - - async refileSentDirect(localNodeNum: number): Promise { - const own = conversationKeyString({ kind: "direct", peer: localNodeNum }); - const bucket = this.buckets.get(own); - if (!bucket) return 0; - const sent = bucket.filter( - (m) => m.from === localNodeNum && m.to !== localNodeNum, - ); - if (sent.length === 0) return 0; - this.buckets.set( - own, - bucket.filter((m) => !sent.includes(m)), - ); - for (const m of sent) { - this.insert(conversationKeyString({ kind: "direct", peer: m.to }), m); - } - return sent.length; - } - - private insert(key: string, message: Message): void { - const bucket = this.buckets.get(key) ?? []; - bucket.push(message); - bucket.sort((a, b) => a.rxTime.getTime() - b.rxTime.getTime()); - this.buckets.set(key, bucket); - } - - async updateDelivery(id: number, patch: MessageDeliveryPatch): Promise { - for (const bucket of this.buckets.values()) { - const idx = bucket.findIndex((m) => m.id === id); - const existing = bucket[idx]; - if (existing) { - bucket[idx] = { ...existing, ...patch }; - return; - } - } - } - - async remove(id: number): Promise { - for (const bucket of this.buckets.values()) { - const idx = bucket.findIndex((m) => m.id === id); - if (idx !== -1) { - bucket.splice(idx, 1); - return; - } - } - } - - async updateState(id: number, state: MessageState): Promise { - for (const bucket of this.buckets.values()) { - const idx = bucket.findIndex((m) => m.id === id); - if (idx !== -1) { - const existing = bucket[idx]; - if (!existing) continue; - bucket[idx] = { ...existing, state }; - return; - } - } - } - - async prune(policy: RetentionPolicy): Promise { - const nowMs = Date.now(); - for (const [key, bucket] of this.buckets) { - let filtered = - policy.olderThanMs === undefined - ? bucket - : bucket.filter( - (m) => nowMs - m.rxTime.getTime() <= policy.olderThanMs!, - ); - if ( - policy.maxPerBucket !== undefined && - filtered.length > policy.maxPerBucket - ) { - filtered = filtered.slice(-policy.maxPerBucket); - } - this.buckets.set(key, filtered); - } - } - - async clearConversation(key: ConversationKey): Promise { - this.buckets.delete(conversationKeyString(key)); - } - - async clear(): Promise { - this.buckets.clear(); - } -} diff --git a/packages/sdk/src/features/chat/state/chatStore.ts b/packages/sdk/src/features/chat/state/chatStore.ts deleted file mode 100644 index 0e4994700..000000000 --- a/packages/sdk/src/features/chat/state/chatStore.ts +++ /dev/null @@ -1,152 +0,0 @@ -import { type Signal, signal } from "@preact/signals-core"; -import type { ReadonlySignal } from "../../../core/signals/createStore.ts"; -import { toReadonly } from "../../../core/signals/createStore.ts"; -import type { ChannelNumber } from "../../../core/types.ts"; -import type { Message, MessageDeliveryPatch } from "../domain/Message.ts"; -import { MessageState } from "../domain/MessageState.ts"; - -/** - * Messages grouped by conversation bucket. Direct messages are keyed by - * `direct:`; broadcast messages by `channel:`. - */ -export class ChatStore { - private readonly buckets = new Map>(); - private readonly readBuckets = new Map>(); - - channelKey(channel: ChannelNumber): string { - return `channel:${channel}`; - } - - directKey(peer: number): string { - return `direct:${peer}`; - } - - messagesForChannel(channel: ChannelNumber): ReadonlySignal { - return this.readBucket(this.channelKey(channel)); - } - - messagesForDirect(peer: number): ReadonlySignal { - return this.readBucket(this.directKey(peer)); - } - - append(key: string, message: Message): void { - const bucket = this.writeBucket(key); - bucket.value = [...bucket.value, message]; - } - - /** - * Adds stored messages to a bucket, skipping any it already holds, and - * keeps the bucket in time order. Used on hydrate, where live messages - * may already be in the bucket and the stored copy of one of them may - * come back from the query too. - */ - merge(key: string, messages: ReadonlyArray): void { - if (messages.length === 0) return; - const bucket = this.writeBucket(key); - const seen = new Set(bucket.value.map((m) => m.id)); - const added = messages.filter((m) => { - if (seen.has(m.id)) return false; - seen.add(m.id); - return true; - }); - if (added.length === 0) return; - bucket.value = [...bucket.value, ...added].sort( - (a, b) => a.rxTime.getTime() - b.rxTime.getTime(), - ); - } - - /** - * Whether a message with `id` is already present in the bucket. Used by - * the inbound-packet subscriber to skip duplicates of an outbound message - * that was optimistically appended on send. - */ - hasMessage(key: string, id: number): boolean { - const bucket = this.buckets.get(key); - if (!bucket) return false; - return bucket.value.some((m) => m.id === id); - } - - /** - * Inserts an older message at the front of the bucket. Used when paginating - * backwards; preserves chronological order because callers feed older-first. - */ - prepend(key: string, message: Message): void { - const bucket = this.writeBucket(key); - bucket.value = [message, ...bucket.value]; - } - - /** - * Empties a single conversation bucket. Signal subscribers re-render with - * an empty array. - */ - clearBucket(key: string): void { - const bucket = this.buckets.get(key); - if (bucket && bucket.value.length > 0) bucket.value = []; - } - - /** - * Empties every existing bucket. Buckets that have never been subscribed - * to don't exist yet, so nothing needs doing for them. - */ - clearAll(): void { - for (const bucket of this.buckets.values()) { - if (bucket.value.length > 0) bucket.value = []; - } - } - - updateState(id: number, state: MessageState): void { - this.patch(id, { state }); - } - - updateDelivery(id: number, patch: MessageDeliveryPatch): void { - this.patch(id, patch); - } - - remove(id: number): void { - for (const [, bucket] of this.buckets) { - if (bucket.value.some((m) => m.id === id)) { - bucket.value = bucket.value.filter((m) => m.id !== id); - return; - } - } - } - - getMessage(id: number): Message | undefined { - for (const bucket of this.buckets.values()) { - const found = bucket.value.find((m) => m.id === id); - if (found) return found; - } - return undefined; - } - - private patch(id: number, patch: MessageDeliveryPatch): void { - for (const [, bucket] of this.buckets) { - const idx = bucket.value.findIndex((m) => m.id === id); - if (idx !== -1) { - const next = bucket.value.slice(); - const existing = next[idx]; - if (!existing) continue; - next[idx] = { ...existing, ...patch }; - bucket.value = next; - return; - } - } - } - - private writeBucket(key: string): Signal { - let bucket = this.buckets.get(key); - if (!bucket) { - bucket = signal([]); - this.buckets.set(key, bucket); - this.readBuckets.set(key, toReadonly(bucket)); - } - return bucket; - } - - private readBucket(key: string): ReadonlySignal { - this.writeBucket(key); - const read = this.readBuckets.get(key); - if (!read) throw new Error("unreachable"); - return read; - } -} diff --git a/packages/sdk/src/features/chat/state/draftStore.ts b/packages/sdk/src/features/chat/state/draftStore.ts deleted file mode 100644 index 2fd211854..000000000 --- a/packages/sdk/src/features/chat/state/draftStore.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { type Signal, signal } from "@preact/signals-core"; -import { - type ReadonlySignal, - toReadonly, -} from "../../../core/signals/createStore.ts"; -import { - type ConversationKey, - conversationKeyString, -} from "../domain/MessageRepository.ts"; - -/** - * Per-conversation draft text exposed as readonly signals. Lazy creation: - * a signal is only allocated when a consumer subscribes to that - * conversation's draft. - */ -export class DraftStore { - private readonly buckets = new Map>(); - private readonly read = new Map>(); - - get(key: ConversationKey): ReadonlySignal { - const k = conversationKeyString(key); - this.ensure(k); - return this.read.get(k)!; - } - - set(key: ConversationKey, text: string): void { - const k = conversationKeyString(key); - this.ensure(k).value = text; - } - - clear(key: ConversationKey): void { - const k = conversationKeyString(key); - this.ensure(k).value = ""; - } - - /** - * Empties every draft. Signals stay in place so subscribers keep - * receiving updates. - */ - reset(): void { - for (const bucket of this.buckets.values()) bucket.value = ""; - } - - private ensure(k: string): Signal { - let bucket = this.buckets.get(k); - if (!bucket) { - bucket = signal(""); - this.buckets.set(k, bucket); - this.read.set(k, toReadonly(bucket)); - } - return bucket; - } -} diff --git a/packages/sdk/src/features/config/ConfigClient.test.ts b/packages/sdk/src/features/config/ConfigClient.test.ts deleted file mode 100644 index d0e5934bf..000000000 --- a/packages/sdk/src/features/config/ConfigClient.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { describe, expect, it } from "vitest"; -import { MeshClient } from "../../core/client/MeshClient.ts"; -import { createFakeTransport } from "../../core/testing/createFakeTransport.ts"; - -describe("ConfigClient", () => { - it("merges incoming Config packets into the radio signal by variant", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - - expect(client.config.radio.value).toEqual({}); - - client.events.onConfigPacket.dispatch( - create(Protobuf.Config.ConfigSchema, { - payloadVariant: { - case: "lora", - value: create(Protobuf.Config.Config_LoRaConfigSchema, { region: 4 }), - }, - }), - ); - - expect(client.config.radio.value.lora?.region).toBe(4); - }); - - it("merges incoming ModuleConfig packets into the modules signal", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - - client.events.onModuleConfigPacket.dispatch( - create(Protobuf.ModuleConfig.ModuleConfigSchema, { - payloadVariant: { - case: "mqtt", - value: create(Protobuf.ModuleConfig.ModuleConfig_MQTTConfigSchema, { - enabled: true, - }), - }, - }), - ); - - expect(client.config.modules.value.mqtt?.enabled).toBe(true); - }); - - describe("isRegionUnset", () => { - it("starts false until the first LoRa config packet arrives", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - expect(client.config.isRegionUnset.value).toBe(false); - }); - - it("flips true when an UNSET (0) LoRa region arrives", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - - client.events.onConfigPacket.dispatch( - create(Protobuf.Config.ConfigSchema, { - payloadVariant: { - case: "lora", - value: create(Protobuf.Config.Config_LoRaConfigSchema, { - region: Protobuf.Config.Config_LoRaConfig_RegionCode.UNSET, - }), - }, - }), - ); - - expect(client.config.isRegionUnset.value).toBe(true); - }); - - it("stays false once a real region is set", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - - client.events.onConfigPacket.dispatch( - create(Protobuf.Config.ConfigSchema, { - payloadVariant: { - case: "lora", - value: create(Protobuf.Config.Config_LoRaConfigSchema, { - region: Protobuf.Config.Config_LoRaConfig_RegionCode.US, - }), - }, - }), - ); - - expect(client.config.isRegionUnset.value).toBe(false); - }); - }); -}); diff --git a/packages/sdk/src/features/config/ConfigClient.ts b/packages/sdk/src/features/config/ConfigClient.ts deleted file mode 100644 index 1b820e1b9..000000000 --- a/packages/sdk/src/features/config/ConfigClient.ts +++ /dev/null @@ -1,181 +0,0 @@ -import * as Protobuf from "@meshtastic/protobufs"; -import { computed } from "@preact/signals-core"; -import { Result } from "better-result"; -import type { MeshClient } from "../../core/client/MeshClient.ts"; -import { - type ReadonlySignal, - toReadonly, -} from "../../core/signals/createStore.ts"; -import { - beginEditSettings, - commitEditSettings, - getConfig, - getModuleConfig, - setConfig, - setModuleConfig, -} from "./application/ConfigUseCases.ts"; -import { - requestCannedMessages, - requestRingtone, - setCannedMessages, - setRingtone, -} from "./application/ModuleMessagesUseCases.ts"; -import { DeviceStatusEnum } from "../device/domain/DeviceStatus.ts"; -import { ConfigEditor } from "./domain/ConfigEditor.ts"; -import type { ModuleConfig } from "./domain/ModuleConfig.ts"; -import type { RadioConfig } from "./domain/RadioConfig.ts"; -import { ConfigMapper } from "./infrastructure/ConfigMapper.ts"; -import { type ConfigStore, createConfigStore } from "./state/configStore.ts"; - -export class ConfigClient { - private readonly client: MeshClient; - private readonly store: ConfigStore; - public readonly radio: ReadonlySignal; - public readonly modules: ReadonlySignal; - public readonly editor: ConfigEditor; - /** - * `true` when the device has not yet been assigned a LoRa region — the - * canonical "newly-flashed / unconfigured device" cue. Mirrors - * Meshtastic-Android's `regionUnset` flow (a freshly-flashed firmware - * defaults `Config.LoRa.region` to `UNSET = 0` until the user picks one). - * - * Stays `false` until a LoRa config packet arrives, so consumers don't - * flash a "set region" prompt during the connect handshake. - */ - public readonly isRegionUnset: ReadonlySignal; - /** - * The device's `|`-separated canned message list, or undefined until - * {@link requestCannedMessages} has been answered. - */ - public readonly cannedMessages: ReadonlySignal; - /** - * The External Notification ringtone (RTTTL), or undefined until - * {@link requestRingtone} has been answered. - */ - public readonly ringtone: ReadonlySignal; - - constructor(client: MeshClient) { - this.client = client; - this.store = createConfigStore(); - this.radio = this.store.radio.read; - this.modules = this.store.modules.read; - this.cannedMessages = this.store.cannedMessages.read; - this.ringtone = this.store.ringtone.read; - this.editor = new ConfigEditor(client, { - onStagedAdminMessageCommitted: (message) => - this.applySentAdminMessage(message.payloadVariant), - }); - - this.isRegionUnset = toReadonly( - computed(() => { - const lora = this.store.radio.write.value.lora; - if (!lora) return false; - return ( - lora.region === Protobuf.Config.Config_LoRaConfig_RegionCode.UNSET - ); - }), - ); - - client.events.onConfigPacket.subscribe((config) => { - this.store.radio.write.value = ConfigMapper.mergeRadio( - this.store.radio.write.value, - config, - ); - }); - client.events.onModuleConfigPacket.subscribe((moduleConfig) => { - this.store.modules.write.value = ConfigMapper.mergeModule( - this.store.modules.write.value, - moduleConfig, - ); - }); - client.events.onAdminPacket.subscribe((packet) => { - // Only the local node's answers; a remote node's list is not ours. - if (packet.from !== client.myNodeNum) return; - const variant = packet.data.payloadVariant; - if (variant.case === "getCannedMessageModuleMessagesResponse") { - this.store.cannedMessages.write.value = variant.value; - } else if (variant.case === "getRingtoneResponse") { - this.store.ringtone.write.value = variant.value; - } - }); - client.events.onDeviceStatus.subscribe((status) => { - if (status === DeviceStatusEnum.DeviceDisconnected) { - this.store.cannedMessages.write.value = undefined; - this.store.ringtone.write.value = undefined; - } - }); - } - - /** Ask the device for its canned message list; see {@link cannedMessages}. */ - public requestCannedMessages(): Promise> { - return requestCannedMessages(this.client); - } - - /** Set the canned message list (`|`-separated, at most 200 bytes). */ - public async setCannedMessages( - messages: string, - ): Promise> { - const result = await setCannedMessages(this.client, messages); - if (Result.isOk(result)) { - this.store.cannedMessages.write.value = messages; - } - return result; - } - - /** Ask the device for its ringtone; see {@link ringtone}. */ - public requestRingtone(): Promise> { - return requestRingtone(this.client); - } - - /** Set the External Notification ringtone (RTTTL, at most 230 bytes). */ - public async setRingtone(ringtone: string): Promise> { - const result = await setRingtone(this.client, ringtone); - if (Result.isOk(result)) { - this.store.ringtone.write.value = ringtone; - } - return result; - } - - /** Keep the cached values in step with sets sent through the editor. */ - private applySentAdminMessage( - variant: Protobuf.Admin.AdminMessage["payloadVariant"], - ): void { - if (variant.case === "setCannedMessageModuleMessages") { - this.store.cannedMessages.write.value = variant.value; - } else if (variant.case === "setRingtoneMessage") { - this.store.ringtone.write.value = variant.value; - } - } - - public beginEdit(): Promise> { - return beginEditSettings(this.client); - } - - public commitEdit(): Promise> { - return commitEditSettings(this.client); - } - - public setRadio( - config: Protobuf.Config.Config, - ): Promise> { - return setConfig(this.client, config); - } - - public getRadio( - type: Protobuf.Admin.AdminMessage_ConfigType, - ): Promise> { - return getConfig(this.client, type); - } - - public setModule( - moduleConfig: Protobuf.ModuleConfig.ModuleConfig, - ): Promise> { - return setModuleConfig(this.client, moduleConfig); - } - - public getModule( - type: Protobuf.Admin.AdminMessage_ModuleConfigType, - ): Promise> { - return getModuleConfig(this.client, type); - } -} diff --git a/packages/sdk/src/features/config/ConfigEditor.test.ts b/packages/sdk/src/features/config/ConfigEditor.test.ts deleted file mode 100644 index b8ecbf0c1..000000000 --- a/packages/sdk/src/features/config/ConfigEditor.test.ts +++ /dev/null @@ -1,399 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { describe, expect, it } from "vitest"; -import { MeshClient } from "../../core/client/MeshClient.ts"; -import { createFakeTransport } from "../../core/testing/createFakeTransport.ts"; -import { interceptAdminMessages } from "../../core/testing/interceptAdminMessages.ts"; -import { DeviceStatusEnum } from "../../core/transport/Transport.ts"; - -function loraPacket(region: number): Protobuf.Config.Config { - return create(Protobuf.Config.ConfigSchema, { - payloadVariant: { - case: "lora", - value: create(Protobuf.Config.Config_LoRaConfigSchema, { region }), - }, - }); -} - -function mqttPacket(enabled: boolean): Protobuf.ModuleConfig.ModuleConfig { - return create(Protobuf.ModuleConfig.ModuleConfigSchema, { - payloadVariant: { - case: "mqtt", - value: create(Protobuf.ModuleConfig.ModuleConfig_MQTTConfigSchema, { - enabled, - }), - }, - }); -} - -function channelPacket(index: number, name: string): Protobuf.Channel.Channel { - return create(Protobuf.Channel.ChannelSchema, { - index, - role: Protobuf.Channel.Channel_Role.SECONDARY, - settings: create(Protobuf.Channel.ChannelSettingsSchema, { name }), - }); -} - -describe("ConfigEditor", () => { - it("starts clean and tracks dirty when working diverges from baseline", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const editor = client.config.editor; - - expect(editor.isDirty.value).toBe(false); - - client.events.onConfigPacket.dispatch(loraPacket(4)); - expect(editor.isDirty.value).toBe(false); - expect(editor.radio.value.lora?.region).toBe(4); - - editor.setRadioSection( - "lora", - create(Protobuf.Config.Config_LoRaConfigSchema, { region: 7 }), - ); - expect(editor.isDirty.value).toBe(true); - expect(editor.dirtyRadioSections.value).toEqual(["lora"]); - }); - - it("tracks module + channel dirtiness independently", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const editor = client.config.editor; - - client.events.onModuleConfigPacket.dispatch(mqttPacket(false)); - client.events.onChannelPacket.dispatch(channelPacket(1, "primary")); - - editor.setModuleSection( - "mqtt", - create(Protobuf.ModuleConfig.ModuleConfig_MQTTConfigSchema, { - enabled: true, - }), - ); - expect(editor.dirtyModuleSections.value).toEqual(["mqtt"]); - - editor.setChannel(channelPacket(1, "renamed")); - expect(editor.dirtyChannels.value).toEqual([1]); - expect(editor.isDirty.value).toBe(true); - }); - - it("reset() restores working = baseline and clears dirty flags", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const editor = client.config.editor; - - client.events.onConfigPacket.dispatch(loraPacket(4)); - editor.setRadioSection( - "lora", - create(Protobuf.Config.Config_LoRaConfigSchema, { region: 7 }), - ); - expect(editor.isDirty.value).toBe(true); - - editor.reset(); - expect(editor.isDirty.value).toBe(false); - expect(editor.radio.value.lora?.region).toBe(4); - }); - - it("reset() drops queued admin messages", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const editor = client.config.editor; - - editor.queueAdminMessage( - create(Protobuf.Admin.AdminMessageSchema, { - payloadVariant: { - case: "setFixedPosition", - value: create(Protobuf.Mesh.PositionSchema, { latitudeI: 1 }), - }, - }), - ); - expect(editor.isDirty.value).toBe(true); - - editor.reset(); - expect(editor.isDirty.value).toBe(false); - }); - - it("inbound baseline updates do not stomp pending working edits", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const editor = client.config.editor; - - // User edits lora region - client.events.onConfigPacket.dispatch(loraPacket(4)); - editor.setRadioSection( - "lora", - create(Protobuf.Config.Config_LoRaConfigSchema, { region: 7 }), - ); - - // Device pushes a baseline change for the same section while user is editing - client.events.onConfigPacket.dispatch(loraPacket(8)); - - // Working edit preserved; dirty still set - expect(editor.radio.value.lora?.region).toBe(7); - expect(editor.dirtyRadioSections.value).toEqual(["lora"]); - }); - - it("keeps radio fields a partial update leaves out", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const editor = client.config.editor; - - client.events.onConfigPacket.dispatch( - create(Protobuf.Config.ConfigSchema, { - payloadVariant: { - case: "lora", - value: create(Protobuf.Config.Config_LoRaConfigSchema, { - region: 4, - paFanDisabled: true, - ignoreIncoming: [1234], - }), - }, - }), - ); - - // Form data after zod validation: only the fields the form renders. - editor.setRadioSection("lora", { - region: 7, - } as unknown as Protobuf.Config.Config_LoRaConfig); - - const lora = editor.radio.value.lora; - expect(lora?.region).toBe(7); - expect(lora?.paFanDisabled).toBe(true); - expect(lora?.ignoreIncoming).toEqual([1234]); - expect(editor.dirtyRadioSections.value).toEqual(["lora"]); - }); - - it("keeps module fields a partial update leaves out", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const editor = client.config.editor; - - client.events.onModuleConfigPacket.dispatch( - create(Protobuf.ModuleConfig.ModuleConfigSchema, { - payloadVariant: { - case: "rangeTest", - value: create( - Protobuf.ModuleConfig.ModuleConfig_RangeTestConfigSchema, - { enabled: false, clearOnReboot: true }, - ), - }, - }), - ); - - editor.setModuleSection("rangeTest", { - enabled: true, - } as unknown as Protobuf.ModuleConfig.ModuleConfig_RangeTestConfig); - - expect(editor.modules.value.rangeTest?.enabled).toBe(true); - expect(editor.modules.value.rangeTest?.clearOnReboot).toBe(true); - }); - - it("a partial update equal to the baseline is not dirty", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const editor = client.config.editor; - - client.events.onConfigPacket.dispatch(loraPacket(4)); - editor.setRadioSection("lora", { - region: 4, - } as unknown as Protobuf.Config.Config_LoRaConfig); - - expect(editor.isDirty.value).toBe(false); - }); - - it("an undefined section reverts to the baseline", async () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const editor = client.config.editor; - const radio = interceptAdminMessages(client); - - client.events.onConfigPacket.dispatch(loraPacket(4)); - client.events.onModuleConfigPacket.dispatch(mqttPacket(false)); - editor.setRadioSection( - "lora", - create(Protobuf.Config.Config_LoRaConfigSchema, { region: 7 }), - ); - editor.setRadioSection("lora", undefined); - editor.setModuleSection("mqtt", undefined); - editor.setRadioSection("position", undefined); - - expect(editor.radio.value.lora?.region).toBe(4); - expect(editor.isDirty.value).toBe(false); - expect((await editor.commit()).status).toBe("ok"); - expect(radio.sent).toEqual([]); - }); - - it("disconnect drops baseline and working", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const editor = client.config.editor; - - client.events.onConfigPacket.dispatch(loraPacket(4)); - editor.setRadioSection( - "lora", - create(Protobuf.Config.Config_LoRaConfigSchema, { region: 7 }), - ); - expect(editor.isDirty.value).toBe(true); - - client.events.onDeviceStatus.dispatch(DeviceStatusEnum.DeviceDisconnected); - - expect(editor.radio.value).toEqual({}); - expect(editor.isDirty.value).toBe(false); - }); -}); - -const LORA = "lora" as const; - -/** A connected editor with lora edited from region 1 to 4. */ -function setupCommit() { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const editor = client.config.editor; - const radio = interceptAdminMessages(client); - - client.events.onConfigPacket.dispatch(loraPacket(1)); - client.events.onModuleConfigPacket.dispatch(mqttPacket(false)); - client.events.onChannelPacket.dispatch(channelPacket(1, "primary")); - editor.setRadioSection( - LORA, - create(Protobuf.Config.Config_LoRaConfigSchema, { region: 4 }), - ); - return { client, editor, radio }; -} - -const enableMqtt = () => - create(Protobuf.ModuleConfig.ModuleConfig_MQTTConfigSchema, { - enabled: true, - }); - -const user = (longName: string) => - create(Protobuf.Mesh.UserSchema, { id: "!00000001", longName }); - -describe("ConfigEditor.commit", () => { - it("keeps an edit made while a commit is in flight dirty", async () => { - const { editor, radio } = setupCommit(); - const held = radio.hold("commitEditSettings"); - - const pending = editor.commit(); - await held.reached; - editor.setModuleSection("mqtt", enableMqtt()); - held.release(); - expect((await pending).status).toBe("ok"); - - expect(editor.dirtyRadioSections.value).toEqual([]); - expect(editor.dirtyModuleSections.value).toEqual(["mqtt"]); - expect(radio.sentModuleConfig("mqtt")).toBeUndefined(); - - expect((await editor.commit()).status).toBe("ok"); - expect(radio.sentModuleConfig("mqtt")?.enabled).toBe(true); - expect(editor.isDirty.value).toBe(false); - }); - - it("keeps device packets for unsent sections that arrive during a commit", async () => { - const { client, editor, radio } = setupCommit(); - const held = radio.hold("commitEditSettings"); - - const pending = editor.commit(); - await held.reached; - client.events.onModuleConfigPacket.dispatch(mqttPacket(true)); - client.events.onChannelPacket.dispatch(channelPacket(1, "renamed")); - held.release(); - expect((await pending).status).toBe("ok"); - - expect(editor.isDirty.value).toBe(false); - expect(editor.modules.value.mqtt?.enabled).toBe(true); - expect(editor.channels.value.get(1)?.settings?.name).toBe("renamed"); - }); - - it("keeps an owner update that arrives during a commit", async () => { - const { editor, radio } = setupCommit(); - editor.setBaselineOwner(user("Before")); - const held = radio.hold("commitEditSettings"); - - const pending = editor.commit(); - await held.reached; - editor.setBaselineOwner(user("After")); - held.release(); - expect((await pending).status).toBe("ok"); - - expect(editor.isOwnerDirty.value).toBe(false); - expect(editor.owner.value?.longName).toBe("After"); - expect(radio.cases()).not.toContain("setOwner"); - }); - - it("leaves the editor empty when the device disconnects during a commit", async () => { - const { client, editor, radio } = setupCommit(); - const held = radio.hold("commitEditSettings"); - - const pending = editor.commit(); - await held.reached; - client.events.onDeviceStatus.dispatch(DeviceStatusEnum.DeviceDisconnected); - held.release(); - expect((await pending).status).toBe("error"); - - expect(editor.radio.value).toEqual({}); - expect(editor.isDirty.value).toBe(false); - client.events.onConfigPacket.dispatch(loraPacket(1)); - expect(editor.isDirty.value).toBe(false); - }); - - it("sends a message queued again during a commit", async () => { - const { editor, radio } = setupCommit(); - const message = create(Protobuf.Admin.AdminMessageSchema, { - payloadVariant: { case: "removeFixedPosition", value: true }, - }); - editor.queueAdminMessage(message); - const held = radio.hold("commitEditSettings"); - - const pending = editor.commit(); - await held.reached; - editor.queueAdminMessage(message); - held.release(); - expect((await pending).status).toBe("ok"); - expect(editor.isDirty.value).toBe(true); - - expect((await editor.commit()).status).toBe("ok"); - expect( - radio.cases().filter((c) => c === "removeFixedPosition"), - ).toHaveLength(2); - expect(editor.isDirty.value).toBe(false); - }); - - it("runs a commit requested during another after it finishes", async () => { - const { editor, radio } = setupCommit(); - const held = radio.hold("commitEditSettings"); - - const first = editor.commit(); - await held.reached; - editor.setModuleSection("mqtt", enableMqtt()); - const second = editor.commit(); - held.release(); - - expect((await first).status).toBe("ok"); - expect((await second).status).toBe("ok"); - expect(radio.cases()).toEqual([ - "beginEditSettings", - "setConfig", - "commitEditSettings", - "beginEditSettings", - "setModuleConfig", - "commitEditSettings", - ]); - expect(editor.isDirty.value).toBe(false); - }); - - it("closes the transaction and stays dirty when a send fails", async () => { - const { editor, radio } = setupCommit(); - editor.setModuleSection("mqtt", enableMqtt()); - radio.failNext("setModuleConfig"); - - expect((await editor.commit()).status).toBe("error"); - - expect(radio.cases()).toEqual([ - "beginEditSettings", - "setConfig", - "setModuleConfig", - "commitEditSettings", - ]); - expect(editor.dirtyRadioSections.value).toEqual([LORA]); - expect(editor.dirtyModuleSections.value).toEqual(["mqtt"]); - }); -}); diff --git a/packages/sdk/src/features/config/ModuleMessages.test.ts b/packages/sdk/src/features/config/ModuleMessages.test.ts deleted file mode 100644 index c5ba09316..000000000 --- a/packages/sdk/src/features/config/ModuleMessages.test.ts +++ /dev/null @@ -1,227 +0,0 @@ -import { create, fromBinary } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { Result } from "better-result"; -import { describe, expect, it, vi } from "vitest"; -import { MeshClient } from "../../core/client/MeshClient.ts"; -import { createFakeTransport } from "../../core/testing/createFakeTransport.ts"; -import { DeviceStatusEnum } from "../../core/transport/Transport.ts"; -import { - CANNED_MESSAGES_MAX_BYTES, - RINGTONE_MAX_BYTES, - requestCannedMessages, - requestRingtone, - setCannedMessages, - setRingtone, -} from "./application/ModuleMessagesUseCases.ts"; - -function makeClient() { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - const sendPacket = vi.spyOn(client, "sendPacket").mockResolvedValue(42); - const sentAdmin = () => - sendPacket.mock.calls.map((call) => - fromBinary(Protobuf.Admin.AdminMessageSchema, call[0] as Uint8Array), - ); - return { client, sendPacket, sentAdmin }; -} - -function adminPacket( - from: number, - payloadVariant: Protobuf.Admin.AdminMessage["payloadVariant"], -) { - return { - id: 1, - rxTime: new Date(), - type: "direct" as const, - from, - to: from, - channel: 0, - data: create(Protobuf.Admin.AdminMessageSchema, { payloadVariant }), - }; -} - -function admin(payloadVariant: Protobuf.Admin.AdminMessage["payloadVariant"]) { - return create(Protobuf.Admin.AdminMessageSchema, { payloadVariant }); -} - -describe("module message use-cases", () => { - it("requests the canned messages and the ringtone", async () => { - const { client, sentAdmin } = makeClient(); - expect(Result.isOk(await requestCannedMessages(client))).toBe(true); - expect(Result.isOk(await requestRingtone(client))).toBe(true); - expect(sentAdmin().map((m) => m.payloadVariant)).toEqual([ - { case: "getCannedMessageModuleMessagesRequest", value: true }, - { case: "getRingtoneRequest", value: true }, - ]); - }); - - it("sets the canned messages and the ringtone", async () => { - const { client, sentAdmin } = makeClient(); - const result = await setCannedMessages(client, "Hi|Bye"); - expect(Result.isOk(result) && result.value).toBe(42); - await setRingtone(client, "a:d=8,o=5,b=100:c"); - expect(sentAdmin().map((m) => m.payloadVariant)).toEqual([ - { case: "setCannedMessageModuleMessages", value: "Hi|Bye" }, - { case: "setRingtoneMessage", value: "a:d=8,o=5,b=100:c" }, - ]); - }); - - it("rejects values over the firmware byte limits without sending", async () => { - const { client, sendPacket } = makeClient(); - const messages = await setCannedMessages( - client, - "é".repeat(CANNED_MESSAGES_MAX_BYTES / 2 + 1), - ); - const ringtone = await setRingtone( - client, - "a".repeat(RINGTONE_MAX_BYTES + 1), - ); - expect(Result.isError(messages)).toBe(true); - expect(Result.isError(ringtone)).toBe(true); - expect(sendPacket).not.toHaveBeenCalled(); - }); - - it("returns an error when the send fails", async () => { - const { client, sendPacket } = makeClient(); - sendPacket.mockRejectedValueOnce(new Error("offline")); - const result = await requestRingtone(client); - expect(Result.isError(result) && result.error.message).toBe("offline"); - }); -}); - -describe("ConfigClient canned messages and ringtone", () => { - it("stays undefined until the local node answers", () => { - const { client } = makeClient(); - expect(client.config.cannedMessages.value).toBeUndefined(); - expect(client.config.ringtone.value).toBeUndefined(); - - client.events.onAdminPacket.dispatch( - adminPacket(client.myNodeNum, { - case: "getCannedMessageModuleMessagesResponse", - value: "Yes|No", - }), - ); - client.events.onAdminPacket.dispatch( - adminPacket(client.myNodeNum, { - case: "getRingtoneResponse", - value: "tone:d=4:c", - }), - ); - expect(client.config.cannedMessages.value).toBe("Yes|No"); - expect(client.config.ringtone.value).toBe("tone:d=4:c"); - }); - - it("ignores answers from other nodes", () => { - const { client } = makeClient(); - client.events.onAdminPacket.dispatch( - adminPacket(client.myNodeNum + 1, { - case: "getRingtoneResponse", - value: "remote", - }), - ); - expect(client.config.ringtone.value).toBeUndefined(); - }); - - it("forgets both on disconnect", () => { - const { client } = makeClient(); - client.events.onAdminPacket.dispatch( - adminPacket(client.myNodeNum, { - case: "getRingtoneResponse", - value: "tone", - }), - ); - client.events.onDeviceStatus.dispatch(DeviceStatusEnum.DeviceDisconnected); - expect(client.config.ringtone.value).toBeUndefined(); - }); - - it("caches a value it set", async () => { - const { client } = makeClient(); - await client.config.setCannedMessages("A|B"); - await client.config.setRingtone("r"); - expect(client.config.cannedMessages.value).toBe("A|B"); - expect(client.config.ringtone.value).toBe("r"); - }); -}); - -describe("ConfigEditor.stageAdminMessage", () => { - it("keeps one message per key and marks the editor dirty", () => { - const { client } = makeClient(); - const editor = client.config.editor; - editor.stageAdminMessage( - "cannedMessages", - admin({ case: "setCannedMessageModuleMessages", value: "a" }), - ); - editor.stageAdminMessage( - "cannedMessages", - admin({ case: "setCannedMessageModuleMessages", value: "ab" }), - ); - expect(editor.stagedAdminMessages.value.size).toBe(1); - expect( - editor.stagedAdminMessages.value.get("cannedMessages")?.payloadVariant - .value, - ).toBe("ab"); - expect(editor.isDirty.value).toBe(true); - - editor.stageAdminMessage("cannedMessages", undefined); - expect(editor.stagedAdminMessages.value.size).toBe(0); - expect(editor.isDirty.value).toBe(false); - }); - - it("drops staged messages on reset and disconnect", () => { - const { client } = makeClient(); - const editor = client.config.editor; - const ringtone = admin({ case: "setRingtoneMessage", value: "r" }); - - editor.stageAdminMessage("ringtone", ringtone); - editor.reset(); - expect(editor.stagedAdminMessages.value.size).toBe(0); - expect(editor.isDirty.value).toBe(false); - - editor.stageAdminMessage("ringtone", ringtone); - client.events.onDeviceStatus.dispatch(DeviceStatusEnum.DeviceDisconnected); - expect(editor.stagedAdminMessages.value.size).toBe(0); - }); - - it("sends staged messages inside the edit and caches them on commit", async () => { - const { client, sentAdmin } = makeClient(); - const editor = client.config.editor; - editor.stageAdminMessage( - "cannedMessages", - admin({ case: "setCannedMessageModuleMessages", value: "Hi|Bye" }), - ); - editor.stageAdminMessage( - "ringtone", - admin({ case: "setRingtoneMessage", value: "tone" }), - ); - - const result = await editor.commit(); - expect(Result.isOk(result)).toBe(true); - expect(sentAdmin().map((m) => m.payloadVariant.case)).toEqual([ - "beginEditSettings", - "setCannedMessageModuleMessages", - "setRingtoneMessage", - "commitEditSettings", - ]); - expect(editor.stagedAdminMessages.value.size).toBe(0); - expect(editor.isDirty.value).toBe(false); - expect(client.config.cannedMessages.value).toBe("Hi|Bye"); - expect(client.config.ringtone.value).toBe("tone"); - }); - - it("keeps staged messages when the commit fails", async () => { - const { client, sendPacket } = makeClient(); - const editor = client.config.editor; - editor.stageAdminMessage( - "ringtone", - admin({ case: "setRingtoneMessage", value: "tone" }), - ); - sendPacket - .mockResolvedValueOnce(1) - .mockRejectedValueOnce(new Error("no ack")); - - const result = await editor.commit(); - expect(Result.isError(result)).toBe(true); - expect(editor.stagedAdminMessages.value.size).toBe(1); - expect(client.config.ringtone.value).toBeUndefined(); - }); -}); diff --git a/packages/sdk/src/features/config/application/ConfigUseCases.ts b/packages/sdk/src/features/config/application/ConfigUseCases.ts deleted file mode 100644 index 06968c307..000000000 --- a/packages/sdk/src/features/config/application/ConfigUseCases.ts +++ /dev/null @@ -1,94 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; -import { Result } from "better-result"; -import type { MeshClient } from "../../../core/client/MeshClient.ts"; -import { sendAdminMessage } from "../../device/infrastructure/AdminMessageSender.ts"; - -export async function beginEditSettings( - client: MeshClient, -): Promise> { - client.events.onPendingSettingsChange.dispatch(true); - try { - const id = await sendAdminMessage(client, { - case: "beginEditSettings", - value: true, - }); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} - -export async function commitEditSettings( - client: MeshClient, -): Promise> { - client.events.onPendingSettingsChange.dispatch(false); - try { - const id = await sendAdminMessage(client, { - case: "commitEditSettings", - value: true, - }); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} - -export async function setConfig( - client: MeshClient, - config: Protobuf.Config.Config, -): Promise> { - try { - const id = await sendAdminMessage(client, { - case: "setConfig", - value: config, - }); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} - -export async function getConfig( - client: MeshClient, - type: Protobuf.Admin.AdminMessage_ConfigType, -): Promise> { - try { - const id = await sendAdminMessage(client, { - case: "getConfigRequest", - value: type, - }); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} - -export async function setModuleConfig( - client: MeshClient, - moduleConfig: Protobuf.ModuleConfig.ModuleConfig, -): Promise> { - try { - const id = await sendAdminMessage(client, { - case: "setModuleConfig", - value: moduleConfig, - }); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} - -export async function getModuleConfig( - client: MeshClient, - type: Protobuf.Admin.AdminMessage_ModuleConfigType, -): Promise> { - try { - const id = await sendAdminMessage(client, { - case: "getModuleConfigRequest", - value: type, - }); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} diff --git a/packages/sdk/src/features/config/application/ModuleMessagesUseCases.ts b/packages/sdk/src/features/config/application/ModuleMessagesUseCases.ts deleted file mode 100644 index e247d93a6..000000000 --- a/packages/sdk/src/features/config/application/ModuleMessagesUseCases.ts +++ /dev/null @@ -1,91 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; -import { Result } from "better-result"; -import type { MeshClient } from "../../../core/client/MeshClient.ts"; -import { sendAdminMessage } from "../../device/infrastructure/AdminMessageSender.ts"; - -/** - * The canned message list and the External Notification ringtone are not part - * of ModuleConfig. Firmware keeps each one as a single string and reads and - * writes it through its own admin messages. - */ - -/** nanopb max_size 201 for the `|`-separated canned message list. */ -export const CANNED_MESSAGES_MAX_BYTES = 200; -/** nanopb max_size 231 for the RTTTL ringtone. */ -export const RINGTONE_MAX_BYTES = 230; - -const encoder = new TextEncoder(); - -async function send( - client: MeshClient, - payloadVariant: Protobuf.Admin.AdminMessage["payloadVariant"], -): Promise> { - try { - return Result.ok(await sendAdminMessage(client, payloadVariant)); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} - -function tooLong(what: string, max: number): Error { - return new Error(`${what} is longer than ${max} bytes`); -} - -/** Admin message that sets the canned message list. */ -export function cannedMessagesAdminMessage( - messages: string, -): Protobuf.Admin.AdminMessage["payloadVariant"] { - return { case: "setCannedMessageModuleMessages", value: messages }; -} - -/** Admin message that sets the External Notification ringtone. */ -export function ringtoneAdminMessage( - ringtone: string, -): Protobuf.Admin.AdminMessage["payloadVariant"] { - return { case: "setRingtoneMessage", value: ringtone }; -} - -/** - * Ask the device for its canned message list. The answer arrives as a - * `getCannedMessageModuleMessagesResponse` admin message. - */ -export function requestCannedMessages( - client: MeshClient, -): Promise> { - return send(client, { - case: "getCannedMessageModuleMessagesRequest", - value: true, - }); -} - -export function setCannedMessages( - client: MeshClient, - messages: string, -): Promise> { - if (encoder.encode(messages).length > CANNED_MESSAGES_MAX_BYTES) { - return Promise.resolve( - Result.err(tooLong("Canned messages", CANNED_MESSAGES_MAX_BYTES)), - ); - } - return send(client, cannedMessagesAdminMessage(messages)); -} - -/** - * Ask the device for its ringtone. The answer arrives as a - * `getRingtoneResponse` admin message. - */ -export function requestRingtone( - client: MeshClient, -): Promise> { - return send(client, { case: "getRingtoneRequest", value: true }); -} - -export function setRingtone( - client: MeshClient, - ringtone: string, -): Promise> { - if (encoder.encode(ringtone).length > RINGTONE_MAX_BYTES) { - return Promise.resolve(Result.err(tooLong("Ringtone", RINGTONE_MAX_BYTES))); - } - return send(client, ringtoneAdminMessage(ringtone)); -} diff --git a/packages/sdk/src/features/config/domain/ConfigEditor.ts b/packages/sdk/src/features/config/domain/ConfigEditor.ts deleted file mode 100644 index b0f092892..000000000 --- a/packages/sdk/src/features/config/domain/ConfigEditor.ts +++ /dev/null @@ -1,636 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { signal } from "@preact/signals-core"; -import { Result } from "better-result"; -import type { MeshClient } from "../../../core/client/MeshClient.ts"; -import { - type ReadonlySignal, - toReadonly, -} from "../../../core/signals/createStore.ts"; -import { setChannel } from "../../channels/application/ChannelUseCases.ts"; -import { DeviceStatusEnum } from "../../device/domain/DeviceStatus.ts"; -import { sendAdminMessage } from "../../device/infrastructure/AdminMessageSender.ts"; -import { setOwner } from "../../nodes/application/SetOwnerUseCase.ts"; -import { - beginEditSettings, - commitEditSettings, - setConfig, - setModuleConfig, -} from "../application/ConfigUseCases.ts"; -import { ConfigMapper } from "../infrastructure/ConfigMapper.ts"; -import type { ModuleConfig, ModuleConfigSection } from "./ModuleConfig.ts"; -import type { RadioConfig, RadioConfigSection } from "./RadioConfig.ts"; - -/** - * Per-section editor for radio config, module config, and channels. - * - * Tracks two views: - * - * - **Baseline**: what the device most recently sent. Updated automatically - * from `onConfigPacket` / `onModuleConfigPacket` / `onChannelPacket` and - * re-applied as the post-commit truth. - * - **Working copy**: UI edits. Set via `setRadioSection` / `setModuleSection` - * / `setChannel`. Mid-edit baseline updates do NOT discard working changes; - * `dirty*` recomputes against the new baseline so the user keeps their edits. - * - * On disconnect both signals reset to empty so a stale working copy can never - * leak across reconnects. The next `onConfigPacket` re-fills baseline; working - * stays equal to baseline until the user edits again. - */ -export class ConfigEditor { - private readonly client: MeshClient; - private readonly baselineRadio = signal({}); - private readonly baselineModules = signal({}); - private readonly baselineChannels = signal< - ReadonlyMap - >(new Map()); - private readonly workingRadio = signal({}); - private readonly workingModules = signal({}); - private readonly workingChannels = signal< - ReadonlyMap - >(new Map()); - private readonly baselineOwner = signal( - undefined, - ); - private readonly workingOwner = signal( - undefined, - ); - private readonly queuedAdminMessages = signal< - readonly Protobuf.Admin.AdminMessage[] - >([]); - private readonly _stagedAdminMessages = signal< - ReadonlyMap - >(new Map()); - private readonly _dirtyRadioSections = signal( - [], - ); - private readonly _dirtyModuleSections = signal< - readonly ModuleConfigSection[] - >([]); - private readonly _dirtyChannels = signal([]); - private readonly _isOwnerDirty = signal(false); - private readonly _isDirty = signal(false); - - public readonly radio: ReadonlySignal = toReadonly( - this.workingRadio, - ); - public readonly modules: ReadonlySignal = toReadonly( - this.workingModules, - ); - public readonly channels: ReadonlySignal< - ReadonlyMap - > = toReadonly(this.workingChannels); - public readonly dirtyRadioSections: ReadonlySignal< - readonly RadioConfigSection[] - > = toReadonly(this._dirtyRadioSections); - public readonly dirtyModuleSections: ReadonlySignal< - readonly ModuleConfigSection[] - > = toReadonly(this._dirtyModuleSections); - public readonly dirtyChannels: ReadonlySignal = toReadonly( - this._dirtyChannels, - ); - public readonly owner: ReadonlySignal = - toReadonly(this.workingOwner); - public readonly isOwnerDirty: ReadonlySignal = toReadonly( - this._isOwnerDirty, - ); - public readonly isDirty: ReadonlySignal = toReadonly(this._isDirty); - /** - * Admin messages staged with {@link stageAdminMessage}, by key. Sent on the - * next commit; cleared by commit, reset and disconnect. - */ - public readonly stagedAdminMessages: ReadonlySignal< - ReadonlyMap - > = toReadonly(this._stagedAdminMessages); - - private readonly onStagedAdminMessageCommitted?: ( - message: Protobuf.Admin.AdminMessage, - ) => void; - - private commitQueue: Promise = Promise.resolve(); - /** Bumped on disconnect so an in-flight commit can tell. */ - private connectionGeneration = 0; - - constructor( - client: MeshClient, - options: { - /** Called for each staged admin message after a successful commit. */ - onStagedAdminMessageCommitted?: ( - message: Protobuf.Admin.AdminMessage, - ) => void; - } = {}, - ) { - this.client = client; - this.onStagedAdminMessageCommitted = options.onStagedAdminMessageCommitted; - - client.events.onConfigPacket.subscribe((config) => { - const next = ConfigMapper.mergeRadio(this.baselineRadio.peek(), config); - this.baselineRadio.value = next; - const variant = config.payloadVariant.case; - if (variant) { - // Apply baseline changes that don't conflict with a pending edit. If - // the user has already touched this section in the working copy, leave - // their edit in place; the dirty bookkeeping will refresh below. - const wasDirty = this._dirtyRadioSections.peek().includes(variant); - if (!wasDirty) { - this.workingRadio.value = { - ...this.workingRadio.peek(), - [variant]: next[variant], - }; - } - } - this.recomputeDirty(); - }); - - client.events.onModuleConfigPacket.subscribe((moduleConfig) => { - const next = ConfigMapper.mergeModule( - this.baselineModules.peek(), - moduleConfig, - ); - this.baselineModules.value = next; - const variant = moduleConfig.payloadVariant.case; - if (variant) { - const wasDirty = this._dirtyModuleSections.peek().includes(variant); - if (!wasDirty) { - this.workingModules.value = { - ...this.workingModules.peek(), - [variant]: next[variant], - }; - } - } - this.recomputeDirty(); - }); - - client.events.onChannelPacket.subscribe((channel) => { - const baseline = new Map(this.baselineChannels.peek()); - baseline.set(channel.index, channel); - this.baselineChannels.value = baseline; - const wasDirty = this._dirtyChannels.peek().includes(channel.index); - if (!wasDirty) { - const working = new Map(this.workingChannels.peek()); - working.set(channel.index, channel); - this.workingChannels.value = working; - } - this.recomputeDirty(); - }); - - client.events.onDeviceStatus.subscribe((status) => { - if (status === DeviceStatusEnum.DeviceDisconnected) { - this.connectionGeneration++; - this.baselineRadio.value = {}; - this.baselineModules.value = {}; - this.baselineChannels.value = new Map(); - this.baselineOwner.value = undefined; - this.workingRadio.value = {}; - this.workingModules.value = {}; - this.workingChannels.value = new Map(); - this.workingOwner.value = undefined; - this.queuedAdminMessages.value = []; - this._stagedAdminMessages.value = new Map(); - this._dirtyRadioSections.value = []; - this._dirtyModuleSections.value = []; - this._dirtyChannels.value = []; - this._isOwnerDirty.value = false; - this._isDirty.value = false; - } - }); - } - - /** - * Update the baseline owner (the device's current user). Web pulls this - * from `useMyNode().user` after the NodeInfo packet arrives, so we accept - * it through a setter rather than subscribing to a SDK signal. - */ - public setBaselineOwner(owner: Protobuf.Mesh.User | undefined): void { - this.baselineOwner.value = owner; - if (!this._isOwnerDirty.peek()) { - this.workingOwner.value = owner; - } - this.recomputeDirty(); - } - - public setOwner(owner: Protobuf.Mesh.User): void { - this.workingOwner.value = owner; - this.recomputeDirty(); - } - - /** - * Queue an arbitrary admin message to be sent inside the next commit - * (between beginEdit and commitEdit). Used for one-off side flows like - * setFixedPosition where the user wants to commit a pending coordinate - * alongside their other edits. - */ - public queueAdminMessage(message: Protobuf.Admin.AdminMessage): void { - this.queuedAdminMessages.value = [ - ...this.queuedAdminMessages.peek(), - message, - ]; - this.recomputeDirty(); - } - - /** - * Stage an admin message under `key`, replacing any message staged under - * the same key, or remove it with `undefined`. Unlike - * {@link queueAdminMessage}, a form can call this on every change and - * {@link reset} drops it. Used for settings that live outside Config and - * ModuleConfig, such as the canned message list and the ringtone. - */ - public stageAdminMessage( - key: string, - message: Protobuf.Admin.AdminMessage | undefined, - ): void { - const current = this._stagedAdminMessages.peek(); - if (message === undefined && !current.has(key)) return; - const next = new Map(current); - if (message === undefined) { - next.delete(key); - } else { - next.set(key, message); - } - this._stagedAdminMessages.value = next; - this.recomputeDirty(); - } - - /** - * Stage a radio config section. `value` is merged over the current working - * (or baseline) section, so fields a form doesn't render keep the device's - * value instead of being sent as protobuf defaults. `undefined` reverts the - * section to the baseline. - */ - public setRadioSection( - key: K, - value: RadioConfig[K], - ): void { - const working = this.workingRadio.peek(); - const baseline = this.baselineRadio.peek()[key]; - const current = working[key] ?? baseline; - this.workingRadio.value = { - ...working, - [key]: - value === undefined - ? baseline - : current - ? { ...current, ...value } - : value, - }; - this.recomputeDirty(); - } - - /** Stage a module config section, merged like {@link setRadioSection}. */ - public setModuleSection( - key: K, - value: ModuleConfig[K], - ): void { - const working = this.workingModules.peek(); - const baseline = this.baselineModules.peek()[key]; - const current = working[key] ?? baseline; - this.workingModules.value = { - ...working, - [key]: - value === undefined - ? baseline - : current - ? { ...current, ...value } - : value, - }; - this.recomputeDirty(); - } - - public setChannel(channel: Protobuf.Channel.Channel): void { - const next = new Map(this.workingChannels.peek()); - next.set(channel.index, channel); - this.workingChannels.value = next; - this.recomputeDirty(); - } - - public reset(): void { - this.workingRadio.value = this.baselineRadio.peek(); - this.workingModules.value = this.baselineModules.peek(); - this.workingChannels.value = new Map(this.baselineChannels.peek()); - this.workingOwner.value = this.baselineOwner.peek(); - this._stagedAdminMessages.value = new Map(); - this.queuedAdminMessages.value = []; - this.recomputeDirty(); - } - - /** - * Send all dirty sections to the device wrapped in a beginEdit/commitEdit - * pair. Commits run one at a time; edits made during a commit stay dirty - * for the next one. - */ - public commit(): Promise> { - const run = this.commitQueue.then(() => this.runCommit()); - this.commitQueue = run.catch(() => undefined); - return run; - } - - private async runCommit(): Promise> { - if (!this._isDirty.peek()) return Result.ok(undefined); - - // Taken before the first await. Setters replace the working signals, so - // later edits never reach it. - const payload = this.collectPayload(); - // An empty transaction makes the radio rewrite its config and report - // success for nothing. - if (isEmptyPayload(payload)) return Result.ok(undefined); - const generation = this.connectionGeneration; - - const beginResult = await beginEditSettings(this.client); - if (Result.isError(beginResult)) return Result.err(beginResult.error); - - const sendResult = await this.sendPayload(payload); - if (Result.isError(sendResult)) { - // There is no abort message. Close the transaction rather than leave it - // open; everything stays dirty, so the next commit resends it. - if (generation === this.connectionGeneration) { - await commitEditSettings(this.client); - } - return Result.err(sendResult.error); - } - - const commitResult = await commitEditSettings(this.client); - if (Result.isError(commitResult)) return Result.err(commitResult.error); - - // Disconnect already cleared the editor; don't carry this payload into - // the next connection. - if (generation !== this.connectionGeneration) { - return Result.err( - new Error("The device disconnected before the commit finished"), - ); - } - - this.reconcileAfterCommit(payload); - for (const message of payload.staged.values()) { - this.onStagedAdminMessageCommitted?.(message); - } - return Result.ok(undefined); - } - - private collectPayload(): CommitPayload { - const radio = this.workingRadio.peek(); - const radioPayload: CommitPayload["radio"] = []; - for (const variant of this._dirtyRadioSections.peek()) { - const value = radio[variant]; - if (value !== undefined) radioPayload.push([variant, value]); - } - - const modules = this.workingModules.peek(); - const modulePayload: CommitPayload["modules"] = []; - for (const variant of this._dirtyModuleSections.peek()) { - const value = modules[variant]; - if (value !== undefined) modulePayload.push([variant, value]); - } - - const channels = this.workingChannels.peek(); - const channelPayload: CommitPayload["channels"] = []; - for (const index of this._dirtyChannels.peek()) { - const channel = channels.get(index); - if (channel) channelPayload.push([index, channel]); - } - - return { - radio: radioPayload, - modules: modulePayload, - channels: channelPayload, - owner: this._isOwnerDirty.peek() ? this.workingOwner.peek() : undefined, - queued: this.queuedAdminMessages.peek(), - staged: this._stagedAdminMessages.peek(), - }; - } - - private async sendPayload( - payload: CommitPayload, - ): Promise> { - for (const [variant, value] of payload.radio) { - const result = await setConfig( - this.client, - buildRadioConfig(variant, value), - ); - if (Result.isError(result)) return Result.err(result.error); - } - - for (const [variant, value] of payload.modules) { - const result = await setModuleConfig( - this.client, - buildModuleConfig(variant, value), - ); - if (Result.isError(result)) return Result.err(result.error); - } - - for (const [, channel] of payload.channels) { - const result = await setChannel(this.client, channel); - if (Result.isError(result)) return Result.err(result.error); - } - - if (payload.owner) { - const result = await setOwner(this.client, payload.owner); - if (Result.isError(result)) return Result.err(result.error); - } - - for (const message of [...payload.queued, ...payload.staged.values()]) { - const variant = message.payloadVariant; - if (!variant.case) continue; - try { - await sendAdminMessage(this.client, variant); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } - } - - return Result.ok(undefined); - } - - /** - * Make only what was sent the new baseline. Other sections keep theirs, - * including device packets that arrived during the commit. - */ - private reconcileAfterCommit(payload: CommitPayload): void { - if (payload.radio.length > 0) { - const baseline: Record = { - ...this.baselineRadio.peek(), - }; - for (const [variant, value] of payload.radio) baseline[variant] = value; - this.baselineRadio.value = baseline as RadioConfig; - } - - if (payload.modules.length > 0) { - const baseline: Record = { - ...this.baselineModules.peek(), - }; - for (const [variant, value] of payload.modules) baseline[variant] = value; - this.baselineModules.value = baseline as ModuleConfig; - } - - if (payload.channels.length > 0) { - const baseline = new Map(this.baselineChannels.peek()); - for (const [index, channel] of payload.channels) { - baseline.set(index, channel); - } - this.baselineChannels.value = baseline; - } - - if (payload.owner) this.baselineOwner.value = payload.owner; - - // One entry per message sent: the same object may have been queued again - // during the commit, and that copy hasn't been sent. - if (payload.queued.length > 0) { - const remaining = [...this.queuedAdminMessages.peek()]; - for (const message of payload.queued) { - const index = remaining.indexOf(message); - if (index !== -1) remaining.splice(index, 1); - } - this.queuedAdminMessages.value = remaining; - } - - if (payload.staged.size > 0) { - const unsent = new Map(this._stagedAdminMessages.peek()); - for (const [key, message] of payload.staged) { - if (unsent.get(key) === message) unsent.delete(key); - } - this._stagedAdminMessages.value = unsent; - } - - this.recomputeDirty(); - } - - private recomputeDirty(): void { - const radioBase = this.baselineRadio.peek(); - const radioWorking = this.workingRadio.peek(); - const radioDirty: RadioConfigSection[] = []; - const radioKeys = new Set([ - ...Object.keys(radioBase), - ...Object.keys(radioWorking), - ]); - for (const key of radioKeys) { - if ( - !shallowEqual( - radioBase[key as keyof RadioConfig], - radioWorking[key as keyof RadioConfig], - ) - ) { - radioDirty.push(key as RadioConfigSection); - } - } - - const moduleBase = this.baselineModules.peek(); - const moduleWorking = this.workingModules.peek(); - const moduleDirty: ModuleConfigSection[] = []; - const moduleKeys = new Set([ - ...Object.keys(moduleBase), - ...Object.keys(moduleWorking), - ]); - for (const key of moduleKeys) { - if ( - !shallowEqual( - moduleBase[key as keyof ModuleConfig], - moduleWorking[key as keyof ModuleConfig], - ) - ) { - moduleDirty.push(key as ModuleConfigSection); - } - } - - const channelDirty: number[] = []; - const channelBase = this.baselineChannels.peek(); - const channelWorking = this.workingChannels.peek(); - const channelKeys = new Set([ - ...channelBase.keys(), - ...channelWorking.keys(), - ]); - for (const idx of channelKeys) { - if (!shallowEqual(channelBase.get(idx), channelWorking.get(idx))) { - channelDirty.push(idx); - } - } - - const ownerDirty = !shallowEqual( - this.baselineOwner.peek(), - this.workingOwner.peek(), - ); - const hasQueuedAdmin = - this.queuedAdminMessages.peek().length > 0 || - this._stagedAdminMessages.peek().size > 0; - - this._dirtyRadioSections.value = radioDirty; - this._dirtyModuleSections.value = moduleDirty; - this._dirtyChannels.value = channelDirty; - this._isOwnerDirty.value = ownerDirty; - this._isDirty.value = - radioDirty.length > 0 || - moduleDirty.length > 0 || - channelDirty.length > 0 || - ownerDirty || - hasQueuedAdmin; - } -} - -interface CommitPayload { - radio: [RadioConfigSection, NonNullable][]; - modules: [ - ModuleConfigSection, - NonNullable, - ][]; - channels: [number, Protobuf.Channel.Channel][]; - /** Set only when the owner was dirty. */ - owner: Protobuf.Mesh.User | undefined; - queued: readonly Protobuf.Admin.AdminMessage[]; - staged: ReadonlyMap; -} - -function isEmptyPayload(payload: CommitPayload): boolean { - return ( - payload.radio.length === 0 && - payload.modules.length === 0 && - payload.channels.length === 0 && - payload.owner === undefined && - payload.queued.length === 0 && - payload.staged.size === 0 - ); -} - -function buildRadioConfig( - variant: RadioConfigSection, - value: unknown, -): Protobuf.Config.Config { - return create(Protobuf.Config.ConfigSchema, { - payloadVariant: { - case: variant, - value, - } as Protobuf.Config.Config["payloadVariant"], - }); -} - -function buildModuleConfig( - variant: ModuleConfigSection, - value: unknown, -): Protobuf.ModuleConfig.ModuleConfig { - return create(Protobuf.ModuleConfig.ModuleConfigSchema, { - payloadVariant: { - case: variant, - value, - } as Protobuf.ModuleConfig.ModuleConfig["payloadVariant"], - }); -} - -function shallowEqual(a: unknown, b: unknown): boolean { - if (a === b) return true; - if (a === undefined || b === undefined) return false; - if (a === null || b === null) return false; - if (typeof a !== "object" || typeof b !== "object") return false; - const ao = a as Record; - const bo = b as Record; - const aKeys = Object.keys(ao); - const bKeys = Object.keys(bo); - if (aKeys.length !== bKeys.length) return false; - for (const k of aKeys) { - const av = ao[k]; - const bv = bo[k]; - if (av === bv) continue; - if (typeof av === "object" && typeof bv === "object") { - if (!shallowEqual(av, bv)) return false; - } else { - return false; - } - } - return true; -} diff --git a/packages/sdk/src/features/config/domain/ModuleConfig.ts b/packages/sdk/src/features/config/domain/ModuleConfig.ts deleted file mode 100644 index 60d9f0d18..000000000 --- a/packages/sdk/src/features/config/domain/ModuleConfig.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; - -export type ModuleConfigSection = Exclude< - Protobuf.ModuleConfig.ModuleConfig["payloadVariant"]["case"], - undefined ->; - -export type ModuleConfig = { - readonly [V in ModuleConfigSection]?: Extract< - Protobuf.ModuleConfig.ModuleConfig["payloadVariant"], - { case: V } - >["value"]; -}; diff --git a/packages/sdk/src/features/config/domain/RadioConfig.ts b/packages/sdk/src/features/config/domain/RadioConfig.ts deleted file mode 100644 index 4e95bcd16..000000000 --- a/packages/sdk/src/features/config/domain/RadioConfig.ts +++ /dev/null @@ -1,21 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; - -/** - * The radio-config sections keyed by their protobuf variant case (excluding - * the "no variant" undefined case). - */ -export type RadioConfigSection = Exclude< - Protobuf.Config.Config["payloadVariant"]["case"], - undefined ->; - -/** - * Section -> proto-payload map, derived directly from the Config message so - * new variants stay typed automatically. - */ -export type RadioConfig = { - readonly [V in RadioConfigSection]?: Extract< - Protobuf.Config.Config["payloadVariant"], - { case: V } - >["value"]; -}; diff --git a/packages/sdk/src/features/config/index.ts b/packages/sdk/src/features/config/index.ts deleted file mode 100644 index 8862dd546..000000000 --- a/packages/sdk/src/features/config/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -export { ConfigClient } from "./ConfigClient.ts"; -export { ConfigEditor } from "./domain/ConfigEditor.ts"; -export { - CANNED_MESSAGES_MAX_BYTES, - RINGTONE_MAX_BYTES, -} from "./application/ModuleMessagesUseCases.ts"; -export type { RadioConfig, RadioConfigSection } from "./domain/RadioConfig.ts"; -export type { - ModuleConfig, - ModuleConfigSection, -} from "./domain/ModuleConfig.ts"; -export { ConfigMapper } from "./infrastructure/ConfigMapper.ts"; diff --git a/packages/sdk/src/features/config/infrastructure/ConfigMapper.ts b/packages/sdk/src/features/config/infrastructure/ConfigMapper.ts deleted file mode 100644 index 37ad4d8a3..000000000 --- a/packages/sdk/src/features/config/infrastructure/ConfigMapper.ts +++ /dev/null @@ -1,22 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; -import type { ModuleConfig } from "../domain/ModuleConfig.ts"; -import type { RadioConfig } from "../domain/RadioConfig.ts"; - -export const ConfigMapper = { - mergeRadio( - existing: RadioConfig, - incoming: Protobuf.Config.Config, - ): RadioConfig { - const variant = incoming.payloadVariant; - if (!variant.case) return existing; - return { ...existing, [variant.case]: variant.value }; - }, - mergeModule( - existing: ModuleConfig, - incoming: Protobuf.ModuleConfig.ModuleConfig, - ): ModuleConfig { - const variant = incoming.payloadVariant; - if (!variant.case) return existing; - return { ...existing, [variant.case]: variant.value }; - }, -}; diff --git a/packages/sdk/src/features/config/state/configStore.ts b/packages/sdk/src/features/config/state/configStore.ts deleted file mode 100644 index e8ed65f3e..000000000 --- a/packages/sdk/src/features/config/state/configStore.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { createStore } from "../../../core/signals/createStore.ts"; -import type { ModuleConfig } from "../domain/ModuleConfig.ts"; -import type { RadioConfig } from "../domain/RadioConfig.ts"; - -export function createConfigStore() { - return { - radio: createStore({}), - modules: createStore({}), - cannedMessages: createStore(undefined), - ringtone: createStore(undefined), - }; -} - -export type ConfigStore = ReturnType; diff --git a/packages/sdk/src/features/device/DeviceClient.keyVerification.test.ts b/packages/sdk/src/features/device/DeviceClient.keyVerification.test.ts deleted file mode 100644 index 4e3340ce0..000000000 --- a/packages/sdk/src/features/device/DeviceClient.keyVerification.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { fromBinary } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { describe, expect, it } from "vitest"; -import { MeshClient } from "../../core/client/MeshClient.ts"; -import { createFakeTransport } from "../../core/testing/createFakeTransport.ts"; - -describe("DeviceClient.sendKeyVerification", () => { - it("sends a KeyVerificationAdmin to the local node", async () => { - const { transport, sent } = createFakeTransport(); - const client = new MeshClient({ transport, heartbeatIntervalMs: false }); - - client.device - .sendKeyVerification( - Protobuf.Admin.KeyVerificationAdmin_MessageType.PROVIDE_SECURITY_NUMBER, - 0, - 123n, - 456, - ) - .catch(() => {}); - await new Promise((resolve) => setTimeout(resolve, 300)); - - const toRadio = fromBinary(Protobuf.Mesh.ToRadioSchema, sent[0]!); - if (toRadio.payloadVariant.case !== "packet") throw new Error("no packet"); - const data = toRadio.payloadVariant.value.payloadVariant; - if (data.case !== "decoded") throw new Error("encrypted"); - const admin = fromBinary( - Protobuf.Admin.AdminMessageSchema, - data.value.payload, - ); - expect(admin.payloadVariant.case).toBe("keyVerification"); - if (admin.payloadVariant.case !== "keyVerification") return; - expect(admin.payloadVariant.value).toMatchObject({ - messageType: - Protobuf.Admin.KeyVerificationAdmin_MessageType.PROVIDE_SECURITY_NUMBER, - remoteNodenum: 0, - nonce: 123n, - securityNumber: 456, - }); - }); -}); diff --git a/packages/sdk/src/features/device/DeviceClient.ts b/packages/sdk/src/features/device/DeviceClient.ts deleted file mode 100644 index 99743a728..000000000 --- a/packages/sdk/src/features/device/DeviceClient.ts +++ /dev/null @@ -1,221 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import type { MeshClient } from "../../core/client/MeshClient.ts"; -import { - type ReadonlySignal, - toReadonly, -} from "../../core/signals/createStore.ts"; -import { DeviceStatusEnum } from "../../core/transport/Transport.ts"; -import { reboot, rebootOta, shutdown } from "./application/RebootService.ts"; -import { computed } from "@preact/signals-core"; -import { getMetadata } from "./application/GetMetadataUseCase.ts"; -import { - disableLockdown, - isLockedState, - lockNow, - unlock, - type UnlockOptions, -} from "./application/LockdownService.ts"; -import { - type FirmwareSupport, - firmwareSupport, -} from "./domain/FirmwareVersion.ts"; -import { AdminSession } from "./infrastructure/AdminSession.ts"; -import { sendAdminMessage } from "./infrastructure/AdminMessageSender.ts"; -import { createDeviceStore, type DeviceStore } from "./state/deviceStore.ts"; - -/** - * Device slice facade. Owns status/metadata signals and exposes the - * reboot/shutdown/metadata commands. - */ -export class DeviceClient { - private readonly store: DeviceStore; - private readonly client: MeshClient; - private unlockPending = false; - - /** Admin session passkeys, per node. */ - public readonly session: AdminSession; - - public readonly status: ReadonlySignal; - public readonly isConfigured: ReadonlySignal; - public readonly pendingSettingsChanges: ReadonlySignal; - public readonly myNodeNum: ReadonlySignal; - public readonly metadata: ReadonlySignal< - Protobuf.Mesh.DeviceMetadata | undefined - >; - public readonly myNodeInfo: ReadonlySignal< - Protobuf.Mesh.MyNodeInfo | undefined - >; - /** - * Latest lockdown status, on firmware built with lockdown support. While - * the state is LOCKED, NEEDS_PROVISION or UNLOCK_FAILED the device withholds - * its channels and NodeDB. - */ - public readonly lockdownStatus: ReadonlySignal< - Protobuf.Mesh.LockdownStatus | undefined - >; - /** - * True while a lockdown build withholds its channels and NodeDB until the - * client unlocks it with {@link unlock}. - */ - public readonly isLocked: ReadonlySignal; - /** How well this client supports the connected node's firmware. */ - public readonly firmwareSupport: ReadonlySignal; - /** Per-region allowed presets and defaults (firmware 2.8+). */ - public readonly regionPresets: ReadonlySignal< - Protobuf.Mesh.LoRaRegionPresetMap | undefined - >; - - constructor(client: MeshClient) { - this.client = client; - this.session = new AdminSession(client.events); - this.store = createDeviceStore(); - this.status = this.store.status.read; - this.isConfigured = this.store.isConfigured.read; - this.pendingSettingsChanges = this.store.pendingSettingsChanges.read; - this.myNodeNum = this.store.myNodeNum.read; - this.metadata = this.store.metadata.read; - this.myNodeInfo = this.store.myNodeInfo.read; - this.lockdownStatus = this.store.lockdownStatus.read; - this.regionPresets = this.store.regionPresets.read; - this.firmwareSupport = this.store.firmwareSupport.read; - this.isLocked = toReadonly( - computed(() => isLockedState(this.store.lockdownStatus.write.value)), - ); - - client.events.onDeviceStatus.subscribe((status) => { - this.store.status.write.value = status; - if (status === DeviceStatusEnum.DeviceConfigured) { - this.store.isConfigured.write.value = true; - this.seedOwnSession(); - } else if (status === DeviceStatusEnum.DeviceConfiguring) { - this.store.isConfigured.write.value = false; - } else if (status === DeviceStatusEnum.DeviceDisconnected) { - this.session.clear(); - this.unlockPending = false; - this.store.lockdownStatus.write.value = undefined; - } - }); - - client.events.onMyNodeInfo.subscribe((info) => { - // Firmware 2.8 can renumber the node; passkeys belong to the old one. - if ( - this.store.myNodeNum.read.value !== undefined && - this.store.myNodeNum.read.value !== info.myNodeNum - ) { - this.session.clear(); - } - this.store.myNodeInfo.write.value = info; - this.store.myNodeNum.write.value = info.myNodeNum; - }); - - client.events.onDeviceMetadataPacket.subscribe((pkt) => { - // Remote nodes answer getMetadata through the same event; only the - // handshake's metadata (from 0) or our own node's describes this device. - if (pkt.from !== 0 && pkt.from !== client.myNodeNum) return; - this.store.metadata.write.value = pkt.data; - this.store.firmwareSupport.write.value = firmwareSupport( - pkt.data.firmwareVersion, - ); - }); - - client.events.onLockdownStatus.subscribe((status) => { - const wasLocked = isLockedState(this.store.lockdownStatus.write.peek()); - this.store.lockdownStatus.write.value = status; - // After an unlock the device only releases its config to a new - // handshake on the same link. Re-run it only when this session saw the - // device locked or sent a passphrase, so a repeated UNLOCKED can't loop. - if ( - status.state === Protobuf.Mesh.LockdownStatus_State.UNLOCKED && - (wasLocked || this.unlockPending) - ) { - this.unlockPending = false; - this.client.configure().catch((e: unknown) => { - this.client.log.warn("⚠️ Handshake after unlock failed", e); - }); - } else if (isLockedState(status)) { - this.unlockPending = false; - } - }); - - client.events.onRegionPresets.subscribe((presets) => { - this.store.regionPresets.write.value = presets; - }); - - client.events.onPendingSettingsChange.subscribe((pending) => { - this.store.pendingSettingsChanges.write.value = pending; - }); - } - - /** - * Ask the connected node for its owner once the handshake completes. The - * response carries the session passkey, as the Android app and the Kotlin - * SDK do it. - */ - private seedOwnSession(): void { - // A locked device answers nothing useful until it is unlocked; the - // handshake that follows the unlock seeds the session instead. - if (isLockedState(this.store.lockdownStatus.write.peek())) return; - sendAdminMessage(this.client, { - case: "getOwnerRequest", - value: true, - }).catch((e: unknown) => { - this.client.log.warn("⚠️ Unable to seed the admin session", e); - }); - } - - /** - * Drive the manual key-verification handshake through the local node. - * Start it with INITIATE_VERIFICATION and the remote node number; answer the - * node's prompts with remoteNodenum 0 and the nonce from the prompt, since - * the node correlates the exchange by nonce. - */ - public sendKeyVerification( - messageType: Protobuf.Admin.KeyVerificationAdmin_MessageType, - remoteNodenum: number, - nonce: bigint, - securityNumber?: number, - ): Promise { - return sendAdminMessage(this.client, { - case: "keyVerification", - value: create(Protobuf.Admin.KeyVerificationAdminSchema, { - messageType, - remoteNodenum, - nonce, - securityNumber, - }), - }); - } - - /** Send the lockdown passphrase. The result arrives on lockdownStatus. */ - public unlock(options: UnlockOptions): Promise { - this.unlockPending = true; - return unlock(this.client, options); - } - - /** Lock the device again now. */ - public lockNow(): Promise { - return lockNow(this.client); - } - - /** Turn lockdown off for good. See {@link disableLockdown}. */ - public disableLockdown(passphrase: string): Promise { - return disableLockdown(this.client, passphrase); - } - - public reboot(seconds = 0): Promise { - return reboot(this.client, seconds); - } - - public rebootOta(seconds = 0): Promise { - return rebootOta(this.client, seconds); - } - - public shutdown(seconds = 0): Promise { - return shutdown(this.client, seconds); - } - - public getMetadata(nodeNum: number): Promise { - return getMetadata(this.client, nodeNum); - } -} diff --git a/packages/sdk/src/features/device/application/ConfigureUseCase.ts b/packages/sdk/src/features/device/application/ConfigureUseCase.ts deleted file mode 100644 index b7d8ab8ea..000000000 --- a/packages/sdk/src/features/device/application/ConfigureUseCase.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { MeshClient } from "../../../core/client/MeshClient.ts"; - -/** - * Kicks off the wantConfigId handshake. The bulk of configuration state is - * filled asynchronously as the device streams back FromRadio packets — - * ConfigClient/NodesClient/ChannelsClient populate their stores from events. - */ -export async function configure(client: MeshClient): Promise { - return client.configure(); -} diff --git a/packages/sdk/src/features/device/application/DisconnectUseCase.ts b/packages/sdk/src/features/device/application/DisconnectUseCase.ts deleted file mode 100644 index 88f9fc556..000000000 --- a/packages/sdk/src/features/device/application/DisconnectUseCase.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { MeshClient } from "../../../core/client/MeshClient.ts"; - -export async function disconnect(client: MeshClient): Promise { - await client.disconnect(); -} diff --git a/packages/sdk/src/features/device/application/GetMetadataUseCase.ts b/packages/sdk/src/features/device/application/GetMetadataUseCase.ts deleted file mode 100644 index 6ed27bb89..000000000 --- a/packages/sdk/src/features/device/application/GetMetadataUseCase.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { MeshClient } from "../../../core/client/MeshClient.ts"; -import { ChannelNumber } from "../../../core/types.ts"; -import { sendAdminMessage } from "../infrastructure/AdminMessageSender.ts"; - -export function getMetadata( - client: MeshClient, - nodeNum: number, -): Promise { - return sendAdminMessage( - client, - { case: "getDeviceMetadataRequest", value: true }, - nodeNum, - ChannelNumber.Admin, - ); -} diff --git a/packages/sdk/src/features/device/application/HeartbeatService.ts b/packages/sdk/src/features/device/application/HeartbeatService.ts deleted file mode 100644 index 303033b44..000000000 --- a/packages/sdk/src/features/device/application/HeartbeatService.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { MeshClient } from "../../../core/client/MeshClient.ts"; - -export function startHeartbeat(client: MeshClient, intervalMs: number): void { - client.setHeartbeatInterval(intervalMs); -} - -export function sendHeartbeat(client: MeshClient): Promise { - return client.heartbeat(); -} diff --git a/packages/sdk/src/features/device/application/LockdownService.test.ts b/packages/sdk/src/features/device/application/LockdownService.test.ts deleted file mode 100644 index e6409f3a5..000000000 --- a/packages/sdk/src/features/device/application/LockdownService.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { create, fromBinary } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { MeshClient } from "../../../core/client/MeshClient.ts"; -import { CONFIG_NONCE, NODEDB_NONCE } from "../../../core/client/handshake.ts"; -import { createFakeTransport } from "../../../core/testing/createFakeTransport.ts"; - -const State = Protobuf.Mesh.LockdownStatus_State; - -function decode(sent: Uint8Array[]) { - return sent.map((b) => fromBinary(Protobuf.Mesh.ToRadioSchema, b)); -} - -function adminSent(sent: Uint8Array[]) { - return decode(sent).flatMap((m) => { - if (m.payloadVariant.case !== "packet") return []; - const d = m.payloadVariant.value.payloadVariant; - if (d.case !== "decoded") return []; - return [fromBinary(Protobuf.Admin.AdminMessageSchema, d.value.payload)]; - }); -} - -describe("lockdown", () => { - beforeEach(() => vi.useFakeTimers()); - afterEach(() => vi.useRealTimers()); - - async function connectLocked() { - const fake = createFakeTransport(); - const client = new MeshClient({ - transport: fake.transport, - heartbeatIntervalMs: false, - }); - client.configure().catch(() => {}); - await vi.advanceTimersByTimeAsync(300); - fake.respond.withMyNodeInfo({ myNodeNum: 0x1234 }); - fake.respond.withConfigCompleteId(CONFIG_NONCE); - fake.respond.withRaw( - create(Protobuf.Mesh.FromRadioSchema, { - payloadVariant: { - case: "lockdownStatus", - value: { state: State.LOCKED }, - }, - }), - ); - await vi.advanceTimersByTimeAsync(1_000); - fake.respond.withConfigCompleteId(NODEDB_NONCE); - await vi.advanceTimersByTimeAsync(500); - return { ...fake, client }; - } - - it("reports a locked device and skips the session seed", async () => { - const { client, sent } = await connectLocked(); - expect(client.device.isLocked.value).toBe(true); - expect( - adminSent(sent).some((a) => a.payloadVariant.case === "getOwnerRequest"), - ).toBe(false); - }); - - it("sends the passphrase and re-runs the handshake once unlocked", async () => { - const { client, respond, sent } = await connectLocked(); - client.device.unlock({ passphrase: "hunter2" }).catch(() => {}); - await vi.advanceTimersByTimeAsync(500); - - const auth = adminSent(sent).find( - (a) => a.payloadVariant.case === "lockdownAuth", - ); - if (auth?.payloadVariant.case !== "lockdownAuth") throw new Error("none"); - expect(new TextDecoder().decode(auth.payloadVariant.value.passphrase)).toBe( - "hunter2", - ); - expect(auth.payloadVariant.value.bootsRemaining).toBe(50); - - const before = decode(sent).filter( - (m) => m.payloadVariant.case === "wantConfigId", - ).length; - respond.withRaw( - create(Protobuf.Mesh.FromRadioSchema, { - payloadVariant: { - case: "lockdownStatus", - value: { state: State.UNLOCKED }, - }, - }), - ); - await vi.advanceTimersByTimeAsync(500); - const wantConfigs = decode(sent).filter( - (m) => m.payloadVariant.case === "wantConfigId", - ); - expect(wantConfigs.length).toBe(before + 1); - expect(wantConfigs.at(-1)?.payloadVariant.value).toBe(CONFIG_NONCE); - expect(client.device.isLocked.value).toBe(false); - }); - - it("does not re-run the handshake for an UNLOCKED it didn't ask for", async () => { - const fake = createFakeTransport(); - const client = new MeshClient({ - transport: fake.transport, - heartbeatIntervalMs: false, - }); - fake.respond.withRaw( - create(Protobuf.Mesh.FromRadioSchema, { - payloadVariant: { - case: "lockdownStatus", - value: { state: State.UNLOCKED }, - }, - }), - ); - await vi.advanceTimersByTimeAsync(500); - expect(fake.sent).toHaveLength(0); - expect(client.device.isLocked.value).toBe(false); - }); -}); diff --git a/packages/sdk/src/features/device/application/LockdownService.ts b/packages/sdk/src/features/device/application/LockdownService.ts deleted file mode 100644 index 73b51e2b1..000000000 --- a/packages/sdk/src/features/device/application/LockdownService.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import type { MeshClient } from "../../../core/client/MeshClient.ts"; -import { sendAdminMessage } from "../infrastructure/AdminMessageSender.ts"; - -/** Boots an unlock stays valid for when the caller doesn't say. */ -export const DEFAULT_UNLOCK_BOOTS = 50; - -export interface UnlockOptions { - passphrase: string; - /** Reboots the unlock survives. Defaults to {@link DEFAULT_UNLOCK_BOOTS}. */ - bootsRemaining?: number; - /** Hours until the unlock expires; 0 or unset means no time limit. */ - validForHours?: number; - /** Per-boot session cap in seconds; 0 or unset means unlimited. */ - maxSessionSeconds?: number; -} - -const LOCKED_STATES = new Set([ - Protobuf.Mesh.LockdownStatus_State.NEEDS_PROVISION, - Protobuf.Mesh.LockdownStatus_State.LOCKED, - Protobuf.Mesh.LockdownStatus_State.UNLOCK_FAILED, -]); - -/** True while the device withholds its config until the client unlocks it. */ -export const isLockedState = ( - status: Protobuf.Mesh.LockdownStatus | undefined, -): boolean => !!status && LOCKED_STATES.has(status.state); - -function sendLockdownAuth( - client: MeshClient, - auth: Parameters>[1], -): Promise { - // LockdownAuth only works on the local node. Its outcome arrives as - // FromRadio.lockdown_status, not as an admin response. - return sendAdminMessage( - client, - { - case: "lockdownAuth", - value: create(Protobuf.Admin.LockdownAuthSchema, auth), - }, - "self", - undefined, - true, - false, - ); -} - -export function unlock(client: MeshClient, options: UnlockOptions) { - const hours = options.validForHours ?? 0; - return sendLockdownAuth(client, { - passphrase: new TextEncoder().encode(options.passphrase), - bootsRemaining: Math.max(0, options.bootsRemaining ?? DEFAULT_UNLOCK_BOOTS), - validUntilEpoch: - hours > 0 ? Math.floor(Date.now() / 1000) + hours * 3600 : 0, - maxSessionSeconds: Math.max(0, options.maxSessionSeconds ?? 0), - }); -} - -export function lockNow(client: MeshClient) { - return sendLockdownAuth(client, { lockNow: true }); -} - -/** - * Turn lockdown off. Irreversible: the device decrypts its storage, removes - * the passphrase and reboots out of lockdown. - */ -export function disableLockdown(client: MeshClient, passphrase: string) { - return sendLockdownAuth(client, { - passphrase: new TextEncoder().encode(passphrase), - disable: true, - }); -} diff --git a/packages/sdk/src/features/device/application/RebootService.ts b/packages/sdk/src/features/device/application/RebootService.ts deleted file mode 100644 index a26e09a07..000000000 --- a/packages/sdk/src/features/device/application/RebootService.ts +++ /dev/null @@ -1,29 +0,0 @@ -import type { MeshClient } from "../../../core/client/MeshClient.ts"; -import { sendAdminMessage } from "../infrastructure/AdminMessageSender.ts"; - -export function shutdown(client: MeshClient, seconds: number): Promise { - return sendAdminMessage(client, { case: "shutdownSeconds", value: seconds }); -} - -export function reboot(client: MeshClient, seconds: number): Promise { - return sendAdminMessage(client, { case: "rebootSeconds", value: seconds }); -} - -export function rebootOta( - client: MeshClient, - seconds: number, -): Promise { - return sendAdminMessage(client, { case: "rebootOtaSeconds", value: seconds }); -} - -export function factoryResetDevice(client: MeshClient): Promise { - return sendAdminMessage(client, { case: "factoryResetDevice", value: 1 }); -} - -export function factoryResetConfig(client: MeshClient): Promise { - return sendAdminMessage(client, { case: "factoryResetConfig", value: 1 }); -} - -export function enterDfuMode(client: MeshClient): Promise { - return sendAdminMessage(client, { case: "enterDfuModeRequest", value: true }); -} diff --git a/packages/sdk/src/features/device/domain/Device.ts b/packages/sdk/src/features/device/domain/Device.ts deleted file mode 100644 index 73bce4be6..000000000 --- a/packages/sdk/src/features/device/domain/Device.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; - -/** - * Aggregate representing a single connected device — its identity, status, - * and hardware metadata. - */ -export interface Device { - readonly myNodeNum: number; - readonly hwModel?: Protobuf.Mesh.HardwareModel; - readonly rebootCount?: number; - readonly firmwareVersion?: string; - readonly metadata?: Protobuf.Mesh.DeviceMetadata; -} diff --git a/packages/sdk/src/features/device/domain/DeviceStatus.ts b/packages/sdk/src/features/device/domain/DeviceStatus.ts deleted file mode 100644 index 5163805c9..000000000 --- a/packages/sdk/src/features/device/domain/DeviceStatus.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { DeviceStatusEnum } from "../../../core/transport/Transport.ts"; - -export { DeviceStatusEnum }; - -export function isConnected(status: DeviceStatusEnum): boolean { - return ( - status === DeviceStatusEnum.DeviceConnected || - status === DeviceStatusEnum.DeviceConfiguring || - status === DeviceStatusEnum.DeviceConfigured - ); -} - -export function isConfigured(status: DeviceStatusEnum): boolean { - return status === DeviceStatusEnum.DeviceConfigured; -} diff --git a/packages/sdk/src/features/device/domain/FirmwareVersion.test.ts b/packages/sdk/src/features/device/domain/FirmwareVersion.test.ts deleted file mode 100644 index 42ee16ed8..000000000 --- a/packages/sdk/src/features/device/domain/FirmwareVersion.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { firmwareAtLeast, firmwareSupport } from "./FirmwareVersion.ts"; - -describe("firmwareSupport", () => { - it.each([ - ["2.8.1.8e6a88d", "supported"], - ["2.5.14", "supported"], - ["2.5.13.abc", "shouldUpdate"], - ["2.3.15", "shouldUpdate"], - ["2.3.14", "tooOld"], - ["1.9.0", "tooOld"], - ["", "unknown"], - ["unknown", "unknown"], - ])("%s is %s", (version, expected) => { - expect(firmwareSupport(version)).toBe(expected); - }); - - it("compares numerically, not as text", () => { - expect(firmwareAtLeast("2.10.0", "2.8.1")).toBe(true); - expect(firmwareAtLeast("2.8.0", "2.8.1")).toBe(false); - expect(firmwareAtLeast("", "2.8.1")).toBe(false); - }); -}); diff --git a/packages/sdk/src/features/device/domain/FirmwareVersion.ts b/packages/sdk/src/features/device/domain/FirmwareVersion.ts deleted file mode 100644 index e51506001..000000000 --- a/packages/sdk/src/features/device/domain/FirmwareVersion.ts +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Firmware support levels, matching the Android app's DeviceVersion checks. - * Below {@link MIN_FIRMWARE_VERSION} the client still works but the user - * should update; below {@link ABS_MIN_FIRMWARE_VERSION} the client refuses - * to connect. A version that doesn't parse (lockdown sends an empty one) is - * "unknown", never "too old". - */ -export const MIN_FIRMWARE_VERSION = "2.5.14"; -export const ABS_MIN_FIRMWARE_VERSION = "2.3.15"; - -export type FirmwareSupport = - | "supported" - | "shouldUpdate" - | "tooOld" - | "unknown"; - -/** Parse "2.7.15.abc1234" or "2.7.15" into [major, minor, patch]. */ -export function parseFirmwareVersion( - version: string, -): [number, number, number] | undefined { - const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version.trim()); - if (!match) return undefined; - return [Number(match[1]), Number(match[2]), Number(match[3])]; -} - -export function compareFirmwareVersions( - a: [number, number, number], - b: [number, number, number], -): number { - for (let i = 0; i < 3; i++) { - const diff = a[i]! - b[i]!; - if (diff !== 0) return diff; - } - return 0; -} - -/** True when `version` parses and is at least `minimum`. */ -export function firmwareAtLeast(version: string, minimum: string): boolean { - const v = parseFirmwareVersion(version); - const min = parseFirmwareVersion(minimum); - return !!v && !!min && compareFirmwareVersions(v, min) >= 0; -} - -export function firmwareSupport(version: string): FirmwareSupport { - if (!parseFirmwareVersion(version)) return "unknown"; - if (!firmwareAtLeast(version, ABS_MIN_FIRMWARE_VERSION)) return "tooOld"; - if (!firmwareAtLeast(version, MIN_FIRMWARE_VERSION)) return "shouldUpdate"; - return "supported"; -} diff --git a/packages/sdk/src/features/device/index.ts b/packages/sdk/src/features/device/index.ts deleted file mode 100644 index d26849604..000000000 --- a/packages/sdk/src/features/device/index.ts +++ /dev/null @@ -1,7 +0,0 @@ -export { DeviceClient } from "./DeviceClient.ts"; -export type { Device } from "./domain/Device.ts"; -export { - DeviceStatusEnum, - isConfigured, - isConnected, -} from "./domain/DeviceStatus.ts"; diff --git a/packages/sdk/src/features/device/infrastructure/AdminMessageSender.ts b/packages/sdk/src/features/device/infrastructure/AdminMessageSender.ts deleted file mode 100644 index 410065788..000000000 --- a/packages/sdk/src/features/device/infrastructure/AdminMessageSender.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { create, toBinary } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import type { MeshClient } from "../../../core/client/MeshClient.ts"; -import { - ChannelNumber, - type Destination, - type PacketError, -} from "../../../core/types.ts"; - -const isBadSessionKey = (e: unknown): boolean => - (e as PacketError | undefined)?.error === - Protobuf.Mesh.Routing_Error.ADMIN_BAD_SESSION_KEY; - -/** - * Builds an AdminMessage from a payload variant and sends it over the ADMIN_APP - * portnum. Shared by config, channels, nodes, position, and device slices so - * the plumbing is not duplicated across 15+ use-cases. - * - * Stamps the destination's session passkey when one is cached. If the node - * rejects it with ADMIN_BAD_SESSION_KEY, asks the node for a fresh passkey - * and retries once. - */ -export async function sendAdminMessage( - client: MeshClient, - payloadVariant: Protobuf.Admin.AdminMessage["payloadVariant"], - destination: Destination = "self", - channel: ChannelNumber = ChannelNumber.Primary, - wantAck = true, - wantResponse = true, -): Promise { - const nodeNum = - destination === "self" - ? client.myNodeNum - : destination === "broadcast" - ? undefined - : destination; - - const send = () => { - const message = create(Protobuf.Admin.AdminMessageSchema, { - payloadVariant, - sessionPasskey: - nodeNum === undefined ? undefined : client.device.session.get(nodeNum), - }); - return client.sendPacket( - toBinary(Protobuf.Admin.AdminMessageSchema, message), - Protobuf.Portnums.PortNum.ADMIN_APP, - destination, - channel, - wantAck, - wantResponse, - ); - }; - - try { - return await send(); - } catch (e) { - if (nodeNum === undefined || !isBadSessionKey(e)) throw e; - client.device.session.forget(nodeNum); - if (!(await refreshSession(client, nodeNum, channel))) throw e; - return send(); - } -} - -/** - * Ask a node for something cheap that it answers with a fresh passkey, and - * wait for it. The local node is asked for its owner and remote nodes for - * their metadata, as the Android app does. - */ -async function refreshSession( - client: MeshClient, - nodeNum: number, - channel: ChannelNumber, -): Promise { - const arrived = client.device.session.waitFor(nodeNum); - const request: Protobuf.Admin.AdminMessage["payloadVariant"] = - nodeNum === client.myNodeNum - ? { case: "getOwnerRequest", value: true } - : { case: "getDeviceMetadataRequest", value: true }; - const message = create(Protobuf.Admin.AdminMessageSchema, { - payloadVariant: request, - }); - client - .sendPacket( - toBinary(Protobuf.Admin.AdminMessageSchema, message), - Protobuf.Portnums.PortNum.ADMIN_APP, - nodeNum, - channel, - ) - .catch(() => { - // The response, not the ack, is what carries the passkey. - }); - return arrived; -} diff --git a/packages/sdk/src/features/device/infrastructure/AdminSession.test.ts b/packages/sdk/src/features/device/infrastructure/AdminSession.test.ts deleted file mode 100644 index 406b49783..000000000 --- a/packages/sdk/src/features/device/infrastructure/AdminSession.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { MeshClient } from "../../../core/client/MeshClient.ts"; -import { createFakeTransport } from "../../../core/testing/createFakeTransport.ts"; -import { sendAdminMessage } from "./AdminMessageSender.ts"; -import { SESSION_PASSKEY_TTL_MS } from "./AdminSession.ts"; - -const REMOTE = 0x42; -const KEY = new Uint8Array([9, 8, 7, 6]); - -function setup() { - const fake = createFakeTransport(); - const client = new MeshClient({ - transport: fake.transport, - heartbeatIntervalMs: false, - }); - return { ...fake, client }; -} - -function adminFrom( - from: number, - payloadVariant: Protobuf.Admin.AdminMessage["payloadVariant"], - sessionPasskey = KEY, -) { - return create(Protobuf.Mesh.MeshPacketSchema, { - from, - to: 1, - id: Math.floor(Math.random() * 1e9) + 1, - payloadVariant: { - case: "decoded", - value: { - portnum: Protobuf.Portnums.PortNum.ADMIN_APP, - payload: toBinary( - Protobuf.Admin.AdminMessageSchema, - create(Protobuf.Admin.AdminMessageSchema, { - payloadVariant, - sessionPasskey, - }), - ), - }, - }, - }); -} - -function sentAdmin(sent: Uint8Array[]) { - return sent.flatMap((bytes) => { - const toRadio = fromBinary(Protobuf.Mesh.ToRadioSchema, bytes); - if (toRadio.payloadVariant.case !== "packet") return []; - const packet = toRadio.payloadVariant.value; - if (packet.payloadVariant.case !== "decoded") return []; - const data = packet.payloadVariant.value; - if (data.portnum !== Protobuf.Portnums.PortNum.ADMIN_APP) return []; - return [ - { - to: packet.to, - id: packet.id, - admin: fromBinary(Protobuf.Admin.AdminMessageSchema, data.payload), - }, - ]; - }); -} - -describe("AdminSession", () => { - beforeEach(() => { - vi.useFakeTimers(); - }); - afterEach(() => { - vi.useRealTimers(); - }); - - it("caches the passkey from a node's admin response and stamps it", async () => { - const { client, respond, sent } = setup(); - respond.withMeshPacket( - adminFrom(REMOTE, { - case: "getDeviceMetadataResponse", - value: create(Protobuf.Mesh.DeviceMetadataSchema), - }), - ); - await vi.advanceTimersByTimeAsync(10); - expect(client.device.session.get(REMOTE)).toEqual(KEY); - - sendAdminMessage(client, { case: "rebootSeconds", value: 5 }, REMOTE).catch( - () => {}, - ); - await vi.advanceTimersByTimeAsync(500); - const [reboot] = sentAdmin(sent); - expect(reboot?.to).toBe(REMOTE); - expect(reboot?.admin.sessionPasskey).toEqual(KEY); - }); - - it("forgets a passkey after the TTL", async () => { - const { client, respond } = setup(); - respond.withMeshPacket( - adminFrom(REMOTE, { - case: "getDeviceMetadataResponse", - value: create(Protobuf.Mesh.DeviceMetadataSchema), - }), - ); - await vi.advanceTimersByTimeAsync(10); - await vi.advanceTimersByTimeAsync(SESSION_PASSKEY_TTL_MS + 1); - expect(client.device.session.get(REMOTE)).toBeUndefined(); - }); - - it("ignores admin messages without a passkey", async () => { - const { client, respond } = setup(); - respond.withMeshPacket( - adminFrom( - REMOTE, - { - case: "getDeviceMetadataResponse", - value: create(Protobuf.Mesh.DeviceMetadataSchema), - }, - new Uint8Array(), - ), - ); - await vi.advanceTimersByTimeAsync(10); - expect(client.device.session.get(REMOTE)).toBeUndefined(); - }); - - it("re-seeds and retries once on ADMIN_BAD_SESSION_KEY", async () => { - const { client, respond, sent } = setup(); - const result = sendAdminMessage( - client, - { case: "rebootSeconds", value: 5 }, - REMOTE, - ); - result.catch(() => {}); - await vi.advanceTimersByTimeAsync(500); - const [first] = sentAdmin(sent); - expect(first?.admin.sessionPasskey).toHaveLength(0); - - client.queue.processError({ - id: first!.id, - error: Protobuf.Mesh.Routing_Error.ADMIN_BAD_SESSION_KEY, - }); - await vi.advanceTimersByTimeAsync(500); - const seed = sentAdmin(sent)[1]; - expect(seed?.admin.payloadVariant.case).toBe("getDeviceMetadataRequest"); - - respond.withMeshPacket( - adminFrom(REMOTE, { - case: "getDeviceMetadataResponse", - value: create(Protobuf.Mesh.DeviceMetadataSchema), - }), - ); - await vi.advanceTimersByTimeAsync(500); - const retry = sentAdmin(sent)[2]; - expect(retry?.admin.payloadVariant.case).toBe("rebootSeconds"); - expect(retry?.admin.sessionPasskey).toEqual(KEY); - - client.queue.processAck(retry!.id); - await expect(result).resolves.toBe(retry!.id); - }); -}); diff --git a/packages/sdk/src/features/device/infrastructure/AdminSession.ts b/packages/sdk/src/features/device/infrastructure/AdminSession.ts deleted file mode 100644 index 3a23879b8..000000000 --- a/packages/sdk/src/features/device/infrastructure/AdminSession.ts +++ /dev/null @@ -1,83 +0,0 @@ -import type { EventBus } from "../../../core/event-bus/EventBus.ts"; - -/** - * Firmware rotates the admin session passkey every 150 s and accepts one for - * 300 s. Using it for at most 4 minutes keeps a safety margin. - */ -export const SESSION_PASSKEY_TTL_MS = 4 * 60_000; - -/** How long to wait for a node to answer the request that seeds its passkey. */ -export const SESSION_SEED_TIMEOUT_MS = 30_000; - -interface Entry { - key: Uint8Array; - receivedAt: number; -} - -/** - * Per-node cache of admin session passkeys. Firmware attaches a passkey to - * every admin response; a client must send it back on admin writes to that - * node, or remote nodes reject them with ADMIN_BAD_SESSION_KEY. - * - * Only responses are trusted: the passkey is latched from admin messages that - * a node sent us, never from our own requests. - */ -export class AdminSession { - private readonly keys = new Map(); - private readonly waiters = new Map void)[]>(); - - constructor( - events: EventBus, - private readonly now: () => number = Date.now, - ) { - events.onAdminPacket.subscribe((packet) => { - const key = packet.data.sessionPasskey; - if (key.length === 0) return; - this.keys.set(packet.from, { key, receivedAt: this.now() }); - const waiting = this.waiters.get(packet.from); - this.waiters.delete(packet.from); - for (const resolve of waiting ?? []) resolve(); - }); - } - - /** The node's passkey, if one arrived within the TTL. */ - public get(nodeNum: number): Uint8Array | undefined { - const entry = this.keys.get(nodeNum); - if (!entry) return undefined; - if (this.now() - entry.receivedAt > SESSION_PASSKEY_TTL_MS) { - this.keys.delete(nodeNum); - return undefined; - } - return entry.key; - } - - public forget(nodeNum: number): void { - this.keys.delete(nodeNum); - } - - public clear(): void { - this.keys.clear(); - } - - /** Resolves true once a passkey from the node arrives, false on timeout. */ - public waitFor( - nodeNum: number, - timeoutMs = SESSION_SEED_TIMEOUT_MS, - ): Promise { - return new Promise((resolve) => { - const timer = setTimeout(() => { - const list = this.waiters.get(nodeNum) ?? []; - this.waiters.set( - nodeNum, - list.filter((w) => w !== onKey), - ); - resolve(false); - }, timeoutMs); - const onKey = () => { - clearTimeout(timer); - resolve(true); - }; - this.waiters.set(nodeNum, [...(this.waiters.get(nodeNum) ?? []), onKey]); - }); - } -} diff --git a/packages/sdk/src/features/device/state/deviceStore.ts b/packages/sdk/src/features/device/state/deviceStore.ts deleted file mode 100644 index 587415248..000000000 --- a/packages/sdk/src/features/device/state/deviceStore.ts +++ /dev/null @@ -1,45 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; -import { createStore } from "../../../core/signals/createStore.ts"; -import { DeviceStatusEnum } from "../../../core/transport/Transport.ts"; -import type { FirmwareSupport } from "../domain/FirmwareVersion.ts"; - -/** - * Writable signals for the device slice. Only the slice application layer - * mutates these; callers consume the `.read` readonly facades exposed by - * DeviceClient. - */ -export function createDeviceStore() { - const status = createStore( - DeviceStatusEnum.DeviceDisconnected, - ); - const isConfigured = createStore(false); - const pendingSettingsChanges = createStore(false); - const myNodeNum = createStore(undefined); - const metadata = createStore( - undefined, - ); - const myNodeInfo = createStore( - undefined, - ); - const firmwareSupport = createStore("unknown"); - const lockdownStatus = createStore( - undefined, - ); - const regionPresets = createStore< - Protobuf.Mesh.LoRaRegionPresetMap | undefined - >(undefined); - - return { - status, - isConfigured, - pendingSettingsChanges, - myNodeNum, - metadata, - myNodeInfo, - lockdownStatus, - regionPresets, - firmwareSupport, - }; -} - -export type DeviceStore = ReturnType; diff --git a/packages/sdk/src/features/files/FilesClient.ts b/packages/sdk/src/features/files/FilesClient.ts deleted file mode 100644 index 490d7b211..000000000 --- a/packages/sdk/src/features/files/FilesClient.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { Result } from "better-result"; -import type { MeshClient } from "../../core/client/MeshClient.ts"; -import { generatePacketId } from "../../core/identifiers/PacketId.ts"; -import type { ReadonlySignal } from "../../core/signals/createStore.ts"; -import type { FileTransfer } from "./domain/FileTransfer.ts"; -import { FilesStore } from "./state/filesStore.ts"; - -export class FilesClient { - private readonly client: MeshClient; - private readonly store: FilesStore; - public readonly transfers: ReadonlySignal>; - - constructor(client: MeshClient) { - this.client = client; - this.store = new FilesStore(); - this.transfers = this.store.read; - } - - public async upload( - filename: string, - data: Uint8Array, - ): Promise> { - const id = generatePacketId(); - const transfer: FileTransfer = { - id, - filename, - direction: "upload", - status: "in_progress", - size: data.length, - }; - this.store.set(id, transfer); - try { - await this.client.xModem.uploadFile(filename, data); - const done: FileTransfer = { ...transfer, status: "complete" }; - this.store.set(id, done); - return Result.ok(done); - } catch (e) { - const failed: FileTransfer = { ...transfer, status: "failed" }; - this.store.set(id, failed); - return Result.err(e instanceof Error ? e : new Error(String(e))); - } - } - - public async download( - filename: string, - ): Promise> { - const id = generatePacketId(); - const transfer: FileTransfer = { - id, - filename, - direction: "download", - status: "in_progress", - }; - this.store.set(id, transfer); - try { - await this.client.xModem.downloadFile(filename); - const done: FileTransfer = { ...transfer, status: "complete" }; - this.store.set(id, done); - return Result.ok(done); - } catch (e) { - const failed: FileTransfer = { ...transfer, status: "failed" }; - this.store.set(id, failed); - return Result.err(e instanceof Error ? e : new Error(String(e))); - } - } -} diff --git a/packages/sdk/src/features/files/domain/FileTransfer.ts b/packages/sdk/src/features/files/domain/FileTransfer.ts deleted file mode 100644 index 5fd19552a..000000000 --- a/packages/sdk/src/features/files/domain/FileTransfer.ts +++ /dev/null @@ -1,9 +0,0 @@ -export type TransferStatus = "pending" | "in_progress" | "complete" | "failed"; - -export interface FileTransfer { - readonly id: number; - readonly filename: string; - readonly direction: "upload" | "download"; - readonly status: TransferStatus; - readonly size?: number; -} diff --git a/packages/sdk/src/features/files/index.ts b/packages/sdk/src/features/files/index.ts deleted file mode 100644 index 01b1bb552..000000000 --- a/packages/sdk/src/features/files/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { FilesClient } from "./FilesClient.ts"; -export type { FileTransfer, TransferStatus } from "./domain/FileTransfer.ts"; diff --git a/packages/sdk/src/features/files/state/filesStore.ts b/packages/sdk/src/features/files/state/filesStore.ts deleted file mode 100644 index a916462a0..000000000 --- a/packages/sdk/src/features/files/state/filesStore.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { SignalMap } from "../../../core/signals/createStore.ts"; -import type { FileTransfer } from "../domain/FileTransfer.ts"; - -export class FilesStore extends SignalMap {} diff --git a/packages/sdk/src/features/nodes/NodesClient.errors.test.ts b/packages/sdk/src/features/nodes/NodesClient.errors.test.ts deleted file mode 100644 index 695ec4520..000000000 --- a/packages/sdk/src/features/nodes/NodesClient.errors.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { describe, expect, it } from "vitest"; -import { MeshClient } from "../../core/client/MeshClient.ts"; -import { createFakeTransport } from "../../core/testing/createFakeTransport.ts"; -import { ChannelNumber } from "../../core/types.ts"; - -const KEY_A = new Uint8Array([1, 2, 3, 4]); -const KEY_B = new Uint8Array([9, 8, 7, 6]); - -function nodeInfo(num: number, key?: Uint8Array, longName = `Node ${num}`) { - return create(Protobuf.Mesh.NodeInfoSchema, { - num, - user: create(Protobuf.Mesh.UserSchema, { - id: `!${num.toString(16)}`, - longName, - shortName: longName.slice(0, 4), - publicKey: key ?? new Uint8Array(), - }), - }); -} - -describe("NodesClient PKI error tracking", () => { - it("MISMATCH_PKI when an existing node re-presents with a different key", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - - client.events.onNodeInfoPacket.dispatch(nodeInfo(1, KEY_A, "First")); - expect(client.nodes.errorFor(1)).toBeUndefined(); - - client.events.onNodeInfoPacket.dispatch(nodeInfo(1, KEY_B, "Impostor")); - expect(client.nodes.errorFor(1)?.error).toBe("MISMATCH_PKI"); - // Original node is preserved. - expect(client.nodes.byNum(1)?.user?.longName).toBe("First"); - }); - - it("DUPLICATE_PKI when a new node claims another node's public key", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - - client.events.onNodeInfoPacket.dispatch(nodeInfo(1, KEY_A)); - client.events.onNodeInfoPacket.dispatch(nodeInfo(2, KEY_A)); - - expect(client.nodes.errorFor(2)?.error).toBe("DUPLICATE_PKI"); - // The duplicate is rejected — only the first node remains. - expect(client.nodes.list.value.map((n) => n.num)).toEqual([1]); - }); - - it("clears the error on a subsequent successful update", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - - // Seed with empty key so any incoming key is allowed. - client.events.onNodeInfoPacket.dispatch(nodeInfo(1)); - client.events.onNodeInfoPacket.dispatch(nodeInfo(1, KEY_A)); - // Trigger a routing-error error. - client.nodes.setError(1, Protobuf.Mesh.Routing_Error.PKI_UNKNOWN_PUBKEY); - expect(client.nodes.hasError(1)).toBe(true); - - // A clean refresh with the same key should clear the error. - client.events.onNodeInfoPacket.dispatch(nodeInfo(1, KEY_A)); - expect(client.nodes.hasError(1)).toBe(false); - }); - - it("records routing PKI errors against the originating node", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - - client.events.onRoutingPacket.dispatch({ - id: 1, - from: 99, - to: 0xffffffff, - channel: ChannelNumber.Primary, - type: "broadcast", - rxTime: new Date(), - data: create(Protobuf.Mesh.RoutingSchema, { - variant: { - case: "errorReason", - value: Protobuf.Mesh.Routing_Error.PKI_UNKNOWN_PUBKEY, - }, - }), - }); - - expect(client.nodes.errorFor(99)?.error).toBe( - Protobuf.Mesh.Routing_Error.PKI_UNKNOWN_PUBKEY, - ); - }); - - it("clearError / clearAllErrors", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - - client.nodes.setError(1, "MISMATCH_PKI"); - client.nodes.setError(2, "DUPLICATE_PKI"); - expect(client.nodes.errors.value.length).toBe(2); - - client.nodes.clearError(1); - expect(client.nodes.errors.value.length).toBe(1); - - client.nodes.clearAllErrors(); - expect(client.nodes.errors.value.length).toBe(0); - }); -}); diff --git a/packages/sdk/src/features/nodes/NodesClient.test.ts b/packages/sdk/src/features/nodes/NodesClient.test.ts deleted file mode 100644 index 7b7b41904..000000000 --- a/packages/sdk/src/features/nodes/NodesClient.test.ts +++ /dev/null @@ -1,149 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { describe, expect, it } from "vitest"; -import { MeshClient } from "../../core/client/MeshClient.ts"; -import { createFakeTransport } from "../../core/testing/createFakeTransport.ts"; -import { ChannelNumber } from "../../core/types.ts"; - -describe("NodesClient", () => { - it("populates the list signal from incoming NodeInfo packets", async () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - - expect(client.nodes.list.value).toEqual([]); - - client.events.onNodeInfoPacket.dispatch( - create(Protobuf.Mesh.NodeInfoSchema, { num: 1 }), - ); - client.events.onNodeInfoPacket.dispatch( - create(Protobuf.Mesh.NodeInfoSchema, { num: 2, isFavorite: true }), - ); - - expect(client.nodes.list.value.map((n) => n.num)).toEqual([1, 2]); - expect(client.nodes.byNum(2)?.isFavorite).toBe(true); - }); - - it("byNum returns undefined for unknown nodes", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - expect(client.nodes.byNum(999)).toBeUndefined(); - }); - - it("folds live device-metrics telemetry into the node", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - - client.events.onNodeInfoPacket.dispatch( - create(Protobuf.Mesh.NodeInfoSchema, { num: 100 }), - ); - client.events.onTelemetryPacket.dispatch({ - id: 1, - from: 100, - to: 0, - channel: ChannelNumber.Primary, - type: "broadcast", - rxTime: new Date(1000), - data: create(Protobuf.Telemetry.TelemetrySchema, { - variant: { - case: "deviceMetrics", - value: create(Protobuf.Telemetry.DeviceMetricsSchema, { - batteryLevel: 80, - voltage: 4.1, - }), - }, - }), - }); - - expect(client.nodes.byNum(100)?.deviceMetrics?.batteryLevel).toBe(80); - expect(client.nodes.byNum(100)?.deviceMetrics?.voltage).toBeCloseTo(4.1); - }); - - it("updates lastHeard only from packets that carry rx_time", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - client.events.onNodeInfoPacket.dispatch( - create(Protobuf.Mesh.NodeInfoSchema, { num: 5, lastHeard: 1_000 }), - ); - - // A replayed packet with no rx_time leaves lastHeard alone. - client.events.onMeshPacket.dispatch( - create(Protobuf.Mesh.MeshPacketSchema, { from: 5, id: 1 }), - ); - expect(client.nodes.byNum(5)?.lastHeard).toBe(1_000); - - client.events.onMeshPacket.dispatch( - create(Protobuf.Mesh.MeshPacketSchema, { from: 5, id: 2, rxTime: 2_000 }), - ); - expect(client.nodes.byNum(5)?.lastHeard).toBe(2_000); - }); - - function withFirmware(client: MeshClient, firmwareVersion: string) { - client.events.onDeviceMetadataPacket.dispatch({ - id: 0, - from: 0, - to: 0, - type: "direct", - channel: ChannelNumber.Primary, - rxTime: new Date(), - data: create(Protobuf.Mesh.DeviceMetadataSchema, { firmwareVersion }), - }); - } - - it("treats every node as heard on firmware older than 2.8.1", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - withFirmware(client, "2.7.15.abc"); - client.events.onNodeInfoPacket.dispatch( - create(Protobuf.Mesh.NodeInfoSchema, { num: 8 }), - ); - expect(client.nodes.byNum(8)?.heardOnCurrentLora).toBe(true); - }); - - it("reports unheard nodes on firmware 2.8.1", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - withFirmware(client, "2.8.1.8e6a88d"); - client.events.onNodeInfoPacket.dispatch( - create(Protobuf.Mesh.NodeInfoSchema, { num: 8 }), - ); - client.events.onNodeInfoPacket.dispatch( - create(Protobuf.Mesh.NodeInfoSchema, { - num: 9, - heardOnCurrentLora: true, - }), - ); - expect(client.nodes.byNum(8)?.heardOnCurrentLora).toBe(false); - expect(client.nodes.byNum(9)?.heardOnCurrentLora).toBe(true); - }); - - it("keeps a known position when a thin NodeInfo arrives", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - client.events.onNodeInfoPacket.dispatch( - create(Protobuf.Mesh.NodeInfoSchema, { - num: 3, - position: { latitudeI: 10, longitudeI: 20 }, - }), - ); - client.events.onNodeInfoPacket.dispatch( - create(Protobuf.Mesh.NodeInfoSchema, { num: 3, isFavorite: true }), - ); - expect(client.nodes.byNum(3)?.position?.latitudeI).toBe(10); - expect(client.nodes.byNum(3)?.isFavorite).toBe(true); - }); - - it("records a node's status message", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - client.events.onNodeStatusPacket.dispatch({ - id: 1, - from: 4, - to: 0xffffffff, - type: "broadcast", - channel: ChannelNumber.Primary, - rxTime: new Date(), - data: create(Protobuf.Mesh.StatusMessageSchema, { status: "at camp" }), - }); - expect(client.nodes.byNum(4)?.status).toBe("at camp"); - }); -}); diff --git a/packages/sdk/src/features/nodes/NodesClient.ts b/packages/sdk/src/features/nodes/NodesClient.ts deleted file mode 100644 index 52279b49e..000000000 --- a/packages/sdk/src/features/nodes/NodesClient.ts +++ /dev/null @@ -1,288 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import type { Result } from "better-result"; -import type { MeshClient } from "../../core/client/MeshClient.ts"; -import type { ReadonlySignal } from "../../core/signals/createStore.ts"; -import type { Node } from "./domain/Node.ts"; -import type { NodeError, NodeErrorType } from "./domain/NodeError.ts"; -import type { NodesRepository } from "./domain/NodesRepository.ts"; -import { firmwareAtLeast } from "../device/domain/FirmwareVersion.ts"; -import { NodeMapper } from "./infrastructure/NodeMapper.ts"; -import { InMemoryNodesRepository } from "./infrastructure/repositories/InMemoryNodesRepository.ts"; -import { validateIncomingNode } from "./infrastructure/nodeValidation.ts"; -import { NodeErrorsStore } from "./state/nodeErrorsStore.ts"; -import { NodesStore } from "./state/nodesStore.ts"; -import { - favoriteNode, - removeFavoriteNode, -} from "./application/FavoriteNodeUseCase.ts"; -import { - ignoreNode, - removeIgnoredNode, -} from "./application/IgnoreNodeUseCase.ts"; -import { - removeNodeByNum, - resetNodes, -} from "./application/RemoveNodeUseCase.ts"; - -export interface NodesClientOptions { - repository?: NodesRepository; -} - -/** - * Per-client view of the device's node DB plus client-side validation / - * error tracking. Persists snapshots through the configured - * `NodesRepository`; rehydrates on construction. - */ -export class NodesClient { - private readonly client: MeshClient; - private readonly store: NodesStore; - private readonly errorsStore: NodeErrorsStore; - private readonly repository: NodesRepository; - private hydrated = false; - /** Bumped on every storage rescope; see `ChatClient`. */ - private epoch = 0; - - public readonly list: ReadonlySignal>; - public readonly errors: ReadonlySignal>; - - constructor(client: MeshClient, options: NodesClientOptions = {}) { - this.client = client; - this.store = new NodesStore(); - this.errorsStore = new NodeErrorsStore(); - this.repository = options.repository ?? new InMemoryNodesRepository(); - this.list = this.store.read; - this.errors = this.errorsStore.read; - - client.events.onNodeInfoPacket.subscribe((info) => - this.handleIncoming(info), - ); - - client.events.onUserPacket.subscribe((packet) => { - this.patch(packet.from, { user: packet.data }); - }); - - client.events.onPositionPacket.subscribe((packet) => { - this.patch(packet.from, { position: packet.data }); - }); - - client.events.onTelemetryPacket.subscribe((packet) => { - // Fold live device-metrics telemetry into the node so battery / channel - // utilisation / voltage stay current between NodeInfo broadcasts. - if (packet.data.variant.case === "deviceMetrics") { - this.patch(packet.from, { deviceMetrics: packet.data.variant.value }); - } - }); - - client.events.onNodeStatusPacket.subscribe((packet) => { - this.patch(packet.from, { status: packet.data.status }); - }); - - client.events.onMeshPacket.subscribe((packet) => { - // Every inbound mesh packet refreshes lastHeard / snr for the - // originating node. Since firmware 2.8 the device also replays each - // node's cached position and telemetry after the handshake, with - // rx_time set to when it last heard the node, or unset when it had no - // wall-clock time then. A packet without rx_time says nothing about - // when the node was heard, so it must not mark the node as heard now. - if (!packet.rxTime) return; - this.patch(packet.from, { - lastHeard: packet.rxTime, - snr: packet.rxSnr, - }); - }); - - client.events.onRoutingPacket.subscribe((packet) => { - if (packet.data.variant.case !== "errorReason") return; - const reason = packet.data.variant.value; - if (reason === Protobuf.Mesh.Routing_Error.NONE) return; - if ( - reason === Protobuf.Mesh.Routing_Error.PKI_UNKNOWN_PUBKEY || - reason === Protobuf.Mesh.Routing_Error.PKI_FAILED || - reason === Protobuf.Mesh.Routing_Error.PKI_SEND_FAIL_PUBLIC_KEY || - reason === Protobuf.Mesh.Routing_Error.NO_CHANNEL - ) { - this.setError(packet.from, reason); - } - }); - - void this.hydrate(); - } - - private handleIncoming(info: Protobuf.Mesh.NodeInfo): void { - const snapshot = new Map(); - for (const node of this.list.value) snapshot.set(node.num, node); - - const verdict = validateIncomingNode(info, snapshot); - if (verdict.error) { - this.setError(info.num, verdict.error); - } - if (!verdict.accepted) return; - - const existing = this.store.get(info.num); - const mapped = NodeMapper.fromProto(verdict.accepted); - const node: Node = { - ...mapped, - // Firmware 2.8 sends NodeInfo without position or metrics and replays - // those separately, so keep what we already know. - position: mapped.position ?? existing?.position, - deviceMetrics: mapped.deviceMetrics ?? existing?.deviceMetrics, - status: existing?.status, - heardOnCurrentLora: - mapped.heardOnCurrentLora || !this.firmwareReportsHeard(), - }; - this.store.set(node.num, node); - if (this.errorsStore.has(node.num)) this.errorsStore.delete(node.num); - void this.repository.upsert(node).catch(() => {}); - } - - /** heard_on_current_lora exists from firmware 2.8.1. */ - private firmwareReportsHeard(): boolean { - const version = this.client.device.metadata.value?.firmwareVersion; - return !!version && firmwareAtLeast(version, "2.8.1"); - } - - /** - * Shallow-merges a partial Node update over the existing entry. Creates a - * stub Node if none exists yet — matches the legacy nodeDB behaviour - * where a stray UserPacket / PositionPacket / mesh packet would seed a - * placeholder NodeInfo. - */ - private patch(nodeNum: number, partial: Partial): void { - if (nodeNum === 0) return; - const existing = this.store.get(nodeNum); - const next: Node = existing - ? { ...existing, ...partial } - : { - num: nodeNum, - isFavorite: false, - isIgnored: false, - ...partial, - }; - this.store.set(nodeNum, next); - void this.repository.upsert(next).catch(() => {}); - } - - private async hydrate(): Promise { - if (this.hydrated) return; - this.hydrated = true; - const epoch = this.epoch; - try { - const persisted = await this.repository.loadAll(); - if (epoch !== this.epoch) return; - for (const node of persisted) { - if (!this.store.has(node.num)) this.store.set(node.num, node); - } - } catch { - // ok — adapter may not have history yet - } - } - - /** - * Points the repository at another storage scope and reloads the node list - * from it. Nodes and errors held for the old scope are dropped; nodes the - * device reports from now on win over stored ones. - */ - public rescope(scope: number): void { - this.repository.setScope?.(scope); - this.epoch++; - this.store.clear(); - this.errorsStore.clear(); - this.hydrated = false; - void this.hydrate(); - } - - public byNum(nodeNum: number): Node | undefined { - return this.store.get(nodeNum); - } - - public errorFor(nodeNum: number): NodeError | undefined { - return this.errorsStore.get(nodeNum); - } - - public hasError(nodeNum: number): boolean { - return this.errorsStore.has(nodeNum); - } - - public setError(nodeNum: number, error: NodeErrorType): void { - this.errorsStore.set(nodeNum, { node: nodeNum, error }); - } - - public clearError(nodeNum: number): void { - this.errorsStore.delete(nodeNum); - } - - public clearAllErrors(): void { - this.errorsStore.clear(); - } - - public async favorite(nodeNum: number): Promise> { - const result = await favoriteNode(this.client, nodeNum); - if (result.status === "ok") this.patch(nodeNum, { isFavorite: true }); - return result; - } - - public async unfavorite(nodeNum: number): Promise> { - const result = await removeFavoriteNode(this.client, nodeNum); - if (result.status === "ok") this.patch(nodeNum, { isFavorite: false }); - return result; - } - - public async ignore(nodeNum: number): Promise> { - const result = await ignoreNode(this.client, nodeNum); - if (result.status === "ok") this.patch(nodeNum, { isIgnored: true }); - return result; - } - - public async unignore(nodeNum: number): Promise> { - const result = await removeIgnoredNode(this.client, nodeNum); - if (result.status === "ok") this.patch(nodeNum, { isIgnored: false }); - return result; - } - - public remove(nodeNum: number): Promise> { - void this.repository.remove(nodeNum).catch(() => {}); - this.store.delete(nodeNum); - this.errorsStore.delete(nodeNum); - return removeNodeByNum(this.client, nodeNum); - } - - /** - * Wipes every node except (optionally) the local "my node" entry, then - * sends the device-side reset admin message. Mirrors the legacy - * removeAllNodes(true) + resetNodes flow that the ResetNodeDb dialog - * relied on. - */ - public async reset( - options: { keepMyNode?: boolean } = {}, - ): Promise> { - const myNodeNum = this.client.device.myNodeNum.value; - if (options.keepMyNode && myNodeNum !== undefined) { - const me = this.store.get(myNodeNum); - this.store.clear(); - this.errorsStore.clear(); - if (me) this.store.set(myNodeNum, me); - try { - await this.repository.clear(); - if (me) await this.repository.upsert(me); - } catch { - // ok - } - } else { - this.store.clear(); - this.errorsStore.clear(); - try { - await this.repository.clear(); - } catch { - // ok - } - } - return resetNodes(this.client); - } - - /** Drives the legacy `Protobuf.Mesh.NodeInfoSchema` create flow if a - * consumer needs a placeholder for a not-yet-known node. */ - public createPlaceholder(nodeNum: number): Protobuf.Mesh.NodeInfo { - return create(Protobuf.Mesh.NodeInfoSchema, { num: nodeNum }); - } -} diff --git a/packages/sdk/src/features/nodes/application/FavoriteNodeUseCase.ts b/packages/sdk/src/features/nodes/application/FavoriteNodeUseCase.ts deleted file mode 100644 index 271c92272..000000000 --- a/packages/sdk/src/features/nodes/application/FavoriteNodeUseCase.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { Result } from "better-result"; -import type { MeshClient } from "../../../core/client/MeshClient.ts"; -import { sendAdminMessage } from "../../device/infrastructure/AdminMessageSender.ts"; - -export async function favoriteNode( - client: MeshClient, - nodeNum: number, -): Promise> { - try { - const id = await sendAdminMessage(client, { - case: "setFavoriteNode", - value: nodeNum, - }); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} - -export async function removeFavoriteNode( - client: MeshClient, - nodeNum: number, -): Promise> { - try { - const id = await sendAdminMessage(client, { - case: "removeFavoriteNode", - value: nodeNum, - }); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} diff --git a/packages/sdk/src/features/nodes/application/IgnoreNodeUseCase.ts b/packages/sdk/src/features/nodes/application/IgnoreNodeUseCase.ts deleted file mode 100644 index f809cd73b..000000000 --- a/packages/sdk/src/features/nodes/application/IgnoreNodeUseCase.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { Result } from "better-result"; -import type { MeshClient } from "../../../core/client/MeshClient.ts"; -import { sendAdminMessage } from "../../device/infrastructure/AdminMessageSender.ts"; - -export async function ignoreNode( - client: MeshClient, - nodeNum: number, -): Promise> { - try { - const id = await sendAdminMessage(client, { - case: "setIgnoredNode", - value: nodeNum, - }); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} - -export async function removeIgnoredNode( - client: MeshClient, - nodeNum: number, -): Promise> { - try { - const id = await sendAdminMessage(client, { - case: "removeIgnoredNode", - value: nodeNum, - }); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} diff --git a/packages/sdk/src/features/nodes/application/RemoveNodeUseCase.ts b/packages/sdk/src/features/nodes/application/RemoveNodeUseCase.ts deleted file mode 100644 index cb7d300de..000000000 --- a/packages/sdk/src/features/nodes/application/RemoveNodeUseCase.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { Result } from "better-result"; -import type { MeshClient } from "../../../core/client/MeshClient.ts"; -import { sendAdminMessage } from "../../device/infrastructure/AdminMessageSender.ts"; - -export async function removeNodeByNum( - client: MeshClient, - nodeNum: number, -): Promise> { - try { - const id = await sendAdminMessage(client, { - case: "removeByNodenum", - value: nodeNum, - }); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} - -export async function resetNodes( - client: MeshClient, -): Promise> { - try { - const id = await sendAdminMessage(client, { - case: "nodedbReset", - value: true, - }); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} diff --git a/packages/sdk/src/features/nodes/application/SetOwnerUseCase.ts b/packages/sdk/src/features/nodes/application/SetOwnerUseCase.ts deleted file mode 100644 index 79e051d57..000000000 --- a/packages/sdk/src/features/nodes/application/SetOwnerUseCase.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; -import { Result } from "better-result"; -import type { MeshClient } from "../../../core/client/MeshClient.ts"; -import { sendAdminMessage } from "../../device/infrastructure/AdminMessageSender.ts"; - -export async function setOwner( - client: MeshClient, - owner: Protobuf.Mesh.User, -): Promise> { - try { - const id = await sendAdminMessage(client, { - case: "setOwner", - value: owner, - }); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} diff --git a/packages/sdk/src/features/nodes/domain/Node.ts b/packages/sdk/src/features/nodes/domain/Node.ts deleted file mode 100644 index c89a14122..000000000 --- a/packages/sdk/src/features/nodes/domain/Node.ts +++ /dev/null @@ -1,34 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; - -export interface Node { - readonly num: number; - readonly user?: Protobuf.Mesh.User; - readonly position?: Protobuf.Mesh.Position; - readonly deviceMetrics?: Protobuf.Telemetry.DeviceMetrics; - readonly lastHeard?: number; - readonly snr?: number; - readonly channel?: number; - readonly viaMqtt?: boolean; - readonly hopsAway?: number; - readonly isFavorite: boolean; - readonly isIgnored: boolean; - readonly isKeyManuallyVerified?: boolean; - readonly isMuted?: boolean; - /** The node signs its packets with XEdDSA (firmware 2.8+). */ - readonly hasXeddsaSigned?: boolean; - /** - * Heard over LoRa since the radio's current LoRa settings took effect. - * Firmware older than 2.8.1 doesn't report it, so every node counts as - * heard there. See {@link isUnheardOnCurrentLora}. - */ - readonly heardOnCurrentLora?: boolean; - /** Latest status message the node broadcast (NODE_STATUS_APP). */ - readonly status?: string; -} - -/** - * True for a node the radio hasn't heard on its current LoRa settings. - * Nodes seen only over MQTT are never "unheard": LoRa settings don't apply. - */ -export const isUnheardOnCurrentLora = (node: Node): boolean => - node.heardOnCurrentLora === false && !node.viaMqtt; diff --git a/packages/sdk/src/features/nodes/domain/NodeError.ts b/packages/sdk/src/features/nodes/domain/NodeError.ts deleted file mode 100644 index 8bb18f9b6..000000000 --- a/packages/sdk/src/features/nodes/domain/NodeError.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; - -/** - * Reasons a node may be flagged as untrusted or unreachable. The two - * client-only kinds (`MISMATCH_PKI`, `DUPLICATE_PKI`) are produced by the - * `nodeValidation` mapper when an incoming `NodeInfo` collides with the - * stored public-key history. Routing errors come straight off the wire - * via `Routing_Error`. - */ -export type NodeErrorType = - | Protobuf.Mesh.Routing_Error - | "MISMATCH_PKI" - | "DUPLICATE_PKI"; - -export interface NodeError { - readonly node: number; - readonly error: NodeErrorType; -} diff --git a/packages/sdk/src/features/nodes/domain/NodesRepository.ts b/packages/sdk/src/features/nodes/domain/NodesRepository.ts deleted file mode 100644 index b5beef36f..000000000 --- a/packages/sdk/src/features/nodes/domain/NodesRepository.ts +++ /dev/null @@ -1,23 +0,0 @@ -import type { Node } from "./Node.ts"; - -/** - * Persists the device's view of the mesh node DB. - * - * Snapshot semantics: each `upsert` overwrites the previous row for that - * node number. Implementations can keep additional history (e.g. a - * lastHeard timestamp series) but must always return the most recent - * snapshot from `loadAll` and `get`. - */ -export interface NodesRepository { - loadAll(): Promise; - get(nodeNum: number): Promise; - upsert(node: Node): Promise; - upsertBatch(nodes: ReadonlyArray): Promise; - remove(nodeNum: number): Promise; - clear(): Promise; - /** - * Points every later read and write at another storage scope. See - * `MessageRepository.setScope`. - */ - setScope?(scope: number): void; -} diff --git a/packages/sdk/src/features/nodes/index.ts b/packages/sdk/src/features/nodes/index.ts deleted file mode 100644 index 49dc4b478..000000000 --- a/packages/sdk/src/features/nodes/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -export { NodesClient } from "./NodesClient.ts"; -export type { NodesClientOptions } from "./NodesClient.ts"; -export type { Node } from "./domain/Node.ts"; -export { isUnheardOnCurrentLora } from "./domain/Node.ts"; -export type { NodeError, NodeErrorType } from "./domain/NodeError.ts"; -export type { NodesRepository } from "./domain/NodesRepository.ts"; -export { NodeMapper } from "./infrastructure/NodeMapper.ts"; -export { - equalKey, - validateIncomingNode, -} from "./infrastructure/nodeValidation.ts"; -export { InMemoryNodesRepository } from "./infrastructure/repositories/InMemoryNodesRepository.ts"; diff --git a/packages/sdk/src/features/nodes/infrastructure/NodeMapper.test.ts b/packages/sdk/src/features/nodes/infrastructure/NodeMapper.test.ts deleted file mode 100644 index 1749910f4..000000000 --- a/packages/sdk/src/features/nodes/infrastructure/NodeMapper.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { describe, expect, it } from "vitest"; -import { NodeMapper } from "./NodeMapper.ts"; - -describe("NodeMapper", () => { - it("projects NodeInfo onto the Node domain shape", () => { - const proto = create(Protobuf.Mesh.NodeInfoSchema, { - num: 0xdeadbeef, - lastHeard: 1700000000, - snr: 7, - isFavorite: true, - isIgnored: false, - }); - const node = NodeMapper.fromProto(proto); - expect(node.num).toBe(0xdeadbeef); - expect(node.lastHeard).toBe(1700000000); - expect(node.snr).toBe(7); - expect(node.isFavorite).toBe(true); - expect(node.isIgnored).toBe(false); - expect(node.user).toBeUndefined(); - }); -}); diff --git a/packages/sdk/src/features/nodes/infrastructure/NodeMapper.ts b/packages/sdk/src/features/nodes/infrastructure/NodeMapper.ts deleted file mode 100644 index b4dc1c0e7..000000000 --- a/packages/sdk/src/features/nodes/infrastructure/NodeMapper.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; -import type { Node } from "../domain/Node.ts"; - -export const NodeMapper = { - fromProto(info: Protobuf.Mesh.NodeInfo): Node { - return { - num: info.num, - user: info.user, - position: info.position, - deviceMetrics: info.deviceMetrics, - lastHeard: info.lastHeard, - snr: info.snr, - channel: info.channel, - viaMqtt: info.viaMqtt, - hopsAway: info.hopsAway, - isFavorite: info.isFavorite, - isIgnored: info.isIgnored, - isKeyManuallyVerified: info.isKeyManuallyVerified, - isMuted: info.isMuted, - hasXeddsaSigned: info.hasXeddsaSigned, - heardOnCurrentLora: info.heardOnCurrentLora, - }; - }, -}; diff --git a/packages/sdk/src/features/nodes/infrastructure/nodeValidation.ts b/packages/sdk/src/features/nodes/infrastructure/nodeValidation.ts deleted file mode 100644 index 5bc50d942..000000000 --- a/packages/sdk/src/features/nodes/infrastructure/nodeValidation.ts +++ /dev/null @@ -1,74 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; -import type { Node } from "../domain/Node.ts"; -import type { NodeErrorType } from "../domain/NodeError.ts"; - -/** - * Byte-equal compare for two public keys. Empty / undefined keys never - * match each other. - */ -export function equalKey( - a?: Uint8Array | null, - b?: Uint8Array | null, -): boolean { - if (!a || !b) return false; - if (a === b) return true; - if (a.byteLength !== b.byteLength) return false; - for (let i = 0; i < a.byteLength; i++) { - if (a[i] !== b[i]) return false; - } - return true; -} - -export interface ValidatedNodeInfo { - /** The NodeInfo to commit to the store. `undefined` when the incoming node should be dropped entirely. */ - readonly accepted: Protobuf.Mesh.NodeInfo | undefined; - /** Optional error to record against the incoming node's number. */ - readonly error: NodeErrorType | undefined; -} - -/** - * Validates an incoming NodeInfo against the existing snapshot of nodes. - * Pure — no side effects. Caller decides what to do with the verdict. - * - * Mirrors the previous web-side validation in - * `packages/web/src/core/stores/nodeDBStore/nodeValidation.ts` but returns - * the verdict instead of pushing into a Zustand store. - */ -export function validateIncomingNode( - newNode: Protobuf.Mesh.NodeInfo, - existingByNum: ReadonlyMap, -): ValidatedNodeInfo { - const num = newNode.num; - const existing = existingByNum.get(num); - const newKey = newNode.user?.publicKey; - - if (!existing) { - if (newKey && newKey.length > 0) { - // Reject if another node already presents this public key — - // potential impersonation. - for (const node of existingByNum.values()) { - const otherKey = node.user?.publicKey; - if (otherKey && otherKey.length > 0 && equalKey(otherKey, newKey)) { - return { accepted: undefined, error: "DUPLICATE_PKI" }; - } - } - } - return { accepted: newNode, error: undefined }; - } - - const oldKey = existing.user?.publicKey; - const oldKeyEmpty = !oldKey || oldKey.length === 0; - - if (oldKeyEmpty || equalKey(oldKey, newKey)) { - // Trust the incoming update. - return { accepted: newNode, error: undefined }; - } - - if (newKey && newKey.length > 0) { - // Existing node has a key, incoming has a different key — mismatch. - return { accepted: undefined, error: "MISMATCH_PKI" }; - } - - // Incoming has no key, existing does — silently drop the update. - return { accepted: undefined, error: undefined }; -} diff --git a/packages/sdk/src/features/nodes/infrastructure/repositories/InMemoryNodesRepository.ts b/packages/sdk/src/features/nodes/infrastructure/repositories/InMemoryNodesRepository.ts deleted file mode 100644 index 88e02e55a..000000000 --- a/packages/sdk/src/features/nodes/infrastructure/repositories/InMemoryNodesRepository.ts +++ /dev/null @@ -1,33 +0,0 @@ -import type { Node } from "../../domain/Node.ts"; -import type { NodesRepository } from "../../domain/NodesRepository.ts"; - -/** - * Default in-memory NodesRepository — no persistence across reloads. - */ -export class InMemoryNodesRepository implements NodesRepository { - private readonly map = new Map(); - - async loadAll(): Promise { - return Array.from(this.map.values()); - } - - async get(nodeNum: number): Promise { - return this.map.get(nodeNum); - } - - async upsert(node: Node): Promise { - this.map.set(node.num, node); - } - - async upsertBatch(nodes: ReadonlyArray): Promise { - for (const node of nodes) this.map.set(node.num, node); - } - - async remove(nodeNum: number): Promise { - this.map.delete(nodeNum); - } - - async clear(): Promise { - this.map.clear(); - } -} diff --git a/packages/sdk/src/features/nodes/state/nodeErrorsStore.ts b/packages/sdk/src/features/nodes/state/nodeErrorsStore.ts deleted file mode 100644 index 19e0f1214..000000000 --- a/packages/sdk/src/features/nodes/state/nodeErrorsStore.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { SignalMap } from "../../../core/signals/createStore.ts"; -import type { NodeError } from "../domain/NodeError.ts"; - -export class NodeErrorsStore extends SignalMap {} diff --git a/packages/sdk/src/features/nodes/state/nodesStore.ts b/packages/sdk/src/features/nodes/state/nodesStore.ts deleted file mode 100644 index 85df839e3..000000000 --- a/packages/sdk/src/features/nodes/state/nodesStore.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { SignalMap } from "../../../core/signals/createStore.ts"; -import type { Node } from "../domain/Node.ts"; - -export class NodesStore extends SignalMap {} diff --git a/packages/sdk/src/features/position/PositionClient.test.ts b/packages/sdk/src/features/position/PositionClient.test.ts deleted file mode 100644 index 2ac7b15f6..000000000 --- a/packages/sdk/src/features/position/PositionClient.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { describe, expect, it } from "vitest"; -import { MeshClient } from "../../core/client/MeshClient.ts"; -import { createFakeTransport } from "../../core/testing/createFakeTransport.ts"; -import { ChannelNumber } from "../../core/types.ts"; - -describe("PositionClient", () => { - it("tracks per-node positions from packets", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - - client.events.onPositionPacket.dispatch({ - id: 1, - from: 5, - to: 5, - channel: ChannelNumber.Primary, - type: "direct", - rxTime: new Date(1000), - data: create(Protobuf.Mesh.PositionSchema, { - latitudeI: 477500000, - longitudeI: -1224400000, - }), - }); - - expect(client.position.byNode(5)?.latitudeI).toBe(477500000); - expect(client.position.byNode(99)).toBeUndefined(); - expect(client.position.list.value.length).toBe(1); - }); -}); diff --git a/packages/sdk/src/features/position/PositionClient.ts b/packages/sdk/src/features/position/PositionClient.ts deleted file mode 100644 index 239355660..000000000 --- a/packages/sdk/src/features/position/PositionClient.ts +++ /dev/null @@ -1,52 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; -import type { Result } from "better-result"; -import type { MeshClient } from "../../core/client/MeshClient.ts"; -import type { ReadonlySignal } from "../../core/signals/createStore.ts"; -import type { Position } from "./domain/Position.ts"; -import { PositionMapper } from "./infrastructure/PositionMapper.ts"; -import { - removeFixedPosition, - requestPosition, - setFixedPosition, - setPosition, -} from "./application/PositionUseCases.ts"; -import { PositionStore } from "./state/positionStore.ts"; - -export class PositionClient { - private readonly client: MeshClient; - private readonly store: PositionStore; - public readonly list: ReadonlySignal>; - - constructor(client: MeshClient) { - this.client = client; - this.store = new PositionStore(); - this.list = this.store.read; - - client.events.onPositionPacket.subscribe((packet) => { - this.store.set(packet.from, PositionMapper.fromPacket(packet)); - }); - } - - public byNode(nodeNum: number): Position | undefined { - return this.store.get(nodeNum); - } - - public setFixed( - latitude: number, - longitude: number, - ): Promise> { - return setFixedPosition(this.client, latitude, longitude); - } - - public removeFixed(): Promise> { - return removeFixedPosition(this.client); - } - - public set(position: Protobuf.Mesh.Position): Promise> { - return setPosition(this.client, position); - } - - public request(destination: number): Promise> { - return requestPosition(this.client, destination); - } -} diff --git a/packages/sdk/src/features/position/application/PositionUseCases.ts b/packages/sdk/src/features/position/application/PositionUseCases.ts deleted file mode 100644 index a09aec520..000000000 --- a/packages/sdk/src/features/position/application/PositionUseCases.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { create, toBinary } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { Result } from "better-result"; -import type { MeshClient } from "../../../core/client/MeshClient.ts"; -import { sendAdminMessage } from "../../device/infrastructure/AdminMessageSender.ts"; - -export async function setFixedPosition( - client: MeshClient, - latitude: number, - longitude: number, -): Promise> { - try { - const position = create(Protobuf.Mesh.PositionSchema, { - latitudeI: Math.floor(latitude / 1e-7), - longitudeI: Math.floor(longitude / 1e-7), - }); - const id = await sendAdminMessage( - client, - { case: "setFixedPosition", value: position }, - "self", - undefined, - true, - false, - ); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} - -export async function removeFixedPosition( - client: MeshClient, -): Promise> { - try { - const id = await sendAdminMessage( - client, - { case: "removeFixedPosition", value: true }, - "self", - undefined, - true, - false, - ); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} - -export async function setPosition( - client: MeshClient, - position: Protobuf.Mesh.Position, -): Promise> { - try { - const id = await client.sendPacket( - toBinary(Protobuf.Mesh.PositionSchema, position), - Protobuf.Portnums.PortNum.POSITION_APP, - "self", - ); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} - -export async function requestPosition( - client: MeshClient, - destination: number, -): Promise> { - try { - const id = await client.sendPacket( - new Uint8Array(), - Protobuf.Portnums.PortNum.POSITION_APP, - destination, - ); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} diff --git a/packages/sdk/src/features/position/domain/Position.ts b/packages/sdk/src/features/position/domain/Position.ts deleted file mode 100644 index 2e1cfbd13..000000000 --- a/packages/sdk/src/features/position/domain/Position.ts +++ /dev/null @@ -1,7 +0,0 @@ -export interface Position { - readonly nodeNum: number; - readonly latitudeI?: number; - readonly longitudeI?: number; - readonly altitude?: number; - readonly time?: Date; -} diff --git a/packages/sdk/src/features/position/index.ts b/packages/sdk/src/features/position/index.ts deleted file mode 100644 index 9e1c55ddb..000000000 --- a/packages/sdk/src/features/position/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export { PositionClient } from "./PositionClient.ts"; -export type { Position } from "./domain/Position.ts"; -export { PositionMapper } from "./infrastructure/PositionMapper.ts"; diff --git a/packages/sdk/src/features/position/infrastructure/PositionMapper.ts b/packages/sdk/src/features/position/infrastructure/PositionMapper.ts deleted file mode 100644 index 21d25e0d5..000000000 --- a/packages/sdk/src/features/position/infrastructure/PositionMapper.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { PacketMetadata } from "../../../core/types.ts"; -import type * as Protobuf from "@meshtastic/protobufs"; -import type { Position } from "../domain/Position.ts"; - -export const PositionMapper = { - fromPacket(packet: PacketMetadata): Position { - return { - nodeNum: packet.from, - latitudeI: packet.data.latitudeI, - longitudeI: packet.data.longitudeI, - altitude: packet.data.altitude, - time: packet.rxTime, - }; - }, -}; diff --git a/packages/sdk/src/features/position/state/positionStore.ts b/packages/sdk/src/features/position/state/positionStore.ts deleted file mode 100644 index 534c30ac4..000000000 --- a/packages/sdk/src/features/position/state/positionStore.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { SignalMap } from "../../../core/signals/createStore.ts"; -import type { Position } from "../domain/Position.ts"; - -export class PositionStore extends SignalMap {} diff --git a/packages/sdk/src/features/telemetry/TelemetryClient.persistence.test.ts b/packages/sdk/src/features/telemetry/TelemetryClient.persistence.test.ts deleted file mode 100644 index 229973015..000000000 --- a/packages/sdk/src/features/telemetry/TelemetryClient.persistence.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { create, isMessage } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { describe, expect, it } from "vitest"; -import { MeshClient } from "../../core/client/MeshClient.ts"; -import { createFakeTransport } from "../../core/testing/createFakeTransport.ts"; -import { ChannelNumber } from "../../core/types.ts"; -import { InMemoryTelemetryRepository } from "./infrastructure/repositories/InMemoryTelemetryRepository.ts"; - -const dispatch = ( - client: MeshClient, - from: number, - ms: number, - battery = 80, -): void => { - client.events.onTelemetryPacket.dispatch({ - id: ms, - from, - to: 0, - channel: ChannelNumber.Primary, - type: "broadcast", - rxTime: new Date(ms), - data: create(Protobuf.Telemetry.TelemetrySchema, { - time: ms, - variant: { - case: "deviceMetrics", - value: create(Protobuf.Telemetry.DeviceMetricsSchema, { - batteryLevel: battery, - }), - }, - }), - }); -}; - -const flush = (): Promise => new Promise((r) => setTimeout(r, 0)); - -describe("TelemetryClient persistence", () => { - it("appends each incoming packet to the repository", async () => { - const repository = new InMemoryTelemetryRepository(); - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport, telemetry: { repository } }); - - dispatch(client, 100, 1000); - dispatch(client, 100, 2000); - await flush(); - - const persisted = await repository.loadRecent(100, 10); - expect(persisted).toHaveLength(2); - }); - - it("hydrates the in-memory store on first history()/latest() subscription", async () => { - const repository = new InMemoryTelemetryRepository(); - await repository.append({ - nodeNum: 200, - time: new Date(500), - kind: "deviceMetrics", - value: create(Protobuf.Telemetry.DeviceMetricsSchema, { - batteryLevel: 60, - }), - }); - - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport, telemetry: { repository } }); - - const sig = client.telemetry.history(200); - await flush(); - - expect(sig.value).toHaveLength(1); - const reading = sig.value[0]?.value; - expect(isMessage(reading, Protobuf.Telemetry.DeviceMetricsSchema)).toBe( - true, - ); - if (!isMessage(reading, Protobuf.Telemetry.DeviceMetricsSchema)) return; - expect(reading.batteryLevel).toBe(60); - }); - - it("retention prune trims the repository to maxPerNode", async () => { - const repository = new InMemoryTelemetryRepository(); - const { transport } = createFakeTransport(); - const client = new MeshClient({ - transport, - telemetry: { repository, retention: { maxPerNode: 3 } }, - }); - - for (let i = 0; i < 10; i++) { - dispatch(client, 300, (i + 1) * 1000); - } - await flush(); - - const persisted = await repository.loadRecent(300, 100); - expect(persisted).toHaveLength(3); - }); -}); diff --git a/packages/sdk/src/features/telemetry/TelemetryClient.test.ts b/packages/sdk/src/features/telemetry/TelemetryClient.test.ts deleted file mode 100644 index 981571417..000000000 --- a/packages/sdk/src/features/telemetry/TelemetryClient.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { describe, expect, it } from "vitest"; -import { MeshClient } from "../../core/client/MeshClient.ts"; -import { createFakeTransport } from "../../core/testing/createFakeTransport.ts"; -import { ChannelNumber } from "../../core/types.ts"; - -describe("TelemetryClient", () => { - it("captures latest reading per node and grows history", () => { - const { transport } = createFakeTransport(); - const client = new MeshClient({ transport }); - - client.events.onTelemetryPacket.dispatch({ - id: 1, - from: 100, - to: 0, - channel: ChannelNumber.Primary, - type: "broadcast", - rxTime: new Date(1000), - data: create(Protobuf.Telemetry.TelemetrySchema, { - time: 1000, - variant: { - case: "deviceMetrics", - value: create(Protobuf.Telemetry.DeviceMetricsSchema, { - batteryLevel: 80, - }), - }, - }), - }); - client.events.onTelemetryPacket.dispatch({ - id: 2, - from: 100, - to: 0, - channel: ChannelNumber.Primary, - type: "broadcast", - rxTime: new Date(2000), - data: create(Protobuf.Telemetry.TelemetrySchema, { - time: 2000, - variant: { - case: "deviceMetrics", - value: create(Protobuf.Telemetry.DeviceMetricsSchema, { - batteryLevel: 70, - }), - }, - }), - }); - - expect(client.telemetry.latest(100).value?.kind).toBe("deviceMetrics"); - expect(client.telemetry.history(100).value.length).toBe(2); - expect(client.telemetry.latest(999).value).toBeUndefined(); - }); -}); diff --git a/packages/sdk/src/features/telemetry/TelemetryClient.ts b/packages/sdk/src/features/telemetry/TelemetryClient.ts deleted file mode 100644 index 3f7ee660a..000000000 --- a/packages/sdk/src/features/telemetry/TelemetryClient.ts +++ /dev/null @@ -1,105 +0,0 @@ -import type { MeshClient } from "../../core/client/MeshClient.ts"; -import type { ReadonlySignal } from "../../core/signals/createStore.ts"; -import type { TelemetryReading } from "./domain/TelemetryReading.ts"; -import type { - TelemetryRepository, - TelemetryRetentionPolicy, -} from "./domain/TelemetryRepository.ts"; -import { InMemoryTelemetryRepository } from "./infrastructure/repositories/InMemoryTelemetryRepository.ts"; -import { TelemetryMapper } from "./infrastructure/TelemetryMapper.ts"; -import { TelemetryStore } from "./state/telemetryStore.ts"; - -export interface TelemetryClientOptions { - repository?: TelemetryRepository; - retention?: TelemetryRetentionPolicy; -} - -const HYDRATE_LIMIT = 256; - -export class TelemetryClient { - private readonly store: TelemetryStore; - private readonly repository: TelemetryRepository; - private readonly retention?: TelemetryRetentionPolicy; - private readonly hydrated = new Set(); - /** Bumped on every storage rescope; see `ChatClient`. */ - private epoch = 0; - - constructor(client: MeshClient, options: TelemetryClientOptions = {}) { - this.store = new TelemetryStore(); - this.repository = options.repository ?? new InMemoryTelemetryRepository(); - this.retention = options.retention; - - client.events.onTelemetryPacket.subscribe(async (packet) => { - const reading = TelemetryMapper.fromPacket(packet); - this.store.append(reading); - try { - await this.repository.append(reading); - if (this.retention) { - await this.repository.prune(this.retention); - } - } catch (e) { - console.warn("[TelemetryClient] persistence failed:", e); - } - }); - } - - public latest(nodeNum: number): ReadonlySignal { - void this.hydrate(nodeNum); - return this.store.latestFor(nodeNum); - } - - public history(nodeNum: number): ReadonlySignal { - void this.hydrate(nodeNum); - return this.store.historyFor(nodeNum); - } - - /** - * Page older readings before the given cursor — passes through to the - * repository. Caller is responsible for merging with the in-memory store - * if it wants the result reflected in the `history(nodeNum)` signal. - */ - public loadBefore( - nodeNum: number, - cursor: Date, - limit: number, - ): Promise { - return this.repository.loadBefore(nodeNum, cursor, limit); - } - - /** - * Points the repository at another storage scope and reloads from it the - * history of every node loaded so far. Readings held for the old scope are - * dropped. - */ - public rescope(scope: number): void { - this.repository.setScope?.(scope); - this.epoch++; - const nodes = [...this.hydrated]; - this.store.clear(); - this.hydrated.clear(); - for (const nodeNum of nodes) void this.hydrate(nodeNum); - } - - public clearNode(nodeNum: number): Promise { - this.hydrated.delete(nodeNum); - return this.repository.clearNode(nodeNum); - } - - public clear(): Promise { - this.hydrated.clear(); - return this.repository.clear(); - } - - private async hydrate(nodeNum: number): Promise { - if (this.hydrated.has(nodeNum)) return; - this.hydrated.add(nodeNum); - const epoch = this.epoch; - try { - const readings = await this.repository.loadRecent(nodeNum, HYDRATE_LIMIT); - if (epoch !== this.epoch) return; - this.store.merge(nodeNum, readings); - } catch (e) { - console.warn("[TelemetryClient] hydrate failed:", e); - } - } -} diff --git a/packages/sdk/src/features/telemetry/domain/TelemetryReading.ts b/packages/sdk/src/features/telemetry/domain/TelemetryReading.ts deleted file mode 100644 index c3d22a521..000000000 --- a/packages/sdk/src/features/telemetry/domain/TelemetryReading.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type * as Protobuf from "@meshtastic/protobufs"; - -export type TelemetryKind = Protobuf.Telemetry.Telemetry["variant"]["case"]; - -export interface TelemetryReading { - readonly nodeNum: number; - readonly time: Date; - readonly kind: TelemetryKind; - readonly value: Protobuf.Telemetry.Telemetry["variant"]["value"]; -} diff --git a/packages/sdk/src/features/telemetry/domain/TelemetryRepository.ts b/packages/sdk/src/features/telemetry/domain/TelemetryRepository.ts deleted file mode 100644 index 0be563298..000000000 --- a/packages/sdk/src/features/telemetry/domain/TelemetryRepository.ts +++ /dev/null @@ -1,35 +0,0 @@ -import type { TelemetryReading } from "./TelemetryReading.ts"; - -export interface TelemetryRetentionPolicy { - /** Keep at most this many readings per node. */ - maxPerNode?: number; - /** Drop anything older than this many ms. */ - olderThanMs?: number; -} - -/** - * Port for persisting telemetry readings. Implementations live in adapter - * packages (e.g. `@meshtastic/sdk-storage-sqlocal`) or in-memory within the - * SDK itself. - * - * Reads are paginated by node so consumers can lazy-load history on scroll - * rather than rehydrating every reading at boot. - */ -export interface TelemetryRepository { - loadRecent(nodeNum: number, limit: number): Promise; - loadBefore( - nodeNum: number, - cursor: Date, - limit: number, - ): Promise; - append(reading: TelemetryReading): Promise; - appendBatch(readings: ReadonlyArray): Promise; - prune(policy: TelemetryRetentionPolicy): Promise; - clearNode(nodeNum: number): Promise; - clear(): Promise; - /** - * Points every later read and write at another storage scope. See - * `MessageRepository.setScope`. - */ - setScope?(scope: number): void; -} diff --git a/packages/sdk/src/features/telemetry/index.ts b/packages/sdk/src/features/telemetry/index.ts deleted file mode 100644 index 07579b877..000000000 --- a/packages/sdk/src/features/telemetry/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -export { TelemetryClient } from "./TelemetryClient.ts"; -export type { TelemetryClientOptions } from "./TelemetryClient.ts"; -export type { - TelemetryKind, - TelemetryReading, -} from "./domain/TelemetryReading.ts"; -export type { - TelemetryRepository, - TelemetryRetentionPolicy, -} from "./domain/TelemetryRepository.ts"; -export { TelemetryMapper } from "./infrastructure/TelemetryMapper.ts"; -export { InMemoryTelemetryRepository } from "./infrastructure/repositories/InMemoryTelemetryRepository.ts"; diff --git a/packages/sdk/src/features/telemetry/infrastructure/TelemetryMapper.ts b/packages/sdk/src/features/telemetry/infrastructure/TelemetryMapper.ts deleted file mode 100644 index 19a987c2d..000000000 --- a/packages/sdk/src/features/telemetry/infrastructure/TelemetryMapper.ts +++ /dev/null @@ -1,16 +0,0 @@ -import type { PacketMetadata } from "../../../core/types.ts"; -import type * as Protobuf from "@meshtastic/protobufs"; -import type { TelemetryReading } from "../domain/TelemetryReading.ts"; - -export const TelemetryMapper = { - fromPacket( - packet: PacketMetadata, - ): TelemetryReading { - return { - nodeNum: packet.from, - time: packet.rxTime, - kind: packet.data.variant.case, - value: packet.data.variant.value, - }; - }, -}; diff --git a/packages/sdk/src/features/telemetry/infrastructure/repositories/InMemoryTelemetryRepository.test.ts b/packages/sdk/src/features/telemetry/infrastructure/repositories/InMemoryTelemetryRepository.test.ts deleted file mode 100644 index b4a767970..000000000 --- a/packages/sdk/src/features/telemetry/infrastructure/repositories/InMemoryTelemetryRepository.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { describe, expect, it } from "vitest"; -import type { TelemetryReading } from "../../domain/TelemetryReading.ts"; -import { InMemoryTelemetryRepository } from "./InMemoryTelemetryRepository.ts"; - -const reading = (nodeNum: number, ms: number): TelemetryReading => ({ - nodeNum, - time: new Date(ms), - kind: "deviceMetrics", - value: { batteryLevel: 50 } as TelemetryReading["value"], -}); - -describe("InMemoryTelemetryRepository", () => { - it("appends and loads recent readings per node", async () => { - const repo = new InMemoryTelemetryRepository(); - await repo.append(reading(1, 1000)); - await repo.append(reading(1, 2000)); - await repo.append(reading(2, 1500)); - - expect(await repo.loadRecent(1, 10)).toHaveLength(2); - expect(await repo.loadRecent(2, 10)).toHaveLength(1); - expect(await repo.loadRecent(99, 10)).toHaveLength(0); - }); - - it("loadBefore returns the limit of readings before the cursor", async () => { - const repo = new InMemoryTelemetryRepository(); - await repo.appendBatch([ - reading(1, 1000), - reading(1, 2000), - reading(1, 3000), - reading(1, 4000), - ]); - - const result = await repo.loadBefore(1, new Date(3000), 2); - expect(result.map((r) => r.time.getTime())).toEqual([1000, 2000]); - }); - - it("prune drops readings older than olderThanMs", async () => { - const repo = new InMemoryTelemetryRepository(); - await repo.appendBatch([ - reading(1, Date.now() - 10_000_000), - reading(1, Date.now() - 1_000), - ]); - await repo.prune({ olderThanMs: 5_000_000 }); - const remaining = await repo.loadRecent(1, 10); - expect(remaining).toHaveLength(1); - }); - - it("prune trims per-node history to maxPerNode", async () => { - const repo = new InMemoryTelemetryRepository(); - for (let i = 0; i < 50; i++) { - await repo.append(reading(1, i * 1000)); - } - await repo.prune({ maxPerNode: 10 }); - expect(await repo.loadRecent(1, 100)).toHaveLength(10); - }); - - it("clearNode removes only the named node", async () => { - const repo = new InMemoryTelemetryRepository(); - await repo.append(reading(1, 1000)); - await repo.append(reading(2, 1000)); - await repo.clearNode(1); - expect(await repo.loadRecent(1, 10)).toHaveLength(0); - expect(await repo.loadRecent(2, 10)).toHaveLength(1); - }); -}); diff --git a/packages/sdk/src/features/telemetry/infrastructure/repositories/InMemoryTelemetryRepository.ts b/packages/sdk/src/features/telemetry/infrastructure/repositories/InMemoryTelemetryRepository.ts deleted file mode 100644 index dff35956d..000000000 --- a/packages/sdk/src/features/telemetry/infrastructure/repositories/InMemoryTelemetryRepository.ts +++ /dev/null @@ -1,69 +0,0 @@ -import type { TelemetryReading } from "../../domain/TelemetryReading.ts"; -import type { - TelemetryRepository, - TelemetryRetentionPolicy, -} from "../../domain/TelemetryRepository.ts"; - -/** - * Default in-memory TelemetryRepository. No persistence across reloads. - * Suitable for tests and for single-session apps that do not need history. - */ -export class InMemoryTelemetryRepository implements TelemetryRepository { - private readonly buckets = new Map(); - - async loadRecent( - nodeNum: number, - limit: number, - ): Promise { - return (this.buckets.get(nodeNum) ?? []).slice(-limit); - } - - async loadBefore( - nodeNum: number, - cursor: Date, - limit: number, - ): Promise { - const bucket = this.buckets.get(nodeNum) ?? []; - const idx = bucket.findIndex((r) => r.time >= cursor); - const end = idx === -1 ? bucket.length : idx; - const start = Math.max(0, end - limit); - return bucket.slice(start, end); - } - - async append(reading: TelemetryReading): Promise { - await this.appendBatch([reading]); - } - - async appendBatch(readings: ReadonlyArray): Promise { - for (const reading of readings) { - const bucket = this.buckets.get(reading.nodeNum) ?? []; - bucket.push(reading); - bucket.sort((a, b) => a.time.getTime() - b.time.getTime()); - this.buckets.set(reading.nodeNum, bucket); - } - } - - async prune(policy: TelemetryRetentionPolicy): Promise { - const cutoff = policy.olderThanMs - ? Date.now() - policy.olderThanMs - : undefined; - for (const [nodeNum, bucket] of this.buckets.entries()) { - let next = bucket; - if (cutoff !== undefined) { - next = next.filter((r) => r.time.getTime() >= cutoff); - } - if (policy.maxPerNode !== undefined && next.length > policy.maxPerNode) { - next = next.slice(-policy.maxPerNode); - } - this.buckets.set(nodeNum, next); - } - } - - async clearNode(nodeNum: number): Promise { - this.buckets.delete(nodeNum); - } - - async clear(): Promise { - this.buckets.clear(); - } -} diff --git a/packages/sdk/src/features/telemetry/state/telemetryStore.ts b/packages/sdk/src/features/telemetry/state/telemetryStore.ts deleted file mode 100644 index 5e5316cd7..000000000 --- a/packages/sdk/src/features/telemetry/state/telemetryStore.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { type Signal, signal } from "@preact/signals-core"; -import { - type ReadonlySignal, - toReadonly, -} from "../../../core/signals/createStore.ts"; -import type { TelemetryReading } from "../domain/TelemetryReading.ts"; - -const MAX_HISTORY = 256; - -export class TelemetryStore { - private readonly latest = new Map< - number, - Signal - >(); - private readonly latestRead = new Map< - number, - ReadonlySignal - >(); - private readonly history = new Map>(); - private readonly historyRead = new Map< - number, - ReadonlySignal - >(); - - append(reading: TelemetryReading): void { - const latestSig = this.ensureLatest(reading.nodeNum); - latestSig.value = reading; - - const histSig = this.ensureHistory(reading.nodeNum); - const next = [...histSig.value, reading]; - if (next.length > MAX_HISTORY) next.splice(0, next.length - MAX_HISTORY); - histSig.value = next; - } - - /** - * Adds stored readings for one node, skipping any already held (same kind - * and time), and keeps history in time order with the newest as latest. - */ - merge(nodeNum: number, readings: ReadonlyArray): void { - if (readings.length === 0) return; - const histSig = this.ensureHistory(nodeNum); - const keyOf = (r: TelemetryReading): string => - `${r.kind}:${r.time.getTime()}`; - const seen = new Set(histSig.value.map(keyOf)); - const added = readings.filter((r) => { - const key = keyOf(r); - if (seen.has(key)) return false; - seen.add(key); - return true; - }); - if (added.length === 0) return; - const next = [...histSig.value, ...added].sort( - (a, b) => a.time.getTime() - b.time.getTime(), - ); - if (next.length > MAX_HISTORY) next.splice(0, next.length - MAX_HISTORY); - histSig.value = next; - this.ensureLatest(nodeNum).value = next[next.length - 1]; - } - - /** - * Empties every node's latest reading and history. Signals stay in place - * so subscribers keep receiving updates. - */ - clear(): void { - for (const sig of this.latest.values()) sig.value = undefined; - for (const sig of this.history.values()) { - if (sig.value.length > 0) sig.value = []; - } - } - - latestFor(nodeNum: number): ReadonlySignal { - this.ensureLatest(nodeNum); - const read = this.latestRead.get(nodeNum); - if (!read) throw new Error("unreachable"); - return read; - } - - historyFor(nodeNum: number): ReadonlySignal { - this.ensureHistory(nodeNum); - const read = this.historyRead.get(nodeNum); - if (!read) throw new Error("unreachable"); - return read; - } - - private ensureLatest(nodeNum: number): Signal { - let sig = this.latest.get(nodeNum); - if (!sig) { - sig = signal(undefined); - this.latest.set(nodeNum, sig); - this.latestRead.set(nodeNum, toReadonly(sig)); - } - return sig; - } - - private ensureHistory(nodeNum: number): Signal { - let sig = this.history.get(nodeNum); - if (!sig) { - sig = signal([]); - this.history.set(nodeNum, sig); - this.historyRead.set(nodeNum, toReadonly(sig)); - } - return sig; - } -} diff --git a/packages/sdk/src/features/traceroute/TraceRouteClient.ts b/packages/sdk/src/features/traceroute/TraceRouteClient.ts deleted file mode 100644 index dbf4dad49..000000000 --- a/packages/sdk/src/features/traceroute/TraceRouteClient.ts +++ /dev/null @@ -1,35 +0,0 @@ -import type { Result } from "better-result"; -import type { MeshClient } from "../../core/client/MeshClient.ts"; -import type { ReadonlySignal } from "../../core/signals/createStore.ts"; -import type { TraceRoute } from "./domain/TraceRoute.ts"; -import { runTraceRoute } from "./application/TraceRouteUseCase.ts"; -import { TraceRouteStore } from "./state/tracerouteStore.ts"; - -export class TraceRouteClient { - private readonly client: MeshClient; - private readonly store: TraceRouteStore; - public readonly list: ReadonlySignal>; - - constructor(client: MeshClient) { - this.client = client; - this.store = new TraceRouteStore(); - this.list = this.store.read; - - client.events.onTraceRoutePacket.subscribe((packet) => { - this.store.set(packet.from, { - destination: packet.from, - route: packet.data.route, - snr: packet.data.snrTowards, - time: packet.rxTime, - }); - }); - } - - public latest(destination: number): TraceRoute | undefined { - return this.store.get(destination); - } - - public run(destination: number): Promise> { - return runTraceRoute(this.client, destination); - } -} diff --git a/packages/sdk/src/features/traceroute/application/TraceRouteUseCase.ts b/packages/sdk/src/features/traceroute/application/TraceRouteUseCase.ts deleted file mode 100644 index 0a5d471ec..000000000 --- a/packages/sdk/src/features/traceroute/application/TraceRouteUseCase.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { create, toBinary } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { Result } from "better-result"; -import type { MeshClient } from "../../../core/client/MeshClient.ts"; - -export async function runTraceRoute( - client: MeshClient, - destination: number, -): Promise> { - try { - const routeDiscovery = create(Protobuf.Mesh.RouteDiscoverySchema, { - route: [], - }); - const id = await client.sendPacket( - toBinary(Protobuf.Mesh.RouteDiscoverySchema, routeDiscovery), - Protobuf.Portnums.PortNum.TRACEROUTE_APP, - destination, - ); - return Result.ok(id); - } catch (e) { - return Result.err(e instanceof Error ? e : new Error(String(e))); - } -} diff --git a/packages/sdk/src/features/traceroute/domain/TraceRoute.ts b/packages/sdk/src/features/traceroute/domain/TraceRoute.ts deleted file mode 100644 index 15bc5de3d..000000000 --- a/packages/sdk/src/features/traceroute/domain/TraceRoute.ts +++ /dev/null @@ -1,6 +0,0 @@ -export interface TraceRoute { - readonly destination: number; - readonly route: ReadonlyArray; - readonly snr?: ReadonlyArray; - readonly time: Date; -} diff --git a/packages/sdk/src/features/traceroute/index.ts b/packages/sdk/src/features/traceroute/index.ts deleted file mode 100644 index b2d349feb..000000000 --- a/packages/sdk/src/features/traceroute/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { TraceRouteClient } from "./TraceRouteClient.ts"; -export type { TraceRoute } from "./domain/TraceRoute.ts"; diff --git a/packages/sdk/src/features/traceroute/state/tracerouteStore.ts b/packages/sdk/src/features/traceroute/state/tracerouteStore.ts deleted file mode 100644 index 9e66e5337..000000000 --- a/packages/sdk/src/features/traceroute/state/tracerouteStore.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { SignalMap } from "../../../core/signals/createStore.ts"; -import type { TraceRoute } from "../domain/TraceRoute.ts"; - -export class TraceRouteStore extends SignalMap {} diff --git a/packages/sdk/src/shim/legacyMeshDevice.ts b/packages/sdk/src/shim/legacyMeshDevice.ts deleted file mode 100644 index 48460fdb0..000000000 --- a/packages/sdk/src/shim/legacyMeshDevice.ts +++ /dev/null @@ -1,409 +0,0 @@ -/** - * Coarse facade providing the legacy `MeshDevice` surface — preserved - * after Phase C because the web app's `connection.factoryResetDevice()` / - * `connection.reboot()` / etc. callsites still depend on it. Delegates to - * the new `MeshClient` + feature slices. New consumers should reach into - * the slice clients (`client.config`, `client.chat`, …) directly. - */ - -import { create, toBinary } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import type { Logger } from "tslog"; -import { - MeshClient, - type MeshClientOptions, -} from "../core/client/MeshClient.ts"; -import type { EventBus } from "../core/event-bus/EventBus.ts"; -import type { Queue } from "../core/queue/Queue.ts"; -import type { Transport } from "../core/transport/Transport.ts"; -import { DeviceStatusEnum } from "../core/transport/Transport.ts"; -import { - ChannelNumber, - type Destination, - Emitter, - type PacketMetadata, -} from "../core/types.ts"; -import type { Xmodem } from "../core/xmodem/Xmodem.ts"; -import { sendAdminMessage } from "../features/device/infrastructure/AdminMessageSender.ts"; - -export type MeshDeviceOptions = Omit; - -export class MeshDevice { - public readonly meshClient: MeshClient; - private readonly client: MeshClient; - - public transport: Transport; - public log: Logger; - public events: EventBus; - public queue: Queue; - public xModem: Xmodem; - public configId: number; - - protected deviceStatus: DeviceStatusEnum; - protected isConfigured: boolean; - protected pendingSettingsChanges: boolean; - private myNodeInfo: Protobuf.Mesh.MyNodeInfo; - - constructor( - transport: Transport, - configIdOrOptions?: number | MeshDeviceOptions, - ) { - const options: MeshClientOptions = - typeof configIdOrOptions === "number" - ? { transport, configId: configIdOrOptions } - : { transport, ...(configIdOrOptions ?? {}) }; - this.client = new MeshClient(options); - this.meshClient = this.client; - this.transport = this.client.transport; - this.log = this.client.log; - this.events = this.client.events; - this.queue = this.client.queue; - this.xModem = this.client.xModem; - this.configId = this.client.configId; - this.deviceStatus = DeviceStatusEnum.DeviceDisconnected; - this.isConfigured = false; - this.pendingSettingsChanges = false; - this.myNodeInfo = create(Protobuf.Mesh.MyNodeInfoSchema); - - this.client.events.onDeviceStatus.subscribe((status) => { - this.deviceStatus = status; - if (status === DeviceStatusEnum.DeviceConfigured) - this.isConfigured = true; - else if (status === DeviceStatusEnum.DeviceConfiguring) - this.isConfigured = false; - }); - this.client.events.onMyNodeInfo.subscribe((info) => { - this.myNodeInfo = info; - }); - this.client.events.onPendingSettingsChange.subscribe((pending) => { - this.pendingSettingsChanges = pending; - }); - } - - public updateDeviceStatus(status: DeviceStatusEnum): void { - this.client.updateDeviceStatus(status); - } - - public configure(): Promise { - return this.client.configure(); - } - - public heartbeat(): Promise { - return this.client.heartbeat(); - } - - public setHeartbeatInterval(interval: number): void { - this.client.setHeartbeatInterval(interval); - } - - public complete(): void { - this.client.complete(); - } - - public disconnect(): Promise { - return this.client.disconnect(); - } - - public sendPacket( - byteData: Uint8Array, - portNum: Protobuf.Portnums.PortNum, - destination: Destination, - channel: ChannelNumber = ChannelNumber.Primary, - wantAck = true, - wantResponse = true, - echoResponse = false, - replyId?: number, - emoji?: number, - ): Promise { - return this.client.sendPacket( - byteData, - portNum, - destination, - channel, - wantAck, - wantResponse, - echoResponse, - replyId, - emoji, - ); - } - - public sendRaw(toRadio: Uint8Array, id?: number): Promise { - return this.client.sendRaw(toRadio, id); - } - - public async sendText( - text: string, - destination?: Destination, - wantAck?: boolean, - channel?: ChannelNumber, - replyId?: number, - emoji?: number, - ): Promise { - this.log.debug( - Emitter[Emitter.SendText], - `📤 Sending message to ${destination ?? "broadcast"} on channel ${channel?.toString() ?? 0}`, - ); - return this.client.sendPacket( - new TextEncoder().encode(text), - Protobuf.Portnums.PortNum.TEXT_MESSAGE_APP, - destination ?? "broadcast", - channel, - wantAck, - false, - true, - replyId, - emoji, - ); - } - - public sendWaypoint( - waypointMessage: Protobuf.Mesh.Waypoint, - destination: Destination, - channel?: ChannelNumber, - ): Promise { - waypointMessage.id = Math.floor(Math.random() * 1e9); - return this.client.sendPacket( - toBinary(Protobuf.Mesh.WaypointSchema, waypointMessage), - Protobuf.Portnums.PortNum.WAYPOINT_APP, - destination, - channel, - true, - false, - ); - } - - public setConfig(config: Protobuf.Config.Config): Promise { - return sendAdminMessage(this.client, { case: "setConfig", value: config }); - } - - public setModuleConfig( - config: Protobuf.ModuleConfig.ModuleConfig, - ): Promise { - return sendAdminMessage(this.client, { - case: "setModuleConfig", - value: config, - }); - } - - public setCannedMessages( - messages: Protobuf.CannedMessages.CannedMessageModuleConfig, - ): Promise { - return sendAdminMessage(this.client, { - case: "setCannedMessageModuleMessages", - value: messages.messages, - }); - } - - public setOwner(owner: Protobuf.Mesh.User): Promise { - return sendAdminMessage(this.client, { case: "setOwner", value: owner }); - } - - public setChannel(channel: Protobuf.Channel.Channel): Promise { - return sendAdminMessage(this.client, { - case: "setChannel", - value: channel, - }); - } - - public enterDfuMode(): Promise { - return sendAdminMessage(this.client, { - case: "enterDfuModeRequest", - value: true, - }); - } - - public setPosition(position: Protobuf.Mesh.Position): Promise { - return this.client.sendPacket( - toBinary(Protobuf.Mesh.PositionSchema, position), - Protobuf.Portnums.PortNum.POSITION_APP, - "self", - ); - } - - public setFixedPosition( - latitude: number, - longitude: number, - ): Promise { - const position = create(Protobuf.Mesh.PositionSchema, { - latitudeI: Math.floor(latitude / 1e-7), - longitudeI: Math.floor(longitude / 1e-7), - }); - return sendAdminMessage( - this.client, - { case: "setFixedPosition", value: position }, - "self", - undefined, - true, - false, - ); - } - - public removeFixedPosition(): Promise { - return sendAdminMessage( - this.client, - { case: "removeFixedPosition", value: true }, - "self", - undefined, - true, - false, - ); - } - - public getChannel(index: number): Promise { - return sendAdminMessage(this.client, { - case: "getChannelRequest", - value: index + 1, - }); - } - - public getConfig( - type: Protobuf.Admin.AdminMessage_ConfigType, - ): Promise { - return sendAdminMessage(this.client, { - case: "getConfigRequest", - value: type, - }); - } - - public getModuleConfig( - type: Protobuf.Admin.AdminMessage_ModuleConfigType, - ): Promise { - return sendAdminMessage(this.client, { - case: "getModuleConfigRequest", - value: type, - }); - } - - public getOwner(): Promise { - return sendAdminMessage(this.client, { - case: "getOwnerRequest", - value: true, - }); - } - - public sendKeyVerification( - messageType: Protobuf.Admin.KeyVerificationAdmin_MessageType, - remoteNodenum: number, - nonce: bigint, - securityNumber?: number, - ): Promise { - return this.client.device.sendKeyVerification( - messageType, - remoteNodenum, - nonce, - securityNumber, - ); - } - - public getMetadata(nodeNum: number): Promise { - return sendAdminMessage( - this.client, - { case: "getDeviceMetadataRequest", value: true }, - nodeNum, - ChannelNumber.Admin, - ); - } - - public clearChannel(index: number): Promise { - const channel = create(Protobuf.Channel.ChannelSchema, { - index, - role: Protobuf.Channel.Channel_Role.DISABLED, - }); - return sendAdminMessage(this.client, { - case: "setChannel", - value: channel, - }); - } - - public commitEditSettings(): Promise { - this.events.onPendingSettingsChange.dispatch(false); - return sendAdminMessage(this.client, { - case: "commitEditSettings", - value: true, - }); - } - - public resetNodes(): Promise { - return sendAdminMessage(this.client, { case: "nodedbReset", value: true }); - } - - public removeNodeByNum(nodeNum: number): Promise { - return sendAdminMessage(this.client, { - case: "removeByNodenum", - value: nodeNum, - }); - } - - public shutdown(time: number): Promise { - return sendAdminMessage(this.client, { - case: "shutdownSeconds", - value: time, - }); - } - - public reboot(time: number): Promise { - return sendAdminMessage(this.client, { - case: "rebootSeconds", - value: time, - }); - } - - public rebootOta(time: number): Promise { - return sendAdminMessage(this.client, { - case: "rebootOtaSeconds", - value: time, - }); - } - - public factoryResetDevice(): Promise { - return sendAdminMessage(this.client, { - case: "factoryResetDevice", - value: 1, - }); - } - - public factoryResetConfig(): Promise { - return sendAdminMessage(this.client, { - case: "factoryResetConfig", - value: 1, - }); - } - - public traceRoute(destination: number): Promise { - const discovery = create(Protobuf.Mesh.RouteDiscoverySchema, { route: [] }); - return this.client.sendPacket( - toBinary(Protobuf.Mesh.RouteDiscoverySchema, discovery), - Protobuf.Portnums.PortNum.TRACEROUTE_APP, - destination, - ); - } - - public requestPosition(destination: number): Promise { - return this.client.sendPacket( - new Uint8Array(), - Protobuf.Portnums.PortNum.POSITION_APP, - destination, - ); - } - - /** Exposed for callers that still reach into internals (e.g. packet-codec). */ - public handleMeshPacket(_packet: Protobuf.Mesh.MeshPacket): void { - // Packet routing now lives in the core packet-codec. Intentionally a no-op - // on the shim — the underlying MeshClient has already wired decode events. - } - - /** Metadata accessor (previously `this.myNodeInfo`). */ - public getMyNodeInfo(): Protobuf.Mesh.MyNodeInfo { - return this.myNodeInfo; - } - - /** Exposes an optimistic packet echo (was called by sendPacket echoResponse). */ - public echoLocalPacket( - metadata: Omit, "data">, - data: T, - ): void { - void metadata; - void data; - } -} diff --git a/packages/sdk/src/shim/legacyTypes.ts b/packages/sdk/src/shim/legacyTypes.ts deleted file mode 100644 index e9d4fec56..000000000 --- a/packages/sdk/src/shim/legacyTypes.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Backwards-compatible re-export of the cross-cutting types under the - * `Types` namespace. mod.ts already exports `Types` directly from - * `core/types.ts`; this file is no longer wired anywhere but is kept as a - * stable import path for any third-party that grabbed it via the published - * dist. - */ -export type { - Destination, - DeviceOutput, - HttpRetryConfig, - LogEvent, - LogEventPacket, - PacketDestination, - PacketError, - PacketMetadata, - QueueItem, - Transport, -} from "../core/types.ts"; -export { - ChannelNumber, - DeviceStatusEnum, - Emitter, - EmitterScope, -} from "../core/types.ts"; diff --git a/packages/sdk/src/shim/legacyUtils.ts b/packages/sdk/src/shim/legacyUtils.ts deleted file mode 100644 index 3bbd23e7b..000000000 --- a/packages/sdk/src/shim/legacyUtils.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * Re-exports for the public `Utils` namespace (mod.ts: `export * as Utils`). - * Transport packages import `toDeviceStream` / `fromDeviceStream` here. - */ -export { EventBus as EventSystem } from "../core/event-bus/EventBus.ts"; -export { Queue } from "../core/queue/Queue.ts"; -export { Xmodem } from "../core/xmodem/Xmodem.ts"; -export { fromDeviceStream } from "../core/packet-codec/fromDevice.ts"; -export { toDeviceStream } from "../core/packet-codec/toDevice.ts"; diff --git a/packages/sdk/src/types-namespace.ts b/packages/sdk/src/types-namespace.ts deleted file mode 100644 index 3b4de8cda..000000000 --- a/packages/sdk/src/types-namespace.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** - * Wrapper that surfaces the cross-cutting types under a single namespace - * via `import * as Types`. Required because tsdown's dts emitter mishandles - * `export * as Types from ...` directly (it emits a reference to a synthetic - * `types_d_exports` identifier that's never declared, breaking downstream - * consumers' dts bundlers). - */ -export * from "./core/types.ts"; diff --git a/packages/sdk/tests/integration/fake-transport.test.ts b/packages/sdk/tests/integration/fake-transport.test.ts deleted file mode 100644 index d0c7addd1..000000000 --- a/packages/sdk/tests/integration/fake-transport.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { create } from "@bufbuild/protobuf"; -import * as Protobuf from "@meshtastic/protobufs"; -import { describe, expect, it } from "vitest"; -import { MeshClient } from "../../src/core/client/MeshClient.ts"; -import { createFakeTransport } from "../../src/core/testing/createFakeTransport.ts"; -import { ChannelNumber } from "../../src/core/types.ts"; - -describe("MeshClient with fake transport", () => { - it("wires MyNodeInfo → device.myNodeNum signal", async () => { - const { transport, respond } = createFakeTransport(); - const client = new MeshClient({ transport }); - respond.withMyNodeInfo({ myNodeNum: 42 }); - await new Promise((r) => setTimeout(r, 10)); - expect(client.device.myNodeNum.value).toBe(42); - }); - - it("wires NodeInfo → nodes.list signal", async () => { - const { transport, respond } = createFakeTransport(); - const client = new MeshClient({ transport }); - respond.withNodeInfo({ num: 1234 }); - await new Promise((r) => setTimeout(r, 10)); - expect(client.nodes.list.value.length).toBe(1); - expect(client.nodes.list.value[0]?.num).toBe(1234); - }); - - it("routes a TEXT_MESSAGE_APP mesh packet into chat.messages", async () => { - const { transport, respond } = createFakeTransport(); - const client = new MeshClient({ transport }); - const text = new TextEncoder().encode("hello mesh"); - const packet = create(Protobuf.Mesh.MeshPacketSchema, { - id: 5, - from: 9, - to: 0xffffffff, - channel: ChannelNumber.Primary, - rxTime: Math.trunc(Date.now() / 1000), - payloadVariant: { - case: "decoded", - value: { - portnum: Protobuf.Portnums.PortNum.TEXT_MESSAGE_APP, - payload: text, - wantResponse: false, - }, - }, - }); - respond.withMeshPacket(packet); - await new Promise((r) => setTimeout(r, 10)); - const messages = client.chat.messages(ChannelNumber.Primary).value; - expect(messages.length).toBe(1); - expect(messages[0]?.text).toBe("hello mesh"); - }); -}); - -describe("MeshClient rebooted event", () => { - it("dispatches onRebooted when firmware emits a `rebooted` FromRadio", async () => { - const { transport, respond } = createFakeTransport(); - const client = new MeshClient({ transport }); - let fired = 0; - client.events.onRebooted.subscribe(() => { - fired += 1; - }); - - respond.withRaw( - create(Protobuf.Mesh.FromRadioSchema, { - payloadVariant: { case: "rebooted", value: true }, - }), - ); - await new Promise((r) => setTimeout(r, 10)); - - expect(fired).toBe(1); - }); -}); diff --git a/packages/sdk/tsconfig.json b/packages/sdk/tsconfig.json deleted file mode 100644 index b01917932..000000000 --- a/packages/sdk/tsconfig.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "include": ["mod.ts", "src"] -} diff --git a/packages/sdk/vitest.config.ts b/packages/sdk/vitest.config.ts deleted file mode 100644 index a34c603ed..000000000 --- a/packages/sdk/vitest.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { defineProject } from "vitest/config"; - -export default defineProject({ - test: { - name: "@meshtastic/sdk", - environment: "node", - include: ["src/**/*.test.ts", "tests/**/*.test.ts"], - }, -}); diff --git a/packages/transport-deno/README.md b/packages/transport-deno/README.md deleted file mode 100644 index 41f2aca64..000000000 --- a/packages/transport-deno/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# @meshtastic/transport-deno - -[![JSR](https://jsr.io/badges/@meshtastic/transport-deno)](https://jsr.io/@meshtastic/transport-deno) -[![CI](https://img.shields.io/github/actions/workflow/status/meshtastic/js/ci.yml?branch=master&label=actions&logo=github&color=yellow)](https://github.com/meshtastic/js/actions/workflows/ci.yml) -[![CLA assistant](https://cla-assistant.io/readme/badge/meshtastic/meshtastic.js)](https://cla-assistant.io/meshtastic/meshtastic.js) -[![Fiscal Contributors](https://opencollective.com/meshtastic/tiers/badge.svg?label=Fiscal%20Contributors&color=deeppink)](https://opencollective.com/meshtastic/) -[![Vercel](https://img.shields.io/static/v1?label=Powered%20by&message=Vercel&style=flat&logo=vercel&color=000000)](https://vercel.com?utm_source=meshtastic&utm_campaign=oss) - -## Overview - -`@meshtastic/transport-deno` Provides TCP transport (Deno) for Meshtastic -devices. Installation instructions are avaliable at -[JSR](https://jsr.io/@meshtastic/transport-deno) -[NPM](https://www.npmjs.com/org/meshtastic/transport-deno) - -## Usage - -```ts -import { MeshDevice } from "@meshtastic/sdk"; -import { TransportDeno } from "@meshtastic/transport-deno"; - -const transport = await TransportDeno.create("10.10.0.57"); -const device = new MeshDevice(transport); -``` - -## Stats - -![Alt](https://repobeats.axiom.co/api/embed/5330641586e92a2ec84676fedb98f6d4a7b25d69.svg "Repobeats analytics image") diff --git a/packages/transport-deno/deno.json b/packages/transport-deno/deno.json deleted file mode 100644 index 5e63d3d6d..000000000 --- a/packages/transport-deno/deno.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "imports": { - "@deno/dnt": "jsr:@deno/dnt@^0.42.3" - } -} diff --git a/packages/transport-deno/mod.ts b/packages/transport-deno/mod.ts deleted file mode 100644 index 55a633464..000000000 --- a/packages/transport-deno/mod.ts +++ /dev/null @@ -1 +0,0 @@ -export { TransportDeno } from "./src/transport.ts"; diff --git a/packages/transport-deno/package.json b/packages/transport-deno/package.json deleted file mode 100644 index 2181bd6af..000000000 --- a/packages/transport-deno/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "@meshtastic/transport-deno", - "version": "1.0.0", - "description": "Deno-specific transport layer for Meshtastic web applications.", - "license": "GPL-3.0-only", - "files": [ - "package.json", - "README.md", - "LICENSE", - "dist" - ], - "main": "./dist/mod.js", - "module": "./dist/mod.js", - "types": "./dist/mod.d.ts", - "exports": { - ".": "./mod.ts" - }, - "scripts": { - "preinstall": "npx only-allow pnpm", - "prepack": "cp ../../LICENSE ./LICENSE", - "clean": "rm -rf dist LICENSE", - "build:npm": "tsdown", - "publish:npm": "pnpm clean && pnpm build:npm && pnpm publish --access public", - "prepare:jsr": "rm -rf dist && pnpm dlx pkg-to-jsr", - "publish:jsr": "pnpm run prepack && pnpm prepare:jsr && deno publish --allow-dirty --no-check" - }, - "dependencies": { - "@meshtastic/sdk": "workspace:*" - }, - "tsdown": { - "clean": true, - "dts": true, - "entry": "mod.ts", - "format": [ - "esm" - ], - "minify": false, - "report": false, - "sourcemap": false, - "splitting": false, - "target": "esnext", - "treeshake": true - } -} diff --git a/packages/transport-deno/scripts/build_npm.ts b/packages/transport-deno/scripts/build_npm.ts deleted file mode 100644 index 5c88dbd6c..000000000 --- a/packages/transport-deno/scripts/build_npm.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { build, emptyDir } from "@deno/dnt"; - -await emptyDir("./npm"); - -await build({ - entryPoints: ["./mod.ts"], - outDir: "./npm", - shims: { - // see JS docs for overview and more options - deno: true, - }, - package: { - // package.json properties - name: "@meshtastic/transport-deno", - version: Deno.args[0], - description: - "A Deno transport layer for your project, enabling seamless integration with npm.", - license: "GPL-3.0-only", - repository: { - type: "git", - url: "git+https://github.com/username/repo.git", - }, - bugs: { - url: "https://github.com/meshtastic/web/issues", - }, - }, - postBuild() { - // steps to run after building and before running the tests - Deno.copyFileSync("../../LICENSE", "npm/LICENSE"); - Deno.copyFileSync("README.md", "npm/README.md"); - }, -}); diff --git a/packages/transport-deno/src/transport.ts b/packages/transport-deno/src/transport.ts deleted file mode 100644 index 08d195376..000000000 --- a/packages/transport-deno/src/transport.ts +++ /dev/null @@ -1,39 +0,0 @@ -import type { DeviceOutput, Transport } from "@meshtastic/sdk"; -import { fromDeviceStream, toDeviceStream } from "@meshtastic/sdk"; - -export class TransportDeno implements Transport { - private _toDevice: WritableStream; - private _fromDevice: ReadableStream; - private connection: Deno.Conn | undefined; - - public static async create(hostname: string): Promise { - const connection = await Deno.connect({ - hostname, - port: 4403, - }); - return new TransportDeno(connection); - } - - constructor(connection: Deno.Conn) { - this.connection = connection; - const toStream = toDeviceStream(); - toStream.readable.pipeTo(this.connection.writable); - - this._toDevice = toStream.writable; - this._fromDevice = this.connection.readable.pipeThrough(fromDeviceStream()); - } - - get toDevice(): WritableStream { - return this._toDevice; - } - - get fromDevice(): ReadableStream { - return this._fromDevice; - } - - disconnect(): Promise { - this.connection.close(); - this.connection = undefined; - return Promise.resolve(); - } -} diff --git a/packages/transport-http/LICENSE b/packages/transport-http/LICENSE deleted file mode 100644 index f288702d2..000000000 --- a/packages/transport-http/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/packages/transport-http/README.md b/packages/transport-http/README.md deleted file mode 100644 index e1c967fe9..000000000 --- a/packages/transport-http/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# @meshtastic/transport-http - -[![JSR](https://jsr.io/badges/@meshtastic/transport-http)](https://jsr.io/@meshtastic/transport-http) -[![CI](https://img.shields.io/github/actions/workflow/status/meshtastic/js/ci.yml?branch=master&label=actions&logo=github&color=yellow)](https://github.com/meshtastic/js/actions/workflows/ci.yml) -[![CLA assistant](https://cla-assistant.io/readme/badge/meshtastic/meshtastic.js)](https://cla-assistant.io/meshtastic/meshtastic.js) -[![Fiscal Contributors](https://opencollective.com/meshtastic/tiers/badge.svg?label=Fiscal%20Contributors&color=deeppink)](https://opencollective.com/meshtastic/) -[![Vercel](https://img.shields.io/static/v1?label=Powered%20by&message=Vercel&style=flat&logo=vercel&color=000000)](https://vercel.com?utm_source=meshtastic&utm_campaign=oss) - -## Overview - -`@meshtastic/transport-http` Provides HTTP(S) transport for Meshtastic devices. -Installation instructions are available at -[JSR](https://jsr.io/@meshtastic/transport-http) -[NPM](https://www.npmjs.com/package/@meshtastic/transport-http) - -## Usage - -```ts -import { MeshDevice } from "@meshtastic/sdk"; -import { TransportHTTP } from "@meshtastic/transport-http"; - -const transport = await TransportHTTP.create("10.10.0.57"); -const device = new MeshDevice(transport); -``` - -## Stats - -![Alt](https://repobeats.axiom.co/api/embed/5330641586e92a2ec84676fedb98f6d4a7b25d69.svg "Repobeats analytics image") diff --git a/packages/transport-http/mod.ts b/packages/transport-http/mod.ts deleted file mode 100644 index 195079475..000000000 --- a/packages/transport-http/mod.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { TransportHTTP } from "./src/transport.ts"; -export { withLocalNetworkTarget } from "./src/localNetwork.ts"; diff --git a/packages/transport-http/package.json b/packages/transport-http/package.json deleted file mode 100644 index c6adbff40..000000000 --- a/packages/transport-http/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@meshtastic/transport-http", - "version": "1.0.0", - "description": "A transport layer for Meshtastic applications using HTTP.", - "license": "GPL-3.0-only", - "files": [ - "package.json", - "README.md", - "LICENSE", - "dist" - ], - "type": "module", - "main": "./dist/mod.js", - "module": "./dist/mod.js", - "types": "./dist/mod.d.ts", - "exports": { - ".": "./mod.ts" - }, - "scripts": { - "preinstall": "npx only-allow pnpm", - "prepack": "cp ../../LICENSE ./LICENSE", - "clean": "rm -rf dist LICENSE", - "build:npm": "tsdown", - "publish:npm": "pnpm clean && pnpm build:npm && pnpm publish --access public --no-git-checks", - "prepare:jsr": "rm -rf dist && pnpm dlx pkg-to-jsr", - "publish:jsr": "pnpm run prepack && pnpm prepare:jsr && deno publish --allow-dirty --no-check" - }, - "dependencies": { - "@meshtastic/sdk": "workspace:*" - }, - "tsdown": { - "clean": true, - "dts": true, - "entry": "mod.ts", - "format": [ - "esm" - ], - "minify": false, - "report": false, - "sourcemap": false, - "splitting": false, - "target": "esnext", - "treeshake": true - }, - "jsrExclude": [ - "src/**/*.test.ts" - ], - "jsrInclude": [ - "mod.ts", - "src", - "README.md", - "LICENSE" - ] -} diff --git a/packages/transport-http/src/localNetwork.test.ts b/packages/transport-http/src/localNetwork.test.ts deleted file mode 100644 index 095d6840f..000000000 --- a/packages/transport-http/src/localNetwork.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { afterEach, describe, expect, it, vi } from "vitest"; -import { withLocalNetworkTarget } from "./localNetwork.ts"; - -const onPage = (protocol: string) => - vi.stubGlobal("location", { protocol } as Location); - -describe("withLocalNetworkTarget", () => { - afterEach(() => vi.unstubAllGlobals()); - - it("marks http:// requests from an HTTPS page as local", () => { - onPage("https:"); - expect( - withLocalNetworkTarget("http://192.168.1.10", { method: "GET" }), - ).toEqual({ method: "GET", targetAddressSpace: "local" }); - }); - - it.each([ - "http://localhost", - "http://localhost:4403", - "http://127.0.0.1", - "http://[::1]:80", - ])("leaves loopback %s unannotated", (url) => { - onPage("https:"); - expect(withLocalNetworkTarget(url)).toEqual({}); - }); - - it("leaves https:// requests alone", () => { - onPage("https:"); - expect(withLocalNetworkTarget("https://meshtastic.local")).toEqual({}); - }); - - it("leaves requests from an HTTP page alone", () => { - onPage("http:"); - expect(withLocalNetworkTarget("http://meshtastic.local")).toEqual({}); - }); -}); diff --git a/packages/transport-http/src/localNetwork.ts b/packages/transport-http/src/localNetwork.ts deleted file mode 100644 index 9bbd63b72..000000000 --- a/packages/transport-http/src/localNetwork.ts +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Chrome's Local Network Access (enforced from Chrome 142): once the user - * allows a site to reach the local network, its requests to local devices - * are exempt from mixed-content blocking, so an HTTPS page can talk to a - * radio over plain `http://` without a certificate. - * - * Chrome already treats private IP literals and `.local` names as local. - * `targetAddressSpace: "local"` also covers names that look public but - * resolve to the LAN. It is only added to `http://` requests from an HTTPS - * page, the one case where the exemption matters; Chrome rejects such a - * request if the host turns out to be public. Other browsers ignore it. - */ -export function withLocalNetworkTarget( - url: string, - init: RequestInit = {}, -): RequestInit { - if (!url.startsWith("http:") || globalThis.location?.protocol !== "https:") { - return init; - } - // Loopback is its own address space: a "local" target would make Chrome - // reject the request. http://localhost is already trusted, so it needs - // no annotation. - if (isLoopback(url)) return init; - return { ...init, targetAddressSpace: "local" } as RequestInit; -} - -function isLoopback(url: string): boolean { - let host: string; - try { - host = new URL(url).hostname.toLowerCase(); - } catch { - return false; - } - return ( - host === "localhost" || - host.endsWith(".localhost") || - host === "[::1]" || - /^127\.\d+\.\d+\.\d+$/.test(host) - ); -} diff --git a/packages/transport-http/src/transport.test.ts b/packages/transport-http/src/transport.test.ts deleted file mode 100644 index 3f50cc603..000000000 --- a/packages/transport-http/src/transport.test.ts +++ /dev/null @@ -1,247 +0,0 @@ -import { - afterEach, - beforeEach, - describe, - expect, - it, - type MockInstance, - vi, -} from "vitest"; -import { runTransportContract } from "../../../tests/utils/transportContract.ts"; -import { TransportHTTP } from "./transport.ts"; - -let abortTimeoutSpy: MockInstance | undefined; -beforeEach(() => { - abortTimeoutSpy = vi - .spyOn( - globalThis.AbortSignal as unknown as { timeout(ms: number): AbortSignal }, - "timeout", - ) - .mockImplementation((ms: number) => { - const ctrl = new AbortController(); - const abort = () => - ctrl.abort(new DOMException("Timeout reached", "TimeoutError")); - // Uses setTimeout so vi.useFakeTimers() can fast-forward it - setTimeout(abort, ms); - return ctrl.signal; - }); -}); - -afterEach(() => { - abortTimeoutSpy?.mockRestore(); -}); - -function stubFetch() { - const inbox: Uint8Array[] = []; - let lastWritten: ArrayBuffer | undefined; - - let forceNextReadToHang = false; - let forceNextReadToReturn500 = false; - - function makeAbortAwareHang(signal?: AbortSignal): Promise { - return new Promise((_, reject) => { - const abort = () => reject(new DOMException("Aborted", "AbortError")); - if (signal?.aborted) { - abort(); - return; - } - if (signal) { - signal.addEventListener("abort", abort, { once: true }); - } - }); - } - - const mockFetch = vi.fn(async (url: string, init?: RequestInit) => { - const method = (init?.method ?? "GET").toUpperCase(); - - if (url.includes("/api/v1/toradio") && method === "OPTIONS") { - return { ok: true, status: 204 } as Response; - } - - if (url.includes("/api/v1/toradio") && method === "PUT") { - lastWritten = init?.body as ArrayBuffer; - return { ok: true, status: 200 } as Response; - } - - if (url.includes("/api/v1/fromradio") && method === "GET") { - if (forceNextReadToHang) { - forceNextReadToHang = false; - return makeAbortAwareHang(init?.signal ?? undefined); - } - - if (forceNextReadToReturn500) { - forceNextReadToReturn500 = false; - return { - ok: false, - status: 500, - arrayBuffer: async () => new ArrayBuffer(0), - } as Response; - } - - const next = inbox.shift() ?? new Uint8Array(); - return { - ok: true, - status: 200, - arrayBuffer: async () => next.buffer, - } as Response; - } - - return { ok: true, status: 200 } as Response; - }); - - vi.stubGlobal("fetch", mockFetch); - - return { - pushIncoming: (u8: Uint8Array) => inbox.push(u8), - assertLastWritten: (u8: Uint8Array) => { - const got = new Uint8Array(lastWritten || new ArrayBuffer(0)); - expect(got).toEqual(u8); - }, - forceReadErrorOnce: () => { - forceNextReadToReturn500 = true; - }, - forceReadTimeoutOnce: () => { - forceNextReadToHang = true; - }, - getMock: () => mockFetch, - cleanup: () => vi.unstubAllGlobals(), - }; -} - -async function tickNextTimer() { - try { - await vi.advanceTimersToNextTimerAsync(); - } catch { - await new Promise((r) => setTimeout(r, 5)); - } -} - -describe("TransportHTTP (contract)", () => { - runTransportContract({ - name: "TransportHTTP", - setup: () => { - vi.useFakeTimers(); - }, - teardown: () => { - vi.useRealTimers(); - vi.restoreAllMocks(); - vi.unstubAllGlobals(); - }, - create: async () => { - ( - globalThis as unknown as { __http: ReturnType } - ).__http = stubFetch(); - const transport = await TransportHTTP.create("127.0.0.1:80", false); - await tickNextTimer(); - return transport; - }, - pushIncoming: async (bytes) => { - ( - globalThis as unknown as { __http: ReturnType } - ).__http.pushIncoming(bytes); - await tickNextTimer(); - }, - assertLastWritten: (bytes) => { - ( - globalThis as unknown as { __http: ReturnType } - ).__http.assertLastWritten(bytes); - }, - triggerDisconnect: async () => { - ( - globalThis as unknown as { __http: ReturnType } - ).__http.forceReadErrorOnce(); - await tickNextTimer(); - }, - }); -}); - -describe("TransportHTTP (extras)", () => { - let httpStub: ReturnType | undefined; - - beforeEach(() => { - vi.useFakeTimers(); - }); - - afterEach(() => { - vi.useRealTimers(); - vi.restoreAllMocks(); - httpStub?.cleanup(); - httpStub = undefined; - }); - - async function createTransport(): Promise { - httpStub = stubFetch(); - const transport = await TransportHTTP.create("127.0.0.1:80", false); - await tickNextTimer(); - return transport; - } - - async function advanceOnePoll() { - await tickNextTimer(); - } - - it("emits DeviceDisconnected with reason 'read-timeout' when GET /fromradio hangs", async () => { - const transport = await createTransport(); - const reader = transport.fromDevice.getReader(); - - httpStub!.forceReadTimeoutOnce(); - - await tickNextTimer(); - await vi.advanceTimersByTimeAsync(8000); - - let sawReadTimeout = false; - for (let i = 0; i < 6; i++) { - const { value } = await reader.read(); - if (value?.type === "status" && value.data.reason === "read-timeout") { - sawReadTimeout = true; - break; - } - } - expect(sawReadTimeout).toBe(true); - - reader.releaseLock(); - await transport.disconnect(); - }); - - it("stops polling after disconnect()", async () => { - const transport = await createTransport(); - - const fetchMock = httpStub!.getMock(); - const callsBeforeDisconnect = fetchMock.mock.calls.length; - - await transport.disconnect(); - - await advanceOnePoll(); - await vi.runOnlyPendingTimersAsync(); - - const callsAfterDisconnect = fetchMock.mock.calls.length; - expect(callsAfterDisconnect).toBe(callsBeforeDisconnect); - }); - - it("emits DeviceDisconnected with reason 'read-timeout' when GET /fromradio hangs", async () => { - const transport = await createTransport(); - const reader = transport.fromDevice.getReader(); - - httpStub!.forceReadTimeoutOnce(); - - await vi.advanceTimersToNextTimerAsync(); - - await vi.advanceTimersByTimeAsync(8000); - - await Promise.resolve(); - await Promise.resolve(); - - let sawReadTimeout = false; - for (let i = 0; i < 6; i++) { - const { value } = await reader.read(); - if (value?.type === "status" && value.data.reason === "read-timeout") { - sawReadTimeout = true; - break; - } - } - expect(sawReadTimeout).toBe(true); - - reader.releaseLock(); - await transport.disconnect(); - }); -}); diff --git a/packages/transport-http/src/transport.ts b/packages/transport-http/src/transport.ts deleted file mode 100644 index 8054d4988..000000000 --- a/packages/transport-http/src/transport.ts +++ /dev/null @@ -1,253 +0,0 @@ -import { - DeviceStatusEnum, - type DeviceOutput, - type Transport, -} from "@meshtastic/sdk"; -import { withLocalNetworkTarget } from "./localNetwork.ts"; - -const FETCH_INTERVAL_MS = 3000; -const READ_TIMEOUT_MS = 7000; -const WRITE_TIMEOUT_MS = 4000; - -function toArrayBuffer(uint8array: Uint8Array): ArrayBuffer { - if ( - uint8array.buffer instanceof ArrayBuffer && - uint8array.byteOffset === 0 && - uint8array.byteLength === uint8array.buffer.byteLength - ) { - return uint8array.buffer; - } - return uint8array.slice().buffer; -} - -/** - * Provides HTTP(S) transport for Meshtastic devices. - * - * Implements {@link Transport} using the device's HTTP API. - * Polls `/api/v1/fromradio` for incoming packets and writes to `/api/v1/toradio`. - */ -export class TransportHTTP implements Transport { - private _toDevice: WritableStream; - private _fromDevice: ReadableStream; - private fromDeviceController?: ReadableStreamDefaultController; - - private url: string; - private receiveBatchRequests: boolean; - private fetchInterval: number; - private fetching: boolean; - private interval: ReturnType | undefined; - - private inflightReadController?: AbortController; - - private lastStatus: DeviceStatusEnum = DeviceStatusEnum.DeviceDisconnected; - private closingByUser = false; - - /** - * Probe the device and return a connected HTTP transport. - * - * @param address Hostname or IP address (with optional port). - * @param tls Use HTTPS if true, HTTP otherwise. - */ - public static async create( - address: string, - tls?: boolean, - ): Promise { - const connectionUrl = `${tls ? "https" : "http"}://${address}`; - await fetch( - `${connectionUrl}/api/v1/toradio`, - withLocalNetworkTarget(connectionUrl, { method: "OPTIONS" }), - ); - return new TransportHTTP(connectionUrl); - } - - /** - * Construct a new HTTP transport for the given device URL. - * - * @param url Base URL of the device (`http://host:port` or `https://host:port`). - */ - constructor(url: string) { - this.url = url; - this.receiveBatchRequests = false; - this.fetchInterval = FETCH_INTERVAL_MS; - this.fetching = false; - - this._toDevice = new WritableStream({ - write: async (chunk) => { - try { - await this.writeToRadio(chunk); - } catch (error) { - if (!this.closingByUser) { - this.emitStatus( - DeviceStatusEnum.DeviceDisconnected, - this.isTimeoutOrAbort(error) ? "write-timeout" : "write-error", - ); - return; - } - throw error; - } - }, - }); - - this._fromDevice = new ReadableStream({ - start: (ctrl) => { - this.fromDeviceController = ctrl; - this.emitStatus(DeviceStatusEnum.DeviceConnecting); - - // Start polling immediately - void this.safePoll(); - this.interval = setInterval( - () => void this.safePoll(), - this.fetchInterval, - ); - }, - cancel: () => { - if (this.interval) { - clearInterval(this.interval); - } - this.interval = undefined; - }, - }); - } - - /** Poll `/api/v1/fromradio` and enqueue incoming packets. */ - private async readFromRadio(): Promise { - let readBuffer = new ArrayBuffer(1); - - while (readBuffer.byteLength > 0) { - const inflight = new AbortController(); - this.inflightReadController = inflight; - - const signal = AbortSignal.any([ - inflight.signal, - AbortSignal.timeout(READ_TIMEOUT_MS), - ]); - - try { - const response = await fetch( - `${this.url}/api/v1/fromradio?all=${this.receiveBatchRequests ? "true" : "false"}`, - withLocalNetworkTarget(this.url, { - method: "GET", - headers: { Accept: "application/x-protobuf" }, - signal, - }), - ); - if (!response.ok) { - throw new Error( - `fromradio ${response.status} ${response.statusText}`, - ); - } - - this.emitStatus(DeviceStatusEnum.DeviceConnected); - - readBuffer = await response.arrayBuffer(); - - if (readBuffer.byteLength > 0) { - this.fromDeviceController?.enqueue({ - type: "packet", - data: new Uint8Array(readBuffer), - }); - } - } finally { - this.inflightReadController = undefined; - } - } - } - - /** Write a protobuf-encoded request to `/api/v1/toradio`. */ - private async writeToRadio(data: Uint8Array): Promise { - try { - const response = await fetch( - `${this.url}/api/v1/toradio`, - withLocalNetworkTarget(this.url, { - method: "PUT", - headers: { "Content-Type": "application/x-protobuf" }, - body: toArrayBuffer(data), - signal: AbortSignal.timeout(WRITE_TIMEOUT_MS), - }), - ); - if (!response.ok) { - throw new Error(`toradio ${response.status} ${response.statusText}`); - } - } catch (error) { - if (!this.closingByUser) { - this.emitStatus( - DeviceStatusEnum.DeviceDisconnected, - this.isTimeoutOrAbort(error) ? "write-timeout" : "write-error", - ); - return; - } - throw error; - } - } - - /** Writable stream of bytes to the device. */ - get toDevice(): WritableStream { - return this._toDevice; - } - - /** Readable stream of {@link DeviceOutput} from the device. */ - get fromDevice(): ReadableStream { - return this._fromDevice; - } - - /** - * Stop polling and emit `DeviceDisconnected("user")`. - */ - disconnect(): Promise { - this.closingByUser = true; - - if (this.interval) { - clearInterval(this.interval); - } - this.interval = undefined; - this.fetching = false; - - try { - this.inflightReadController?.abort(); - } catch {} - this.inflightReadController = undefined; - - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "user"); - - return Promise.resolve(); - } - - private emitStatus(next: DeviceStatusEnum, reason?: string): void { - if (next === this.lastStatus) { - return; - } - this.lastStatus = next; - this.fromDeviceController?.enqueue({ - type: "status", - data: { status: next, reason }, - }); - } - - private isTimeoutOrAbort(err: unknown): boolean { - return ( - (err instanceof DOMException && - (err.name === "AbortError" || err.name === "TimeoutError")) || - (err instanceof Error && - (err.name === "AbortError" || err.name === "TimeoutError")) - ); - } - - private async safePoll(): Promise { - if (this.fetching) { - return; - } - this.fetching = true; - try { - await this.readFromRadio(); - } catch (error) { - if (!this.closingByUser) { - this.emitStatus( - DeviceStatusEnum.DeviceDisconnected, - this.isTimeoutOrAbort(error) ? "read-timeout" : "read-error", - ); - } - } finally { - this.fetching = false; - } - } -} diff --git a/packages/transport-http/tsconfig.json b/packages/transport-http/tsconfig.json deleted file mode 100644 index b01917932..000000000 --- a/packages/transport-http/tsconfig.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "include": ["mod.ts", "src"] -} diff --git a/packages/transport-node-serial/README.md b/packages/transport-node-serial/README.md deleted file mode 100644 index 7aae82a4f..000000000 --- a/packages/transport-node-serial/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# @meshtastic/transport-node-serial - -[![JSR](https://jsr.io/badges/@meshtastic/transport-node-serial)](https://jsr.io/@meshtastic/transport-node-serial) -[![CI](https://img.shields.io/github/actions/workflow/status/meshtastic/js/ci.yml?branch=master&label=actions&logo=github&color=yellow)](https://github.com/meshtastic/js/actions/workflows/ci.yml) -[![CLA assistant](https://cla-assistant.io/readme/badge/meshtastic/meshtastic.js)](https://cla-assistant.io/meshtastic/meshtastic.js) -[![Fiscal Contributors](https://opencollective.com/meshtastic/tiers/badge.svg?label=Fiscal%20Contributors&color=deeppink)](https://opencollective.com/meshtastic/) -[![Vercel](https://img.shields.io/static/v1?label=Powered%20by&message=Vercel&style=flat&logo=vercel&color=000000)](https://vercel.com?utm_source=meshtastic&utm_campaign=oss) - -## Overview - -`@meshtastic/transport-noden-node` Provides Serial transport (Node) for Meshtastic -devices. Installation instructions are available at -[JSR](https://jsr.io/@meshtastic/transport-node-serial) -[NPM](https://www.npmjs.com/package/@meshtastic/transport-node-serial) - -## Usage - -```ts -import { MeshDevice } from "@meshtastic/sdk"; -import { TransportNodeSerial } from "@meshtastic/transport-node-serial"; - -const transport = await TransportNodeSerial.create("/dev/cu.usbserial-0001"); -const device = new MeshDevice(transport); -``` - -## Stats - -![Alt](https://repobeats.axiom.co/api/embed/5330641586e92a2ec84676fedb98f6d4a7b25d69.svg "Repobeats analytics image") diff --git a/packages/transport-node-serial/mod.ts b/packages/transport-node-serial/mod.ts deleted file mode 100644 index 5aef1978f..000000000 --- a/packages/transport-node-serial/mod.ts +++ /dev/null @@ -1 +0,0 @@ -export { TransportNodeSerial } from "./src/transport.ts"; diff --git a/packages/transport-node-serial/package.json b/packages/transport-node-serial/package.json deleted file mode 100644 index 2a25125ee..000000000 --- a/packages/transport-node-serial/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "name": "@meshtastic/transport-node-serial", - "version": "1.0.0", - "description": "NodeJS-specific serial transport layer for Meshtastic web applications.", - "license": "GPL-3.0-only", - "files": [ - "package.json", - "README.md", - "LICENSE", - "dist" - ], - "type": "module", - "main": "./dist/mod.js", - "module": "./dist/mod.js", - "types": "./dist/mod.d.ts", - "exports": { - ".": "./mod.ts" - }, - "scripts": { - "preinstall": "npx only-allow pnpm", - "prepack": "cp ../../LICENSE ./LICENSE", - "clean": "rm -rf dist LICENSE", - "build:npm": "tsdown", - "publish:npm": "pnpm clean && pnpm build:npm && pnpm publish --access public --no-git-checks", - "prepare:jsr": "rm -rf dist && pnpm dlx pkg-to-jsr", - "publish:jsr": "pnpm run prepack && pnpm prepare:jsr && deno publish --allow-dirty --no-check" - }, - "dependencies": { - "@meshtastic/sdk": "workspace:*", - "serialport": "^13.0.0" - }, - "tsdown": { - "clean": true, - "dts": true, - "entry": "mod.ts", - "format": [ - "esm" - ], - "minify": false, - "report": false, - "sourcemap": false, - "splitting": false, - "target": "esnext", - "treeshake": true - }, - "jsrExclude": [ - "src/**/*.test.ts" - ], - "jsrInclude": [ - "mod.ts", - "src", - "README.md", - "LICENSE" - ] -} diff --git a/packages/transport-node-serial/src/transport.test.ts b/packages/transport-node-serial/src/transport.test.ts deleted file mode 100644 index 81f9ca24f..000000000 --- a/packages/transport-node-serial/src/transport.test.ts +++ /dev/null @@ -1,231 +0,0 @@ -import { Duplex } from "node:stream"; -import * as MeshSDK from "@meshtastic/sdk"; -import { - DeviceStatusEnum, - type DeviceOutput, - toDeviceStream, -} from "@meshtastic/sdk"; -import type { SerialPort } from "serialport"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { runTransportContract } from "../../../tests/utils/transportContract.ts"; -import { TransportNodeSerial } from "./transport.ts"; - -function isStatusEvent( - output: DeviceOutput | undefined, -): output is Extract { - return output !== undefined && output.type === "status"; -} - -class FakeSerialPort extends Duplex { - public lastWritten: Uint8Array | undefined; - - constructor() { - super({ objectMode: false }); - } - - _read() {} - - _write( - chunk: Buffer, - _encoding: BufferEncoding, - callback: (error?: Error | null) => void, - ) { - this.lastWritten = new Uint8Array( - chunk.buffer, - chunk.byteOffset, - chunk.byteLength, - ); - callback(); - } - - pushIncoming(data: Uint8Array) { - const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength); - this.push(buf); - } - - emitErrorOnce(message = "simulated serial error") { - this.emit("error", new Error(message)); - } - - emitClose() { - this.emit("close"); - } - - close() { - this.destroy(); - this.emit("close"); - } -} - -function stubCoreTransforms() { - const toDevice = () => - new TransformStream({ - transform(chunk, controller) { - controller.enqueue(chunk); - }, - }); - - const fromDeviceFactory = () => - new TransformStream({ - transform(chunk, controller) { - controller.enqueue({ type: "packet", data: chunk }); - }, - }); - - // toDeviceStream is a getter - const transform = toDeviceStream; - // biome-ignore lint/suspicious/noExplicitAny: vi.spyOn overloads don't match re-exported module bindings - const sdk = MeshSDK as any; - vi.spyOn(sdk, "toDeviceStream", "get").mockReturnValue( - toDevice as unknown as typeof transform, - ); - - vi.spyOn(sdk, "fromDeviceStream").mockImplementation( - () => - fromDeviceFactory() as unknown as TransformStream< - Uint8Array, - DeviceOutput - >, - ); - - return { - restore: () => vi.restoreAllMocks(), - }; -} - -describe("TransportNodeSerial (contract)", () => { - let transformsStub: { restore: () => void } | undefined; - - beforeEach(() => { - transformsStub = stubCoreTransforms(); - }); - - afterEach(() => { - transformsStub?.restore(); - }); - - runTransportContract({ - name: "TransportNodeSerial", - setup: () => {}, - teardown: () => { - vi.restoreAllMocks(); - }, - create: async () => { - const fakePort = new FakeSerialPort(); - const transport = new TransportNodeSerial( - fakePort as unknown as SerialPort, - ); - await Promise.resolve(); - (globalThis as unknown as { __fakePort: FakeSerialPort }).__fakePort = - fakePort; - return transport; - }, - pushIncoming: async (bytes) => { - ( - globalThis as unknown as { __fakePort: FakeSerialPort } - ).__fakePort.pushIncoming(bytes); - await Promise.resolve(); - }, - assertLastWritten: (bytes) => { - const port = (globalThis as unknown as { __fakePort: FakeSerialPort }) - .__fakePort; - expect(port.lastWritten).toBeDefined(); - expect(port.lastWritten).toEqual(bytes); - }, - triggerDisconnect: async () => { - const fakePort = (globalThis as unknown as { __fakePort: FakeSerialPort }) - .__fakePort; - fakePort.emitErrorOnce("test-disconnect"); - fakePort.emitClose(); - await Promise.resolve(); - }, - }); -}); - -describe("TransportNodeSerial (extras)", () => { - let transformsStub: { restore: () => void } | undefined; - - beforeEach(() => { - transformsStub = stubCoreTransforms(); - }); - - afterEach(() => { - transformsStub?.restore(); - }); - - it("emits DeviceDisconnected with reason 'port-error' on error event", async () => { - const fakePort = new FakeSerialPort(); - const transport = new TransportNodeSerial( - fakePort as unknown as SerialPort, - ); - const reader = transport.fromDevice.getReader(); - - await Promise.resolve(); - - const first = await reader.read(); - expect(isStatusEvent(first.value)).toBe(true); - if (isStatusEvent(first.value)) { - expect(first.value.data.status).toBe(DeviceStatusEnum.DeviceConnecting); - } - - const second = await reader.read(); - expect(isStatusEvent(second.value)).toBe(true); - if (isStatusEvent(second.value)) { - expect(second.value.data.status).toBe(DeviceStatusEnum.DeviceConnected); - } - - fakePort.emitErrorOnce("test-disconnect"); - await Promise.resolve(); - - let sawError = false; - for (let i = 0; i < 6; i++) { - const { value } = await reader.read(); - if (isStatusEvent(value) && value.data.reason === "port-error") { - sawError = true; - break; - } - } - expect(sawError).toBe(true); - - reader.releaseLock(); - await transport.disconnect(); - }); - - it("emits DeviceDisconnected with reason 'port-closed' on close event", async () => { - const fakePort = new FakeSerialPort(); - const transport = new TransportNodeSerial( - fakePort as unknown as SerialPort, - ); - const reader = transport.fromDevice.getReader(); - - await Promise.resolve(); - - const first = await reader.read(); - expect(isStatusEvent(first.value)).toBe(true); - if (isStatusEvent(first.value)) { - expect(first.value.data.status).toBe(DeviceStatusEnum.DeviceConnecting); - } - - const second = await reader.read(); - expect(isStatusEvent(second.value)).toBe(true); - if (isStatusEvent(second.value)) { - expect(second.value.data.status).toBe(DeviceStatusEnum.DeviceConnected); - } - - fakePort.emitClose(); - await Promise.resolve(); - - let sawClosed = false; - for (let i = 0; i < 6; i++) { - const { value } = await reader.read(); - if (isStatusEvent(value) && value.data.reason === "port-closed") { - sawClosed = true; - break; - } - } - expect(sawClosed).toBe(true); - - reader.releaseLock(); - await transport.disconnect(); - }); -}); diff --git a/packages/transport-node-serial/src/transport.ts b/packages/transport-node-serial/src/transport.ts deleted file mode 100644 index bb916714c..000000000 --- a/packages/transport-node-serial/src/transport.ts +++ /dev/null @@ -1,188 +0,0 @@ -import { Readable, Writable } from "node:stream"; -import { - DeviceStatusEnum, - type DeviceOutput, - fromDeviceStream, - toDeviceStream, - type Transport, -} from "@meshtastic/sdk"; -import { SerialPort } from "serialport"; - -/** - * Node.js Serial transport for Meshtastic. - * - * Implements {@link Transport} on top of a Node `SerialPort`. - * Use {@link TransportNodeSerial.create} for a convenient factory, or - * `new TransportNodeSerial(port)` if you already have an open port. - */ -export class TransportNodeSerial implements Transport { - private readonly _toDevice: WritableStream; - private readonly _fromDevice: ReadableStream; - private fromDeviceController?: ReadableStreamDefaultController; - private port: SerialPort | undefined; - private pipePromise?: Promise; - private abortController: AbortController; - private lastStatus: DeviceStatusEnum = DeviceStatusEnum.DeviceDisconnected; - private closingByUser = false; - private errored = false; - - /** - * Creates and connects a new TransportNode instance. - * @param path - Path to the serial device - * @param baudRate - Baud rate for the serial connection (default is 115200). - * @returns A promise that resolves with a connected TransportNode instance. - */ - public static create( - path: string, - baudRate = 115200, - ): Promise { - return new Promise((resolve, reject) => { - const port = new SerialPort({ - path, - baudRate, - autoOpen: true, - }); - - const onError = (err: Error) => { - port.close(); - reject(err); - }; - - port.once("error", onError); - port.on("open", () => { - port.removeListener("error", onError); - resolve(new TransportNodeSerial(port)); - }); - }); - } - - /** - * Constructs a new TransportNode. - * @param port - An active Node.js SerialPort connection. - */ - constructor(port: SerialPort) { - this.port = port; - this.port.on("error", (err) => { - this.errored = true; - this.port?.removeAllListeners(); - this.port?.destroy(); - console.error("Serial port connection error:", err); - if (!this.closingByUser) { - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "port-error"); - } - }); - this.port.on("close", () => { - if (this.closingByUser) { - return; - } - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "port-closed"); - }); - - const fromDeviceSource = Readable.toWeb(port) as ReadableStream; - const transformed = fromDeviceSource.pipeThrough(fromDeviceStream()); - - this.abortController = new AbortController(); - const controller = this.abortController; - - this._fromDevice = new ReadableStream({ - start: async (ctrl) => { - this.fromDeviceController = ctrl; - - this.emitStatus(DeviceStatusEnum.DeviceConnecting); - this.emitStatus(DeviceStatusEnum.DeviceConnected); - - const reader = transformed.getReader(); - try { - while (true) { - const { value, done } = await reader.read(); - if (done) { - break; - } - ctrl.enqueue(value); - } - ctrl.close(); - } catch (error) { - if (this.closingByUser || this.errored) { - ctrl.close(); // graceful EOF on user - } else { - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "read-error"); - ctrl.error( - error instanceof Error ? error : new Error(String(error)), - ); - } - try { - await transformed.cancel(); - } catch {} - } finally { - reader.releaseLock(); - } - }, - }); - - // Stream for data going FROM the application TO the Meshtastic device. - const toDeviceTransform = toDeviceStream(); - this._toDevice = toDeviceTransform.writable; - - this.pipePromise = toDeviceTransform.readable - .pipeTo(Writable.toWeb(port) as WritableStream, { - signal: controller.signal, - }) - .catch((error) => { - if (controller.signal.aborted || this.closingByUser || this.errored) { - return; - } - console.error("Error piping data to serial port:", error); - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "write-error"); - try { - this.port?.close(); - } catch {} - }); - } - - /** - * The WritableStream to send data to the Meshtastic device. - */ - public get toDevice(): WritableStream { - return this._toDevice; - } - - /** - * The ReadableStream to receive data from the Meshtastic device. - */ - public get fromDevice(): ReadableStream { - return this._fromDevice; - } - - /** - * Disconnect from the serial port and emit `DeviceDisconnected("user")`. - * Safe to call multiple times. - */ - async disconnect() { - try { - this.closingByUser = true; - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "user"); - - this.abortController?.abort(); - await this.pipePromise?.catch(() => {}); - - try { - this.port?.close(); - } catch {} - } finally { - this.port = undefined; - this.closingByUser = false; - this.errored = false; - } - } - - private emitStatus(next: DeviceStatusEnum, reason?: string): void { - if (next === this.lastStatus) { - return; - } - this.lastStatus = next; - this.fromDeviceController?.enqueue({ - type: "status", - data: { status: next, reason }, - }); - } -} diff --git a/packages/transport-node-serial/tsconfig.json b/packages/transport-node-serial/tsconfig.json deleted file mode 100644 index 3740512b0..000000000 --- a/packages/transport-node-serial/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "types": ["node"] - }, - "include": ["mod.ts", "src"] -} diff --git a/packages/transport-node/README.md b/packages/transport-node/README.md deleted file mode 100644 index a7e8614cb..000000000 --- a/packages/transport-node/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# @meshtastic/transport-node - -[![JSR](https://jsr.io/badges/@meshtastic/transport-node)](https://jsr.io/@meshtastic/transport-node) -[![CI](https://img.shields.io/github/actions/workflow/status/meshtastic/js/ci.yml?branch=master&label=actions&logo=github&color=yellow)](https://github.com/meshtastic/js/actions/workflows/ci.yml) -[![CLA assistant](https://cla-assistant.io/readme/badge/meshtastic/meshtastic.js)](https://cla-assistant.io/meshtastic/meshtastic.js) -[![Fiscal Contributors](https://opencollective.com/meshtastic/tiers/badge.svg?label=Fiscal%20Contributors&color=deeppink)](https://opencollective.com/meshtastic/) -[![Vercel](https://img.shields.io/static/v1?label=Powered%20by&message=Vercel&style=flat&logo=vercel&color=000000)](https://vercel.com?utm_source=meshtastic&utm_campaign=oss) - -## Overview - -`@meshtastic/transport-node` Provides TCP transport (Node) for Meshtastic -devices. Installation instructions are available at -[JSR](https://jsr.io/@meshtastic/transport-node) -[NPM](https://www.npmjs.com/package/@meshtastic/transport-node) - -## Usage - -```ts -import { MeshDevice } from "@meshtastic/sdk"; -import { TransportNode } from "@meshtastic/transport-node"; - -const transport = await TransportNode.create("10.10.0.57"); -const device = new MeshDevice(transport); -``` - -## Stats - -![Alt](https://repobeats.axiom.co/api/embed/5330641586e92a2ec84676fedb98f6d4a7b25d69.svg "Repobeats analytics image") diff --git a/packages/transport-node/mod.ts b/packages/transport-node/mod.ts deleted file mode 100644 index 37b6657ce..000000000 --- a/packages/transport-node/mod.ts +++ /dev/null @@ -1 +0,0 @@ -export { TransportNode } from "./src/transport.ts"; diff --git a/packages/transport-node/package.json b/packages/transport-node/package.json deleted file mode 100644 index 66d7d5cef..000000000 --- a/packages/transport-node/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@meshtastic/transport-node", - "version": "1.0.0", - "description": "NodeJS-specific transport layer for Meshtastic web applications.", - "license": "GPL-3.0-only", - "files": [ - "package.json", - "README.md", - "LICENSE", - "dist" - ], - "type": "module", - "main": "./dist/mod.js", - "module": "./dist/mod.js", - "types": "./dist/mod.d.ts", - "exports": { - ".": "./mod.ts" - }, - "scripts": { - "preinstall": "npx only-allow pnpm", - "prepack": "cp ../../LICENSE ./LICENSE", - "clean": "rm -rf dist LICENSE", - "build:npm": "tsdown", - "publish:npm": "pnpm clean && pnpm build:npm && pnpm publish --access public --no-git-checks", - "prepare:jsr": "rm -rf dist && pnpm dlx pkg-to-jsr", - "publish:jsr": "pnpm run prepack && pnpm prepare:jsr && deno publish --allow-dirty --no-check" - }, - "dependencies": { - "@meshtastic/sdk": "workspace:*" - }, - "tsdown": { - "clean": true, - "dts": true, - "entry": "mod.ts", - "format": [ - "esm" - ], - "minify": false, - "report": false, - "sourcemap": false, - "splitting": false, - "target": "esnext", - "treeshake": true - }, - "jsrExclude": [ - "src/**/*.test.ts" - ], - "jsrInclude": [ - "mod.ts", - "src", - "README.md", - "LICENSE" - ] -} diff --git a/packages/transport-node/src/transport.test.ts b/packages/transport-node/src/transport.test.ts deleted file mode 100644 index e7288adf5..000000000 --- a/packages/transport-node/src/transport.test.ts +++ /dev/null @@ -1,188 +0,0 @@ -import type { Socket } from "node:net"; -import { Duplex } from "node:stream"; -import * as MeshSDK from "@meshtastic/sdk"; -import { - DeviceStatusEnum, - type DeviceOutput, - toDeviceStream, -} from "@meshtastic/sdk"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { runTransportContract } from "../../../tests/utils/transportContract.ts"; -import { TransportNode } from "./transport.ts"; - -function isStatusEvent( - out: DeviceOutput | undefined, -): out is Extract { - return !!out && (out as any).type === "status"; -} - -class FakeSocket extends Duplex { - public lastWritten: Uint8Array | undefined; - - constructor() { - super({ objectMode: false }); - } - - _read() {} - - _write( - chunk: Buffer, - _encoding: BufferEncoding, - callback: (error?: Error | null) => void, - ) { - this.lastWritten = new Uint8Array( - chunk.buffer, - chunk.byteOffset, - chunk.byteLength, - ); - callback(); - } - - pushIncoming(data: Uint8Array) { - const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength); - this.push(buf); - } - - emitErrorOnce(message = "simulated error") { - this.emit("error", new Error(message)); - } - - emitClose() { - this.emit("close"); - } - - override destroy(error?: Error) { - super.destroy(error); - this.emit("close"); - return this; - } -} - -function stubCoreTransforms() { - const toDevice = () => - new TransformStream({ - transform(chunk, controller) { - controller.enqueue(chunk); - }, - }); - - const fromDeviceFactory = () => - new TransformStream({ - transform(chunk, controller) { - controller.enqueue({ type: "packet", data: chunk }); - }, - }); - - const transform = toDeviceStream; - // biome-ignore lint/suspicious/noExplicitAny: vi.spyOn overloads don't match re-exported module bindings - const sdk = MeshSDK as any; - vi.spyOn(sdk, "toDeviceStream", "get").mockReturnValue( - toDevice as unknown as typeof transform, - ); - - vi.spyOn(sdk, "fromDeviceStream").mockImplementation( - () => - fromDeviceFactory() as unknown as TransformStream< - Uint8Array, - DeviceOutput - >, - ); - - return { - restore: () => vi.restoreAllMocks(), - }; -} - -describe("TransportNode (contract)", () => { - let transformsStub: { restore: () => void } | undefined; - - beforeEach(() => { - transformsStub = stubCoreTransforms(); - }); - - afterEach(() => { - transformsStub?.restore(); - }); - - runTransportContract({ - name: "TransportNode", - setup: () => {}, - teardown: () => { - vi.restoreAllMocks(); - }, - create: async () => { - const fakeSocket = new FakeSocket(); - const transport = new TransportNode(fakeSocket as unknown as Socket); - await Promise.resolve(); - (globalThis as unknown as { __nodeSock: FakeSocket }).__nodeSock = - fakeSocket; - return transport; - }, - pushIncoming: async (bytes) => { - ( - globalThis as unknown as { __nodeSock: FakeSocket } - ).__nodeSock.pushIncoming(bytes); - await Promise.resolve(); - }, - assertLastWritten: (bytes) => { - const sock = (globalThis as unknown as { __nodeSock: FakeSocket }) - .__nodeSock; - expect(sock.lastWritten).toBeDefined(); - expect(sock.lastWritten).toEqual(bytes); - }, - triggerDisconnect: async () => { - ( - globalThis as unknown as { __nodeSock: FakeSocket } - ).__nodeSock.emitErrorOnce("test-disconnect"); - await Promise.resolve(); - }, - }); -}); - -describe("TransportNode (extras)", () => { - let transformsStub: { restore: () => void } | undefined; - - beforeEach(() => { - transformsStub = stubCoreTransforms(); - }); - - afterEach(() => { - transformsStub?.restore(); - }); - - it("emits DeviceDisconnected with reason 'socket-closed' on close event", async () => { - const fakeSocket = new FakeSocket(); - const transport = new TransportNode(fakeSocket as unknown as Socket); - const reader = transport.fromDevice.getReader(); - - await Promise.resolve(); - - const first = await reader.read(); - expect(isStatusEvent(first.value)).toBe(true); - if (isStatusEvent(first.value)) { - expect(first.value.data.status).toBe(DeviceStatusEnum.DeviceConnecting); - } - - const second = await reader.read(); - expect(isStatusEvent(second.value)).toBe(true); - if (isStatusEvent(second.value)) { - expect(second.value.data.status).toBe(DeviceStatusEnum.DeviceConnected); - } - - fakeSocket.emitClose(); - await Promise.resolve(); - - let sawClosed = false; - for (let i = 0; i < 6; i++) { - const { value } = await reader.read(); - if (isStatusEvent(value) && value.data.reason === "socket-closed") { - sawClosed = true; - break; - } - } - expect(sawClosed).toBe(true); - - reader.releaseLock(); - await transport.disconnect(); - }); -}); diff --git a/packages/transport-node/src/transport.ts b/packages/transport-node/src/transport.ts deleted file mode 100644 index b94ec68e3..000000000 --- a/packages/transport-node/src/transport.ts +++ /dev/null @@ -1,205 +0,0 @@ -import { Socket } from "node:net"; -import { Readable, Writable } from "node:stream"; -import { - DeviceStatusEnum, - type DeviceOutput, - fromDeviceStream, - toDeviceStream, - type Transport, -} from "@meshtastic/sdk"; - -/** - * Node.js TCP transport for Meshtastic. - * - * Implements {@link Transport} on top of a Node `net.Socket`. - * Use {@link TransportNode.create} to open a new connection, or - * construct directly with an existing socket. - */ -export class TransportNode implements Transport { - private readonly _toDevice: WritableStream; - private readonly _fromDevice: ReadableStream; - private fromDeviceController?: ReadableStreamDefaultController; - private socket: Socket | undefined; - private pipePromise?: Promise; - private abortController: AbortController; - private lastStatus: DeviceStatusEnum = DeviceStatusEnum.DeviceDisconnected; - - private closingByUser = false; - private errored = false; - - /** - * Creates and connects a new TransportNode instance. - * @param hostname - The IP address or hostname of the Meshtastic device. - * @param port - The port number for the TCP connection (defaults to 4403). - * @param timeout - TCP socket timeout in milliseconds (defaults to 60000). - * @returns A promise that resolves with a connected TransportNode instance. - */ - public static create( - hostname: string, - port = 4403, - timeout = 60000, - ): Promise { - return new Promise((resolve, reject) => { - const socket = new Socket(); - - const onError = (err: Error) => { - socket.destroy(); - socket.removeAllListeners(); - reject(err); - }; - - socket.once("error", onError); - socket.once("ready", () => { - socket.removeListener("error", onError); - resolve(new TransportNode(socket)); - }); - socket.setTimeout(timeout); - socket.connect(port, hostname); - }); - } - - /** - * Constructs a new TransportNode. - * @param connection - An active Node.js net.Socket connection. - */ - constructor(connection: Socket) { - this.socket = connection; - - this.socket.on("error", () => { - this.errored = true; - this.socket?.removeAllListeners(); - this.socket?.destroy(); - if (!this.closingByUser) { - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "socket-error"); - } - }); - - this.socket.on("end", () => { - if (this.closingByUser) { - return; // suppress close-derived disconnect in user flow - } - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "socket-end"); - this.socket?.removeAllListeners(); - this.socket?.destroy(); - }); - - this.socket.on("timeout", () => { - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "socket-timeout"); - this.socket?.removeAllListeners(); - this.socket?.destroy(); - }); - - this.socket.on("close", () => { - if (this.closingByUser) { - return; // suppress close-derived disconnect in user flow - } - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "socket-closed"); - }); - - this.abortController = new AbortController(); - const abortController = this.abortController; - - const fromDeviceSource = Readable.toWeb( - connection, - ) as ReadableStream; - const transformed = fromDeviceSource.pipeThrough(fromDeviceStream()); - - this._fromDevice = new ReadableStream({ - start: async (ctrl) => { - this.fromDeviceController = ctrl; - - this.emitStatus(DeviceStatusEnum.DeviceConnecting); - this.emitStatus(DeviceStatusEnum.DeviceConnected); - - const reader = transformed.getReader(); - try { - while (true) { - const { value, done } = await reader.read(); - if (done) { - break; - } - ctrl.enqueue(value); - } - ctrl.close(); - } catch (error) { - if (this.closingByUser || this.errored) { - ctrl.close(); - } else { - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "read-error"); - - ctrl.error( - error instanceof Error ? error : new Error(String(error)), - ); - } - try { - await transformed.cancel(); - } catch {} - } finally { - reader.releaseLock(); - } - }, - }); - - // Stream for data going FROM the application TO the Meshtastic device. - const toDeviceTransform = toDeviceStream(); - this._toDevice = toDeviceTransform.writable; - - this.pipePromise = toDeviceTransform.readable - .pipeTo(Writable.toWeb(connection) as WritableStream, { - signal: abortController.signal, - }) - .catch((err) => { - if (abortController.signal.aborted || this.socket?.destroyed) { - return; - } - const error = err instanceof Error ? err : new Error(String(err)); - this.socket?.destroy(error); - }); - } - - /** WritableStream to send data to the device. */ - public get toDevice(): WritableStream { - return this._toDevice; - } - - /** ReadableStream to receive data from the device. */ - public get fromDevice(): ReadableStream { - return this._fromDevice; - } - - /** - * Disconnect from the TCP socket and emit `DeviceDisconnected("user")`. - * Safe to call multiple times. - */ - async disconnect(): Promise { - try { - this.closingByUser = true; - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "user"); - - this.abortController.abort(); - if (this.pipePromise) { - await this.pipePromise; - } - this.socket?.destroy(); - } finally { - this.socket = undefined; - this.closingByUser = false; - this.errored = false; - } - } - - private emitStatus(next: DeviceStatusEnum, reason?: string): void { - if (next === this.lastStatus) { - return; - } - this.lastStatus = next; - try { - this.fromDeviceController?.enqueue({ - type: "status", - data: { status: next, reason }, - }); - } catch (e) { - console.error("Enqueue fail", e); - } - } -} diff --git a/packages/transport-node/tsconfig.json b/packages/transport-node/tsconfig.json deleted file mode 100644 index 3740512b0..000000000 --- a/packages/transport-node/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "types": ["node"] - }, - "include": ["mod.ts", "src"] -} diff --git a/packages/transport-web-bluetooth/README.md b/packages/transport-web-bluetooth/README.md deleted file mode 100644 index e755ffc16..000000000 --- a/packages/transport-web-bluetooth/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# @meshtastic/transport-web-bluetooth - -[![JSR](https://jsr.io/badges/@meshtastic/transport-web-bluetooth)](https://jsr.io/@meshtastic/transport-web-bluetooth) -[![CI](https://img.shields.io/github/actions/workflow/status/meshtastic/js/ci.yml?branch=master&label=actions&logo=github&color=yellow)](https://github.com/meshtastic/js/actions/workflows/ci.yml) -[![CLA assistant](https://cla-assistant.io/readme/badge/meshtastic/meshtastic.js)](https://cla-assistant.io/meshtastic/meshtastic.js) -[![Fiscal Contributors](https://opencollective.com/meshtastic/tiers/badge.svg?label=Fiscal%20Contributors&color=deeppink)](https://opencollective.com/meshtastic/) -[![Vercel](https://img.shields.io/static/v1?label=Powered%20by&message=Vercel&style=flat&logo=vercel&color=000000)](https://vercel.com?utm_source=meshtastic&utm_campaign=oss) - -## Overview - -`@meshtastic/transport-web-bluetooth` Provides Web Bluetooth transport for -Meshtastic devices. Installation instructions are available at -[JSR](https://jsr.io/@meshtastic/transport-web-bluetooth) -[NPM](https://www.npmjs.com/org/meshtastic/transport-web-bluetooth) - -## Usage - -```ts -import { MeshDevice } from "@meshtastic/sdk"; -import { TransportWebBluetooth } from "@meshtastic/transport-web-bluetooth"; - -const transport = await TransportWebBluetooth.create(); -const device = new MeshDevice(transport); -``` - -## Stats - -![Alt](https://repobeats.axiom.co/api/embed/5330641586e92a2ec84676fedb98f6d4a7b25d69.svg "Repobeats analytics image") - -### Compatibility - -The Web Bluetooth API's have limited support in browsers, compatibility is -represented in the matrix below. - -![Web Bluetooth compatability matrix](https://caniuse.bitsofco.de/image/web-bluetooth.png) diff --git a/packages/transport-web-bluetooth/mod.ts b/packages/transport-web-bluetooth/mod.ts deleted file mode 100644 index 36e35b999..000000000 --- a/packages/transport-web-bluetooth/mod.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { - BluetoothConnectError, - TransportWebBluetooth, -} from "./src/transport.ts"; diff --git a/packages/transport-web-bluetooth/package.json b/packages/transport-web-bluetooth/package.json deleted file mode 100644 index 46be5249a..000000000 --- a/packages/transport-web-bluetooth/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "name": "@meshtastic/transport-web-bluetooth", - "version": "1.0.0", - "description": "A transport layer for Meshtastic applications using Web Bluetooth.", - "license": "GPL-3.0-only", - "files": [ - "package.json", - "README.md", - "LICENSE", - "dist" - ], - "type": "module", - "main": "./dist/mod.js", - "module": "./dist/mod.js", - "types": "./dist/mod.d.ts", - "exports": { - ".": "./mod.ts" - }, - "scripts": { - "preinstall": "npx only-allow pnpm", - "prepack": "cp ../../LICENSE ./LICENSE", - "clean": "rm -rf dist LICENSE", - "build:npm": "tsdown", - "publish:npm": "pnpm clean && pnpm build:npm && pnpm publish --access public --no-git-checks", - "prepare:jsr": "rm -rf dist && pnpm dlx pkg-to-jsr", - "publish:jsr": "pnpm run prepack && pnpm prepare:jsr && deno publish --allow-dirty --no-check" - }, - "dependencies": { - "@meshtastic/sdk": "workspace:*", - "@types/web-bluetooth": "npm:@types/web-bluetooth@^0.0.21" - }, - "tsdown": { - "clean": true, - "dts": true, - "entry": "mod.ts", - "format": [ - "esm" - ], - "minify": false, - "report": false, - "sourcemap": false, - "splitting": false, - "target": "esnext", - "treeshake": true - }, - "jsrExclude": [ - "src/**/*.test.ts" - ], - "jsrInclude": [ - "mod.ts", - "src", - "README.md", - "LICENSE" - ] -} diff --git a/packages/transport-web-bluetooth/src/transport.test.ts b/packages/transport-web-bluetooth/src/transport.test.ts deleted file mode 100644 index c7825ecab..000000000 --- a/packages/transport-web-bluetooth/src/transport.test.ts +++ /dev/null @@ -1,201 +0,0 @@ -import { describe, expect, vi } from "vitest"; -import { runTransportContract } from "../../../tests/utils/transportContract.ts"; -import { TransportWebBluetooth } from "./transport.ts"; - -class MiniEmitter { - private listeners = new Map void>>(); - addEventListener(type: string, listener: (e: Event) => void) { - if (!this.listeners.has(type)) { - this.listeners.set(type, new Set()); - } - this.listeners.get(type)!.add(listener); - } - removeEventListener(type: string, listener: (e: Event) => void) { - this.listeners.get(type)?.delete(listener); - } - dispatchEvent(event: Event) { - this.listeners.get(event.type)?.forEach((l) => { - l(event); - }); - } -} - -function stubWebBluetooth() { - const incomingQueue: Uint8Array[] = []; - let lastWritten: Uint8Array | undefined; - - // fromRadioCharacteristic: read bytes from queue, one buffer per read - const fromRadioCharacteristic: BluetoothRemoteGATTCharacteristic = { - async readValue() { - const next = incomingQueue.shift() ?? new Uint8Array(); - return new DataView( - next.buffer, - next.byteOffset, - next.byteLength, - ) as unknown as DataView; - }, - addEventListener() {}, - removeEventListener() {}, - } as unknown as BluetoothRemoteGATTCharacteristic; - - // characteristicvaluechanged event plumbing (fromNumCharacteristic) - const charEmitter = new MiniEmitter(); - - const fromNumCharacteristic: BluetoothRemoteGATTCharacteristic = { - async startNotifications() { - return this; - }, - addEventListener(type: string, listener: (e: Event) => void) { - charEmitter.addEventListener(type, listener); - }, - removeEventListener(type: string, listener: (e: Event) => void) { - charEmitter.removeEventListener(type, listener); - }, - } as unknown as BluetoothRemoteGATTCharacteristic; - - const toRadioCharacteristic: BluetoothRemoteGATTCharacteristic = { - async writeValue(bufferSource: BufferSource) { - const u8 = - bufferSource instanceof ArrayBuffer - ? new Uint8Array(bufferSource) - : new Uint8Array( - bufferSource.buffer, - bufferSource.byteOffset, - bufferSource.byteLength, - ); - lastWritten = new Uint8Array(u8); - }, - } as unknown as BluetoothRemoteGATTCharacteristic; - - // Primary service returns our three characteristics by UUID - const primaryService: BluetoothRemoteGATTService = { - async getCharacteristic(uuid: string) { - if (uuid === TransportWebBluetooth.ToRadioUuid) { - return toRadioCharacteristic; - } - if (uuid === TransportWebBluetooth.FromRadioUuid) { - return fromRadioCharacteristic; - } - if (uuid === TransportWebBluetooth.FromNumUuid) { - return fromNumCharacteristic; - } - throw new Error(`Unknown characteristic: ${uuid}`); - }, - } as unknown as BluetoothRemoteGATTService; - - // Device-level emitter to deliver gattserverdisconnected - const deviceEmitter = new MiniEmitter(); - - // GATT server with readonly connected - let isConnected = true; - const gattServer: BluetoothRemoteGATTServer = { - get connected() { - return isConnected; - }, - async connect() { - isConnected = true; - return gattServer; - }, - disconnect() { - isConnected = false; - deviceEmitter.dispatchEvent(new Event("gattserverdisconnected")); - }, - async getPrimaryService() { - return primaryService; - }, - device: { - addEventListener: ( - ...args: Parameters - ) => - deviceEmitter.addEventListener( - args[0] as string, - args[1] as (e: Event) => void, - ), - removeEventListener: ( - ...args: Parameters - ) => - deviceEmitter.removeEventListener( - args[0] as string, - args[1] as (e: Event) => void, - ), - } as unknown as BluetoothDevice, - } as unknown as BluetoothRemoteGATTServer; - - const fakeDevice: BluetoothDevice = { - async watchAdvertisements() {}, - gatt: gattServer, - } as unknown as BluetoothDevice; - - const fakeNavigator = { - bluetooth: { - async requestDevice() { - return fakeDevice; - }, - }, - }; - - vi.stubGlobal( - "navigator", - Object.assign({}, globalThis.navigator, fakeNavigator), - ); - - // helper actions for tests/contract - return { - pushIncoming: (u8: Uint8Array) => { - incomingQueue.push(u8); - charEmitter.dispatchEvent(new Event("characteristicvaluechanged")); - }, - assertLastWritten: (u8: Uint8Array) => { - expect(lastWritten).toBeDefined(); - expect(lastWritten).toEqual(u8); - }, - // simulate underlying link drop (OS-level disconnect) - triggerGattDisconnect: () => { - isConnected = false; - deviceEmitter.dispatchEvent(new Event("gattserverdisconnected")); - }, - cleanup: () => { - vi.unstubAllGlobals(); - }, - }; -} - -describe("TransportWebBluetooth (contract)", () => { - runTransportContract({ - name: "TransportWebBluetooth", - setup: () => {}, - teardown: () => { - ( - globalThis as unknown as { __ble?: ReturnType } - ).__ble?.cleanup(); - ( - globalThis as unknown as { __ble?: ReturnType } - ).__ble = undefined; - vi.restoreAllMocks(); - vi.unstubAllGlobals(); - }, - create: async () => { - ( - globalThis as unknown as { __ble: ReturnType } - ).__ble = stubWebBluetooth(); - return await TransportWebBluetooth.create(); - }, - pushIncoming: async (bytes) => { - ( - globalThis as unknown as { __ble: ReturnType } - ).__ble.pushIncoming(bytes); - await Promise.resolve(); - }, - assertLastWritten: (bytes) => { - ( - globalThis as unknown as { __ble: ReturnType } - ).__ble.assertLastWritten(bytes); - }, - triggerDisconnect: async () => { - ( - globalThis as unknown as { __ble: ReturnType } - ).__ble.triggerGattDisconnect(); - await Promise.resolve(); - }, - }); -}); diff --git a/packages/transport-web-bluetooth/src/transport.ts b/packages/transport-web-bluetooth/src/transport.ts deleted file mode 100644 index 7902b7a16..000000000 --- a/packages/transport-web-bluetooth/src/transport.ts +++ /dev/null @@ -1,341 +0,0 @@ -import { - DeviceStatusEnum, - type DeviceOutput, - type Transport, -} from "@meshtastic/sdk"; - -/** - * Typed error thrown when establishing the GATT connection fails. `kind` - * lets callers distinguish recoverable transients (BT stack hiccup, device - * just woke from sleep) from fatal states (out of range, no service). - * - * `userMessage` is a human-readable, actionable string suitable for - * surfacing in UI without further interpretation. - */ -export class BluetoothConnectError extends Error { - public readonly kind: "transient" | "unavailable" | "missing-service"; - public readonly userMessage: string; - - constructor( - kind: BluetoothConnectError["kind"], - userMessage: string, - options?: { cause?: unknown }, - ) { - super(userMessage, options); - this.name = "BluetoothConnectError"; - this.kind = kind; - this.userMessage = userMessage; - } -} - -function isTransientGattFailure(err: unknown): boolean { - if (!(err instanceof Error)) return false; - if ((err as DOMException).name === "NetworkError") return true; - return /connection attempt failed|gatt/i.test(err.message); -} - -const TRANSIENT_RETRY_DELAY_MS = 750; - -function toArrayBuffer(uint8array: Uint8Array): ArrayBuffer { - if ( - uint8array.buffer instanceof ArrayBuffer && - uint8array.byteOffset === 0 && - uint8array.byteLength === uint8array.buffer.byteLength - ) { - return uint8array.buffer; - } - return uint8array.slice().buffer; -} - -/** - * Provides Web Bluetooth transport for Meshtastic devices. - * - * Implements the {@link Transport} contract using the Web Bluetooth API. - * Use {@link TransportWebBluetooth.create} or {@link TransportWebBluetooth.createFromDevice} - * to construct an instance. - */ -export class TransportWebBluetooth implements Transport { - private _toDevice: WritableStream; - private _fromDevice: ReadableStream; - private fromDeviceController?: ReadableStreamDefaultController; - - private toRadioCharacteristic: BluetoothRemoteGATTCharacteristic; - private fromRadioCharacteristic: BluetoothRemoteGATTCharacteristic; - private fromNumCharacteristic: BluetoothRemoteGATTCharacteristic; - private gattServer: BluetoothRemoteGATTServer; - - private lastStatus: DeviceStatusEnum = DeviceStatusEnum.DeviceDisconnected; - - private closingByUser = false; - private reading = false; - /** UUID for the "toRadio" write characteristic. */ - static ToRadioUuid = "f75c76d2-129e-4dad-a1dd-7866124401e7"; - /** UUID for the "fromRadio" read characteristic. */ - static FromRadioUuid = "2c55e69e-4993-11ed-b878-0242ac120002"; - /** UUID for the "fromNum" notification characteristic. */ - static FromNumUuid = "ed9da18c-a800-4f66-a670-aa7547e34453"; - /** UUID for the Meshtastic GATT service. */ - static ServiceUuid = "6ba1b218-15a8-461f-9fa8-5dcae273eafd"; - - private onGattDisconnected = () => { - if (this.closingByUser) { - return; - } - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "gatt-disconnected"); - }; - private onFromNumChanged = () => { - void this.readFromRadio(); - }; - - /** - * Prompts the user to select a Bluetooth device, connects it, and returns a transport. - */ - public static async create(): Promise { - const device = await navigator.bluetooth.requestDevice({ - filters: [{ services: [TransportWebBluetooth.ServiceUuid] }], - }); - return await TransportWebBluetooth.prepareConnection(device); - } - - /** - * Creates a transport from an existing, user-provided {@link BluetoothDevice}. - */ - public static async createFromDevice( - device: BluetoothDevice, - ): Promise { - return await TransportWebBluetooth.prepareConnection(device); - } - - /** - * Prepares and connects to a {@link BluetoothDevice}, resolving its GATT - * server and characteristics, then returning a transport. - * - * Retries the GATT `connect()` call once on transient failures - * (`NetworkError: Connection attempt failed`) — these are common when - * the device just woke from sleep or the OS BT stack hiccuped. - * - * @throws {BluetoothConnectError} when the GATT connect persistently - * fails, the BluetoothDevice has no `gatt`, or the Meshtastic GATT - * service / characteristics aren't found on the device. - */ - public static async prepareConnection( - device: BluetoothDevice, - ): Promise { - const gattServer = await TransportWebBluetooth.connectGatt(device); - - let service: BluetoothRemoteGATTService; - try { - service = await gattServer.getPrimaryService( - TransportWebBluetooth.ServiceUuid, - ); - } catch (cause) { - throw new BluetoothConnectError( - "missing-service", - "Device does not advertise the Meshtastic GATT service. The firmware may be too old or the device is in another mode.", - { cause }, - ); - } - - const toRadioCharacteristic = await service.getCharacteristic( - TransportWebBluetooth.ToRadioUuid, - ); - const fromRadioCharacteristic = await service.getCharacteristic( - TransportWebBluetooth.FromRadioUuid, - ); - const fromNumCharacteristic = await service.getCharacteristic( - TransportWebBluetooth.FromNumUuid, - ); - - if ( - !toRadioCharacteristic || - !fromRadioCharacteristic || - !fromNumCharacteristic - ) { - throw new BluetoothConnectError( - "missing-service", - "Meshtastic GATT characteristics not found on this device.", - ); - } - - return new TransportWebBluetooth( - toRadioCharacteristic, - fromRadioCharacteristic, - fromNumCharacteristic, - gattServer, - ); - } - - private static async connectGatt( - device: BluetoothDevice, - ): Promise { - if (!device.gatt) { - throw new BluetoothConnectError( - "unavailable", - "Device does not expose a GATT server. Re-pair the device.", - ); - } - try { - const server = await device.gatt.connect(); - if (!server) throw new Error("gatt.connect() returned undefined"); - return server; - } catch (firstErr) { - if (!isTransientGattFailure(firstErr)) { - throw new BluetoothConnectError( - "unavailable", - "Bluetooth connection failed. Make sure the device is in range, powered on, and not connected to a phone or another browser tab.", - { cause: firstErr }, - ); - } - await new Promise((r) => setTimeout(r, TRANSIENT_RETRY_DELAY_MS)); - try { - const server = await device.gatt.connect(); - if (!server) throw new Error("gatt.connect() returned undefined"); - return server; - } catch (retryErr) { - throw new BluetoothConnectError( - "transient", - "Bluetooth connection failed twice. Check the device is in range, powered on, and not paired with a phone or another browser tab. Then click Retry.", - { cause: retryErr }, - ); - } - } - } - - /** - * Create a transport from resolved GATT characteristics and server. - * Prefer using the static factory methods instead. - */ - constructor( - toRadioCharacteristic: BluetoothRemoteGATTCharacteristic, - fromRadioCharacteristic: BluetoothRemoteGATTCharacteristic, - fromNumCharacteristic: BluetoothRemoteGATTCharacteristic, - gattServer: BluetoothRemoteGATTServer, - ) { - this.toRadioCharacteristic = toRadioCharacteristic; - this.fromRadioCharacteristic = fromRadioCharacteristic; - this.fromNumCharacteristic = fromNumCharacteristic; - this.gattServer = gattServer; - - this._fromDevice = new ReadableStream({ - start: async (ctrl) => { - this.fromDeviceController = ctrl; - this.emitStatus(DeviceStatusEnum.DeviceConnecting); - - this.gattServer.device.addEventListener( - "gattserverdisconnected", - this.onGattDisconnected, - ); - - try { - await this.fromNumCharacteristic.startNotifications(); - this.fromNumCharacteristic.addEventListener( - "characteristicvaluechanged", - this.onFromNumChanged, - ); - this.emitStatus(DeviceStatusEnum.DeviceConnected); - // prime once in case data already queued - void this.readFromRadio(); - } catch { - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "notify-failed"); - this.gattServer.device.removeEventListener( - "gattserverdisconnected", - this.onGattDisconnected, - ); - } - }, - }); - - this._toDevice = new WritableStream({ - write: async (chunk) => { - try { - const ab = toArrayBuffer(chunk); - await this.toRadioCharacteristic.writeValue(ab); - void this.readFromRadio(); // ensure we read any response - } catch (error) { - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "write-error"); - throw error; - } - }, - }); - } - - /** Writable stream of bytes to the device. */ - get toDevice(): WritableStream { - return this._toDevice; - } - - /** Readable stream of {@link DeviceOutput} from the device. */ - get fromDevice(): ReadableStream { - return this._fromDevice; - } - - /** - * Closes the GATT connection and emits `DeviceDisconnected("user")`. - */ - disconnect(): Promise { - try { - this.closingByUser = true; - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "user"); - try { - this.fromNumCharacteristic.stopNotifications?.(); - } catch {} - this.fromNumCharacteristic.removeEventListener( - "characteristicvaluechanged", - this.onFromNumChanged, - ); - this.gattServer.device.removeEventListener( - "gattserverdisconnected", - this.onGattDisconnected, - ); - - this.gattServer.disconnect(); - } finally { - this.closingByUser = false; - } - return Promise.resolve(); - } - - private async readFromRadio(): Promise { - if (this.reading) { - return; - } - this.reading = true; - - try { - let hasMoreData = true; - while (hasMoreData && this.fromRadioCharacteristic) { - const value = await this.fromRadioCharacteristic.readValue(); - if (value.byteLength === 0) { - hasMoreData = false; - continue; - } - this.enqueue({ - type: "packet", - data: new Uint8Array(value.buffer), - }); - } - } catch (error) { - if (!this.closingByUser) { - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "read-error"); - } - throw error; - } finally { - this.reading = false; - } - } - - private emitStatus(next: DeviceStatusEnum, reason?: string): void { - if (next === this.lastStatus) { - return; - } - this.lastStatus = next; - this.fromDeviceController?.enqueue({ - type: "status", - data: { status: next, reason }, - }); - } - - private enqueue(output: DeviceOutput): void { - this.fromDeviceController?.enqueue(output); - } -} diff --git a/packages/transport-web-bluetooth/tsconfig.json b/packages/transport-web-bluetooth/tsconfig.json deleted file mode 100644 index 6f71c0d82..000000000 --- a/packages/transport-web-bluetooth/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "types": ["@types/web-bluetooth"] - }, - "include": ["mod.ts", "src"] -} diff --git a/packages/transport-web-serial/README.md b/packages/transport-web-serial/README.md deleted file mode 100644 index 13981f4a9..000000000 --- a/packages/transport-web-serial/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# @meshtastic/transport-web-serial - -[![JSR](https://jsr.io/badges/@meshtastic/transport-web-serial)](https://jsr.io/@meshtastic/transport-web-serial) -[![CI](https://img.shields.io/github/actions/workflow/status/meshtastic/js/ci.yml?branch=master&label=actions&logo=github&color=yellow)](https://github.com/meshtastic/js/actions/workflows/ci.yml) -[![CLA assistant](https://cla-assistant.io/readme/badge/meshtastic/meshtastic.js)](https://cla-assistant.io/meshtastic/meshtastic.js) -[![Fiscal Contributors](https://opencollective.com/meshtastic/tiers/badge.svg?label=Fiscal%20Contributors&color=deeppink)](https://opencollective.com/meshtastic/) -[![Vercel](https://img.shields.io/static/v1?label=Powered%20by&message=Vercel&style=flat&logo=vercel&color=000000)](https://vercel.com?utm_source=meshtastic&utm_campaign=oss) - -## Overview - -`@meshtastic/transport-web-serial` Provides Web Serial transport for Meshtastic -devices. Installation instructions are avaliable at -[JSR](https://jsr.io/@meshtastic/transport-web-serial) -[NPM](https://www.npmjs.com/package/@meshtastic/transport-web-serial) - -## Usage - -```ts -import { MeshDevice } from "@meshtastic/sdk"; -import { TransportWebSerial } from "@meshtastic/transport-web-serial"; - -const transport = await TransportWebSerial.create(); -const device = new MeshDevice(transport); -``` - -## Stats - -![Alt](https://repobeats.axiom.co/api/embed/5330641586e92a2ec84676fedb98f6d4a7b25d69.svg "Repobeats analytics image") - -### Compatibility - -The Web Serial API's have limited support in browsers, compatibility is -represented in the matrix below. - -![Web Serial compatability matrix](https://caniuse.bitsofco.de/image/web-serial.png) diff --git a/packages/transport-web-serial/mod.ts b/packages/transport-web-serial/mod.ts deleted file mode 100644 index 3e92415b4..000000000 --- a/packages/transport-web-serial/mod.ts +++ /dev/null @@ -1 +0,0 @@ -export { SerialConnectError, TransportWebSerial } from "./src/transport.ts"; diff --git a/packages/transport-web-serial/package.json b/packages/transport-web-serial/package.json deleted file mode 100644 index 3be18d7f1..000000000 --- a/packages/transport-web-serial/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "name": "@meshtastic/transport-web-serial", - "version": "1.0.0", - "description": "A transport layer for Meshtastic applications using Web Serial API.", - "license": "GPL-3.0-only", - "files": [ - "package.json", - "README.md", - "LICENSE", - "dist" - ], - "type": "module", - "main": "./dist/mod.js", - "module": "./dist/mod.js", - "types": "./dist/mod.d.ts", - "exports": { - ".": "./mod.ts" - }, - "scripts": { - "preinstall": "npx only-allow pnpm", - "prepack": "cp ../../LICENSE ./LICENSE", - "clean": "rm -rf dist LICENSE", - "build:npm": "tsdown", - "publish:npm": "pnpm clean && pnpm build:npm && pnpm publish --access public --no-git-checks", - "prepare:jsr": "rm -rf dist && pnpm dlx pkg-to-jsr", - "publish:jsr": "pnpm run prepack && pnpm prepare:jsr && deno publish --allow-dirty --no-check" - }, - "dependencies": { - "@meshtastic/sdk": "workspace:*", - "@types/w3c-web-serial": "npm:@types/w3c-web-serial@^1.0.8", - "better-result": "^3.0.1" - }, - "tsdown": { - "clean": true, - "dts": true, - "entry": "mod.ts", - "format": [ - "esm" - ], - "minify": false, - "report": false, - "sourcemap": false, - "splitting": false, - "target": "esnext", - "treeshake": true - }, - "jsrExclude": [ - "src/**/*.test.ts" - ], - "jsrInclude": [ - "mod.ts", - "src", - "README.md", - "LICENSE" - ] -} diff --git a/packages/transport-web-serial/src/transport.test.ts b/packages/transport-web-serial/src/transport.test.ts deleted file mode 100644 index 2aeae1cdb..000000000 --- a/packages/transport-web-serial/src/transport.test.ts +++ /dev/null @@ -1,371 +0,0 @@ -import * as MeshSDK from "@meshtastic/sdk"; -import { - DeviceStatusEnum, - type DeviceOutput, - toDeviceStream, -} from "@meshtastic/sdk"; -import { Result } from "better-result"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { runTransportContract } from "../../../tests/utils/transportContract.ts"; -import { SerialConnectError, TransportWebSerial } from "./transport.ts"; - -function stubCoreTransforms() { - const toDevice = () => - new TransformStream({ - transform(chunk, controller) { - controller.enqueue(chunk); - }, - }); - - // maps raw bytes -> DeviceOutput.packet - const fromDeviceFactory = () => - new TransformStream({ - transform(chunk, controller) { - controller.enqueue({ type: "packet", data: chunk }); - }, - }); - - const transform = toDeviceStream; - // biome-ignore lint/suspicious/noExplicitAny: vi.spyOn's overloads on a re-exported module binding don't match - const sdk = MeshSDK as any; - const restoreTo = vi - .spyOn(sdk, "toDeviceStream", "get") - .mockReturnValue(toDevice as unknown as typeof transform); - - const restoreFrom = vi - .spyOn(sdk, "fromDeviceStream") - .mockImplementation( - () => - fromDeviceFactory() as unknown as TransformStream< - Uint8Array, - DeviceOutput - >, - ); - - return { - restore: () => { - restoreTo.mockRestore(); - restoreFrom.mockRestore(); - }, - }; -} - -function stubNavigatorSerial() { - type SerialDisconnectHandler = (ev: { port?: any }) => void; - const handlers = new Set(); - - const serialStub = { - addEventListener: ( - type: string, - handler: EventListenerOrEventListenerObject, - ) => { - if (type === "disconnect") { - handlers.add(handler as any as SerialDisconnectHandler); - } - }, - removeEventListener: ( - type: string, - handler: EventListenerOrEventListenerObject, - ) => { - if (type === "disconnect") { - handlers.delete(handler as any as SerialDisconnectHandler); - } - }, - dispatchDisconnect(port: any) { - for (const h of handlers) { - h({ port }); - } - }, - requestPort: vi.fn(async () => new FakeSerialPort()), - }; - - const nav: any = (globalThis as any).navigator ?? {}; - const hadNavigator = !!(globalThis as any).navigator; - const originalSerial = nav.serial; - - if (!hadNavigator) { - Object.defineProperty(globalThis as any, "navigator", { - value: nav, - configurable: true, - writable: false, - }); - } - - Object.defineProperty(nav, "serial", { - value: serialStub, - configurable: true, - enumerable: true, - writable: true, - }); - - return { - serialStub, - restore: () => { - if (hadNavigator) { - if (originalSerial === undefined) { - delete (globalThis as any).navigator.serial; - } else { - Object.defineProperty((globalThis as any).navigator, "serial", { - value: originalSerial, - configurable: true, - enumerable: true, - writable: true, - }); - } - } else { - delete (globalThis as any).navigator; - } - }, - }; -} - -class FakeSerialPort { - // Mirrors the Web Serial spec: streams are null until `open()` resolves - // and become null again after `close()`. preparePort relies on this to - // decide whether the port is currently open. - readable: ReadableStream | null = null; - writable: WritableStream | null = null; - lastWritten?: Uint8Array; - - private _readController!: ReadableStreamDefaultController; - - constructor() { - this.openStreams(); - } - - private openStreams(): void { - this.readable = new ReadableStream({ - start: (controller) => { - this._readController = controller; - }, - }); - this.writable = new WritableStream({ - write: async (chunk) => { - this.lastWritten = chunk; - }, - }); - } - - open(_options?: { baudRate?: number }): Promise { - if (!this.readable || !this.writable) { - this.openStreams(); - } - return Promise.resolve(); - } - - close(): Promise { - try { - this._readController.close(); - } catch {} - this.readable = null; - this.writable = null; - return Promise.resolve(); - } - - pushIncoming(bytes: Uint8Array) { - this._readController.enqueue(bytes); - } -} - -describe("TransportWebSerial (contract)", () => { - let transforms: { restore(): void } | undefined; - let navSerial: { serialStub: any; restore(): void } | undefined; - - beforeEach(() => { - transforms = stubCoreTransforms(); - navSerial = stubNavigatorSerial(); - }); - - afterEach(() => { - transforms?.restore(); - navSerial?.restore(); - vi.restoreAllMocks(); - }); - - runTransportContract({ - name: "TransportWebSerial", - setup: () => {}, - teardown: () => {}, - create: async () => { - const fake = new FakeSerialPort(); - const result = await TransportWebSerial.createFromPort(fake as any); - const transport = result.unwrap(); - (globalThis as any).__ws = { fake, serial: navSerial!.serialStub }; - await Promise.resolve(); - return transport; - }, - pushIncoming: async (bytes) => { - (globalThis as any).__ws.fake.pushIncoming(bytes); - await Promise.resolve(); - }, - assertLastWritten: (bytes) => { - expect((globalThis as any).__ws.fake.lastWritten).toEqual(bytes); - }, - triggerDisconnect: async () => { - (globalThis as any).__ws.serial.dispatchDisconnect( - (globalThis as any).__ws.fake, - ); - await Promise.resolve(); - }, - }); -}); - -describe("TransportWebSerial (extras)", () => { - let transforms: { restore(): void } | undefined; - let navSerial: { serialStub: any; restore(): void } | undefined; - - beforeEach(() => { - transforms = stubCoreTransforms(); - navSerial = stubNavigatorSerial(); - }); - - afterEach(() => { - transforms?.restore(); - navSerial?.restore(); - vi.restoreAllMocks(); - }); - - it("emits DeviceDisconnected('serial-disconnected') on OS disconnect event", async () => { - const fake = new FakeSerialPort(); - const result = await TransportWebSerial.createFromPort(fake as any); - const transport = result.unwrap(); - (globalThis as any).__ws = { fake, serial: navSerial!.serialStub }; - - const reader = transport.fromDevice.getReader(); - - // drain statuses until connected - for (let i = 0; i < 3; i++) { - const { value } = await reader.read(); - if (!value || value.type !== "status") { - break; - } - if (value.data.status === DeviceStatusEnum.DeviceConnected) { - break; - } - } - - // fire OS-level disconnect - navSerial!.serialStub.dispatchDisconnect(fake as any); - await Promise.resolve(); - - let saw = false; - for (let i = 0; i < 6; i++) { - const { value } = await reader.read(); - if ( - value?.type === "status" && - value.data.reason === "serial-disconnected" - ) { - saw = true; - break; - } - } - expect(saw).toBe(true); - - reader.releaseLock(); - await transport.disconnect(); - }); -}); - -describe("TransportWebSerial.createFromPort port hygiene", () => { - let transforms: { restore(): void } | undefined; - let navSerial: { serialStub: any; restore(): void } | undefined; - - beforeEach(() => { - transforms = stubCoreTransforms(); - navSerial = stubNavigatorSerial(); - }); - - afterEach(() => { - transforms?.restore(); - navSerial?.restore(); - vi.restoreAllMocks(); - }); - - it("force-closes a port that's still open from a prior session", async () => { - const fake = new FakeSerialPort(); - // Streams are non-null right after construction — simulate "previous - // session left it open". preparePort should close + reopen rather - // than barfing on the already-open state. - expect(fake.readable).not.toBeNull(); - const closeSpy = vi.spyOn(fake, "close"); - const result = await TransportWebSerial.createFromPort(fake as any); - expect(Result.isOk(result)).toBe(true); - expect(closeSpy).toHaveBeenCalledTimes(1); - if (Result.isOk(result)) await result.value.disconnect(); - }); - - it("opens with a large read buffer, asserts DTR/RTS and sends wake bytes", async () => { - const fake = new FakeSerialPort(); - await fake.close(); - const openSpy = vi.spyOn(fake, "open"); - const setSignals = vi.fn().mockResolvedValue(undefined); - (fake as any).setSignals = setSignals; - - const result = await TransportWebSerial.createFromPort(fake as any); - - expect(Result.isOk(result)).toBe(true); - expect(openSpy).toHaveBeenCalledWith({ - baudRate: 115200, - bufferSize: 64 * 1024, - }); - expect(setSignals).toHaveBeenCalledWith({ - dataTerminalReady: true, - requestToSend: true, - }); - expect(Array.from(fake.lastWritten ?? [])).toEqual([ - 0x94, 0x94, 0x94, 0x94, - ]); - if (Result.isOk(result)) await result.value.disconnect(); - }); - - it("still connects when the adapter rejects setSignals", async () => { - const fake = new FakeSerialPort(); - await fake.close(); - (fake as any).setSignals = vi.fn().mockRejectedValue(new Error("nope")); - - const result = await TransportWebSerial.createFromPort(fake as any); - - expect(Result.isOk(result)).toBe(true); - if (Result.isOk(result)) await result.value.disconnect(); - }); - - it("retries open() with backoff on InvalidStateError", async () => { - const fake = new FakeSerialPort(); - await fake.close(); - let attempts = 0; - vi.spyOn(fake, "open").mockImplementation(async () => { - attempts += 1; - if (attempts < 3) { - const err = new Error("Failed to open serial port") as Error & { - name: string; - }; - err.name = "InvalidStateError"; - throw err; - } - // 3rd attempt succeeds — recreate streams as the real port would. - (fake as any).openStreams(); - }); - const result = await TransportWebSerial.createFromPort(fake as any); - expect(attempts).toBe(3); - expect(Result.isOk(result)).toBe(true); - if (Result.isOk(result)) await result.value.disconnect(); - }); - - it("returns Err(kind=in-use) when open() keeps throwing InvalidStateError", async () => { - const fake = new FakeSerialPort(); - await fake.close(); - vi.spyOn(fake, "open").mockImplementation(async () => { - const err = new Error("Failed to open serial port") as Error & { - name: string; - }; - err.name = "InvalidStateError"; - throw err; - }); - const result = await TransportWebSerial.createFromPort(fake as any); - expect(Result.isError(result)).toBe(true); - if (Result.isError(result)) { - expect(result.error).toBeInstanceOf(SerialConnectError); - expect(result.error.kind).toBe("in-use"); - } - }); -}); diff --git a/packages/transport-web-serial/src/transport.ts b/packages/transport-web-serial/src/transport.ts deleted file mode 100644 index ec35a2da9..000000000 --- a/packages/transport-web-serial/src/transport.ts +++ /dev/null @@ -1,439 +0,0 @@ -import { - createLogger, - DeviceStatusEnum, - type DeviceOutput, - fromDeviceStream, - toDeviceStream, - type Transport, -} from "@meshtastic/sdk"; -import { Result } from "better-result"; - -const log = createLogger("TransportWebSerial"); - -/** - * Typed error produced when preparing a `SerialPort` for use fails. `kind` - * lets callers distinguish recoverable cases (port held briefly during - * USB re-enumeration) from fatal ones (another tab or process owns the - * port). `userMessage` is a human-readable, actionable string ready for - * UI without further interpretation. - */ -export class SerialConnectError extends Error { - public readonly kind: "in-use" | "busy" | "unavailable"; - public readonly userMessage: string; - - constructor( - kind: SerialConnectError["kind"], - userMessage: string, - options?: { cause?: unknown }, - ) { - super(userMessage, options); - this.name = "SerialConnectError"; - this.kind = kind; - this.userMessage = userMessage; - } -} - -const PORT_OPEN_RETRY_DELAYS_MS = [250, 500, 750] as const; -const POST_CLOSE_DELAY_MS = 200; -/** - * Read buffer for the port. Web Serial's default (255 bytes) holds one or two - * NodeInfo frames, so a busy main thread during the NodeDB download stalls - * reads and native-USB boards (ESP32-S3) drop frames. - */ -const READ_BUFFER_SIZE = 64 * 1024; -/** Sent before the handshake so a sleeping radio starts listening (as Android does). */ -const WAKE_BYTES = new Uint8Array([0x94, 0x94, 0x94, 0x94]); - -function isPortBusyError(err: unknown): boolean { - if (!(err instanceof Error)) return false; - if ((err as DOMException).name === "InvalidStateError") return true; - return /already open|failed to open serial port|access is denied/i.test( - err.message, - ); -} - -/** - * Provides Web Serial transport for Meshtastic devices. - * - * Implements the {@link Transport} contract using the Web Serial API. - * Use {@link TransportWebSerial.create} or {@link TransportWebSerial.createFromPort} - * to construct an instance. - */ -export class TransportWebSerial implements Transport { - private _toDevice: WritableStream; - private _fromDevice: ReadableStream; - private fromDeviceController?: ReadableStreamDefaultController; - private connection: SerialPort; - private pipePromise: Promise | null = null; - private abortController: AbortController; - private portReadable: ReadableStream; - - private lastStatus: DeviceStatusEnum = DeviceStatusEnum.DeviceDisconnected; - private closingByUser = false; - - /** - * Prompt the user to pick a serial port and open a transport on it. - * Returns `Err` on permission denial or open failure rather than - * throwing — callers don't need a try/catch. - */ - public static async create( - baudRate?: number, - ): Promise> { - let port: SerialPort; - try { - port = await navigator.serial.requestPort(); - } catch (cause) { - return Result.err( - new SerialConnectError("unavailable", "Serial port not selected.", { - cause, - }), - ); - } - return TransportWebSerial.createFromPort(port, baudRate); - } - - /** - * Open a transport on an already-known {@link SerialPort}. Performs the - * port-state hygiene needed for reconnect flows: - * - * - If `readable` / `writable` are non-null (port still open from a - * previous session), close it and wait for the descriptor to settle. - * - Try `port.open()` up to four times with backoff on - * `InvalidStateError` — common during USB re-enumeration. - * - * Returns `Err(SerialConnectError)` on persistent failure; the kind - * distinguishes "port owned by another tab/process" (`in-use`) from - * "transient busy / could not open" (`busy`) from - * "permission denied / no streams" (`unavailable`). - */ - public static async createFromPort( - port: SerialPort, - baudRate?: number, - ): Promise> { - const prep = await TransportWebSerial.preparePort(port, baudRate ?? 115200); - if (Result.isError(prep)) return Result.err(prep.error); - try { - return Result.ok(new TransportWebSerial(port)); - } catch (cause) { - return Result.err( - new SerialConnectError( - "unavailable", - "Serial port opened but its read / write streams are not accessible. Re-plug the device and try again.", - { cause }, - ), - ); - } - } - - /** - * Assert DTR and RTS together, as Android does for native-USB boards - * (toggling them one at a time can reset an ESP32), then send the wake - * bytes. Failures are logged, not fatal: some adapters reject signals. - */ - private static async wakeDevice(port: SerialPort): Promise { - try { - await port.setSignals({ dataTerminalReady: true, requestToSend: true }); - } catch (err) { - log.warn("wakeDevice: setSignals failed", { - message: (err as Error)?.message, - }); - } - if (!port.writable) return; - const writer = port.writable.getWriter(); - try { - await writer.write(WAKE_BYTES); - } catch (err) { - log.warn("wakeDevice: wake bytes failed", { - message: (err as Error)?.message, - }); - } finally { - writer.releaseLock(); - } - } - - private static async preparePort( - port: SerialPort, - baudRate: number, - ): Promise> { - log.debug("preparePort: enter", { - readable: !!port.readable, - writable: !!port.writable, - baudRate, - }); - - if (port.readable || port.writable) { - log.debug("preparePort: port has live streams, closing"); - try { - await port.close(); - log.debug("preparePort: close() ok"); - } catch (cause) { - const err = cause as Error; - log.warn("preparePort: close() threw", { - name: err?.name, - message: err?.message, - }); - return Result.err( - new SerialConnectError( - "in-use", - "Serial port is open and could not be released. Close any other tab, terminal, or app using it (Arduino IDE, screen, picocom, esptool) and try again.", - { cause }, - ), - ); - } - await new Promise((r) => setTimeout(r, POST_CLOSE_DELAY_MS)); - } - - let lastErr: unknown; - for ( - let attempt = 0; - attempt <= PORT_OPEN_RETRY_DELAYS_MS.length; - attempt++ - ) { - try { - log.debug("preparePort: open() attempt", { attempt }); - await port.open({ baudRate, bufferSize: READ_BUFFER_SIZE }); - log.debug("preparePort: open() ok", { attempt }); - await TransportWebSerial.wakeDevice(port); - return Result.ok(true); - } catch (err) { - lastErr = err; - const e = err as Error; - log.warn("preparePort: open() threw", { - attempt, - name: e?.name, - message: e?.message, - willRetry: - isPortBusyError(err) && attempt < PORT_OPEN_RETRY_DELAYS_MS.length, - }); - if ( - !isPortBusyError(err) || - attempt === PORT_OPEN_RETRY_DELAYS_MS.length - ) - break; - await new Promise((r) => - setTimeout(r, PORT_OPEN_RETRY_DELAYS_MS[attempt]), - ); - } - } - - const e = lastErr as Error | undefined; - log.error("preparePort: failed", { name: e?.name, message: e?.message }); - - if (isPortBusyError(lastErr)) { - return Result.err( - new SerialConnectError( - "in-use", - "Serial port is busy. Another tab, terminal, or app is holding it (Arduino IDE, screen, picocom, esptool, Meshtastic CLI). Close it and try again.", - { cause: lastErr }, - ), - ); - } - return Result.err( - new SerialConnectError( - "busy", - "Could not open the serial port. Re-plug the device and try again.", - { cause: lastErr }, - ), - ); - } - - /** - * Constructs a transport around a given {@link SerialPort}. - * @throws If the port lacks readable or writable streams. - */ - constructor(connection: SerialPort) { - if (!connection.readable || !connection.writable) { - throw new Error("Stream not accessible"); - } - - this.connection = connection; - this.portReadable = connection.readable; - this.abortController = new AbortController(); - const abortController = this.abortController; - - log.debug("constructor: wiring pipe + reader"); - - // Set up the pipe with abort signal for clean cancellation - const toDeviceTransform = toDeviceStream(); - this.pipePromise = toDeviceTransform.readable - .pipeTo(connection.writable, { signal: this.abortController.signal }) - .catch((err) => { - // Ignore expected rejection when we cancel it via the AbortController. - if (abortController.signal.aborted) { - log.debug("toDevice pipe aborted (expected)"); - return; - } - const e = err as Error; - log.error("toDevice pipe rejected", { - name: e?.name, - message: e?.message, - }); - this.connection.close().catch(() => {}); - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "write-error"); - }); - - this._toDevice = toDeviceTransform.writable; - - // Wrap + capture controller to inject status packets - this._fromDevice = new ReadableStream({ - start: async (ctrl) => { - this.fromDeviceController = ctrl; - - this.emitStatus(DeviceStatusEnum.DeviceConnecting); - - const transformed = this.portReadable.pipeThrough(fromDeviceStream()); - const reader = transformed.getReader(); - - const onOsDisconnect = (ev: Event) => { - const { port } = ev as unknown as { port?: SerialPort }; - if (port && port === this.connection) { - log.warn("OS-level disconnect event"); - this.emitStatus( - DeviceStatusEnum.DeviceDisconnected, - "serial-disconnected", - ); - } - }; - navigator.serial.addEventListener("disconnect", onOsDisconnect); - - log.debug("read loop starting"); - this.emitStatus(DeviceStatusEnum.DeviceConnected); - - try { - while (true) { - const { value, done } = await reader.read(); - if (done) { - log.debug("read loop: done=true"); - break; - } - ctrl.enqueue(value); - } - ctrl.close(); - } catch (error) { - const e = error as Error; - log.warn("read loop threw", { - closingByUser: this.closingByUser, - name: e?.name, - message: e?.message, - }); - if (!this.closingByUser) { - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "read-error"); - } - ctrl.error(error instanceof Error ? error : new Error(String(error))); - try { - await transformed.cancel(); - } catch {} - } finally { - reader.releaseLock(); - navigator.serial.removeEventListener("disconnect", onOsDisconnect); - log.debug("read loop: released reader lock + listener"); - } - }, - }); - } - - /** Writable stream of bytes to the device. */ - public get toDevice(): WritableStream { - return this._toDevice; - } - - /** Readable stream of {@link DeviceOutput} from the device. */ - public get fromDevice(): ReadableStream { - return this._fromDevice; - } - - private emitStatus(next: DeviceStatusEnum, reason?: string): void { - if (next === this.lastStatus) { - return; - } - this.lastStatus = next; - this.fromDeviceController?.enqueue({ - type: "status", - data: { status: next, reason }, - }); - } - - /** - * Closes the serial port and emits `DeviceDisconnected("user")`. - */ - public async disconnect(): Promise { - log.debug("disconnect: enter"); - try { - this.closingByUser = true; - - // Stop outbound piping - this.abortController.abort(); - log.debug("disconnect: aborted toDevice pipe"); - if (this.pipePromise) { - await this.pipePromise; - log.debug("disconnect: pipePromise settled"); - } - - // Cancel any remaining streams - if (this._fromDevice?.locked) { - try { - await this._fromDevice.cancel(); - log.debug("disconnect: cancelled fromDevice"); - } catch (e) { - const err = e as Error; - log.warn("disconnect: fromDevice.cancel() threw", { - name: err?.name, - message: err?.message, - }); - } - } - - await this.connection.close(); - log.debug("disconnect: connection.close() ok"); - } catch (error) { - const e = error as Error; - log.warn("disconnect: cleanup failed", { - name: e?.name, - message: e?.message, - }); - } finally { - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "user"); - this.closingByUser = false; - log.debug("disconnect: done"); - } - } - - /** - * Reconnects the transport by creating a new AbortController and re-establishing - * the pipe connection. Only call this after disconnect() or if the connection failed. - */ - public async reconnect() { - this.emitStatus(DeviceStatusEnum.DeviceConnecting, "reconnect"); - - try { - if (!this.connection.readable || !this.connection.writable) { - throw new Error("Stream not accessible"); - } - this.portReadable = this.connection.readable; - - // Create a new AbortController for the new connection - this.abortController = new AbortController(); - const abortController = this.abortController; - - // Re-establish the pipe connection - const toDeviceTransform = toDeviceStream(); - this.pipePromise = toDeviceTransform.readable - .pipeTo(this.connection.writable, { - signal: this.abortController.signal, - }) - .catch((error) => { - if (abortController.signal.aborted) { - return; - } - console.error("Error piping data to serial port (reconnect):", error); - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "write-error"); - }); - - this.emitStatus(DeviceStatusEnum.DeviceConnected, "reconnected"); - } catch (error) { - // Couldn’t re-pipe - this.emitStatus(DeviceStatusEnum.DeviceDisconnected, "reconnect-failed"); - throw error; - } - } -} diff --git a/packages/transport-web-serial/tsconfig.json b/packages/transport-web-serial/tsconfig.json deleted file mode 100644 index 4d7c655d9..000000000 --- a/packages/transport-web-serial/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "types": ["@types/w3c-web-serial"] - }, - "include": ["mod.ts", "src"] -} diff --git a/tests/utils/transportContract.ts b/tests/utils/transportContract.ts deleted file mode 100644 index 02a45b9df..000000000 --- a/tests/utils/transportContract.ts +++ /dev/null @@ -1,126 +0,0 @@ -import { - DeviceStatusEnum, - type DeviceOutput, - type Transport, -} from "@meshtastic/sdk"; -import { describe, expect, it } from "vitest"; - -export interface TransportContract { - name: string; - create: () => Promise; - setup?: () => void | Promise; - teardown?: () => void | Promise; - pushIncoming?: (bytes: Uint8Array) => void | Promise; - assertLastWritten?: (bytes: Uint8Array) => void; - triggerDisconnect?: () => void | Promise; -} - -async function readUntilType( - reader: ReadableStreamDefaultReader, - expectedType: DeviceOutput["type"], - maxReads = 20, -): Promise { - for (let i = 0; i < maxReads; i++) { - const { value, done } = await reader.read(); - if (done) { - break; - } - if (value && value.type === expectedType) { - return value; - } - } - throw new Error( - `Did not receive a '${expectedType}' event within ${maxReads} reads`, - ); -} - -export function runTransportContract(contract: TransportContract) { - describe(contract.name, () => { - it("reads packets from fromDevice", async () => { - await contract.setup?.(); - const transport = await contract.create(); - - const reader = transport.fromDevice.getReader(); - const sampleBytes = new Uint8Array([0x01, 0x02, 0x03]); - - await contract.pushIncoming?.(sampleBytes); - - const packetEvent = await readUntilType(reader, "packet"); - expect("data" in packetEvent ? packetEvent.data : undefined).toEqual( - sampleBytes, - ); - - reader.releaseLock(); - await contract.teardown?.(); - }); - - it("writes bytes to toDevice", async () => { - await contract.setup?.(); - const transport = await contract.create(); - - const writer = transport.toDevice.getWriter(); - const outgoingBytes = new Uint8Array([0xaa, 0xbb]); - await writer.write(outgoingBytes); - await writer.close(); - - contract.assertLastWritten?.(outgoingBytes); - await contract.teardown?.(); - }); - - it("disconnect() emits DeviceDisconnected('user')", async () => { - await contract.setup?.(); - const transport = await contract.create(); - - const reader = transport.fromDevice.getReader(); - - // Trigger user disconnect - await transport.disconnect(); - - // Read a few events and assert we eventually see the user disconnect. - let sawUser = false; - for (let i = 0; i < 10; i++) { - const { value } = await reader.read(); - if ( - value && - value.type === "status" && - value.data.status === DeviceStatusEnum.DeviceDisconnected && - value.data.reason === "user" - ) { - sawUser = true; - break; - } - } - expect(sawUser).toBe(true); - - reader.releaseLock(); - await contract.teardown?.(); - }); - - it("emits DeviceDisconnected when the underlying link drops", async () => { - await contract.setup?.(); - const transport = await contract.create(); - - const reader = transport.fromDevice.getReader(); - - await contract.triggerDisconnect?.(); - - // As above, read a few events and assert we eventually see "disconnected" - let sawDrop = false; - for (let i = 0; i < 10; i++) { - const { value } = await reader.read(); - if ( - value && - value.type === "status" && - value.data.status === DeviceStatusEnum.DeviceDisconnected - ) { - sawDrop = true; - break; - } - } - expect(sawDrop).toBe(true); - - reader.releaseLock(); - await contract.teardown?.(); - }); - }); -} From 40347b92c251e0f77b5594f349b7c512a1b3dd48 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 13:55:57 -0500 Subject: [PATCH 35/49] chore: clean up references to the removed SDK packages Update root package.json, pnpm-workspace.yaml, lockfile, CI and release workflows (release loop skips private packages; ui marked private), README and TESTING.md. --- .github/workflows/ci.yml | 2 +- .github/workflows/release-packages.yml | 20 +- README.md | 107 ++------ TESTING.md | 86 ++---- package.json | 2 - packages/ui/package.json | 1 + pnpm-lock.yaml | 354 ++++--------------------- pnpm-workspace.yaml | 6 +- 8 files changed, 104 insertions(+), 474 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4452782b3..87bb219fd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -52,7 +52,7 @@ jobs: set -euo pipefail # List packages to exclude (full paths under repo root) - EXCLUDED_DIRS=("packages/protobufs" "packages/sdk-kmp" "packages/transport-deno" "packages/ui" "packages/web") + EXCLUDED_DIRS=("packages/protobufs" "packages/sdk-kmp" "packages/ui" "packages/web") is_excluded() { local dir="$1" diff --git a/.github/workflows/release-packages.yml b/.github/workflows/release-packages.yml index 5e13ea4ac..c1226b97d 100644 --- a/.github/workflows/release-packages.yml +++ b/.github/workflows/release-packages.yml @@ -44,10 +44,24 @@ jobs: run: | set -euo pipefail if [ "${{ github.event.inputs.packages }}" = "all" ] || [ -z "${{ github.event.inputs.packages }}" ]; then - mapfile -t TARGETS < <(ls -d packages/*) + mapfile -t ALL < <(ls -d packages/*) else - IFS=',' read -ra TARGETS <<< "${{ github.event.inputs.packages }}" - TARGETS=("${TARGETS[@]/#/packages/}") + IFS=',' read -ra ALL <<< "${{ github.event.inputs.packages }}" + ALL=("${ALL[@]/#/packages/}") + fi + # Only publish packages that are not marked "private": true + # (protobufs, sdk-kmp and ui are all private workspace packages). + TARGETS=() + for dir in "${ALL[@]}"; do + if [ -f "$dir/package.json" ] && [ "$(node -p "require('./$dir/package.json').private === true")" = "false" ]; then + TARGETS+=("$dir") + else + echo "Skipping $dir (private or no package.json)" + fi + done + if [ "${#TARGETS[@]}" -eq 0 ]; then + echo "::error::No publishable (non-private) packages selected." + exit 1 fi printf '%s\n' "${TARGETS[@]}" | paste -sd, - > targets.txt echo "list=$(cat targets.txt)" >> "$GITHUB_OUTPUT" diff --git a/README.md b/README.md index 3866e2208..ff46cf371 100644 --- a/README.md +++ b/README.md @@ -1,84 +1,41 @@ # Meshtastic Web Monorepo [![CI](https://img.shields.io/github/actions/workflow/status/meshtastic/web/ci.yml?branch=main&label=Web%20CI&logo=github&color=yellow)](https://github.com/meshtastic/web/actions/workflows/ci.yml) -[![CI](https://img.shields.io/github/actions/workflow/status/meshtastic/js/ci.yml?branch=master&label=JS%20CI&logo=github&color=yellow)](https://github.com/meshtastic/js/actions/workflows/ci.yml) [![CLA assistant](https://cla-assistant.io/readme/badge/meshtastic/web)](https://cla-assistant.io/meshtastic/web) [![Fiscal Contributors](https://opencollective.com/meshtastic/tiers/badge.svg?label=Fiscal%20Contributors&color=deeppink)](https://opencollective.com/meshtastic/) [![Vercel](https://img.shields.io/static/v1?label=Powered%20by&message=Vercel&style=flat&logo=vercel&color=000000)](https://vercel.com?utm_source=meshtastic&utm_campaign=oss) ## Overview -This monorepo consolidates the official [Meshtastic](https://meshtastic.org) web -interface, the domain-driven JavaScript SDK that drives it, and a set of -runtime-specific transport packages. Everything you need to read state from or -send commands to a Meshtastic device lives here. +This monorepo contains the official [Meshtastic](https://meshtastic.org) web +client, the shared UI library it uses, the generated protobuf stubs, and +`sdk-kmp`, a thin JavaScript facade over the Kotlin +[meshtastic-sdk](https://github.com/meshtastic/meshtastic-sdk) that handles +device connections and mesh state. > [!NOTE] > You can find the main Meshtastic documentation at https://meshtastic.org/docs/introduction/. ## Packages -Libraries live under `packages/`; the reference web client lives under `apps/`. - | Package | Purpose | | --- | --- | -| `packages/sdk` | Framework-agnostic TypeScript SDK. Domain-driven feature slices (device, chat, nodes, channels, config, telemetry, position, traceroute, files) built around a `MeshClient` orchestrator with `@preact/signals-core` reactive state. | -| `packages/sdk-kmp` | The Kotlin Multiplatform [meshtastic-sdk](https://github.com/meshtastic/meshtastic-sdk) compiled to JavaScript (Gradle, JDK 21) with a small `@JsExport` facade and browser transports. The web client's connection and mesh behaviour comes from here. | -| `packages/sdk-react` | React hooks + `MeshProvider` on top of `@meshtastic/sdk`. Wraps signals in `useSyncExternalStore` for concurrent-safe renders. | | `apps/web` | Reference React web client. Hosted at [client.meshtastic.org](https://client.meshtastic.org). | +| `packages/sdk-kmp` | Wraps the Kotlin Multiplatform [meshtastic-sdk](https://github.com/meshtastic/meshtastic-sdk), compiled to JavaScript with Gradle (JDK 21), behind a small `@JsExport` facade plus browser transports. The web client's connection and mesh behaviour comes from here. The SDK source is pinned as a git submodule at `packages/sdk-kmp/vendor/meshtastic-sdk`. | | `packages/ui` | Shared Radix + Tailwind component library. | | `packages/protobufs` | Generated TypeScript stubs from [`meshtastic/protobufs`](https://github.com/meshtastic/protobufs), produced via `buf generate`. Source of truth for every wire-level type. | -| `packages/transport-http` | HTTP transport for devices exposing a network interface. | -| `packages/transport-web-bluetooth` | Web Bluetooth transport for BLE-capable devices (browsers). | -| `packages/transport-web-serial` | Web Serial transport for USB-serial devices (browsers). | -| `packages/transport-node` | TCP transport for Node.js. | -| `packages/transport-node-serial` | Serial transport for Node.js. | -| `packages/transport-deno` | TCP transport for Deno. | -| `packages/transport-mock` | In-memory transport for tests. | -All publishable packages ship to both [JSR](https://jsr.io/@meshtastic) and [NPM](https://www.npmjs.com/org/meshtastic). +All packages under `packages/` are private workspace packages; none are +published to npm or JSR from this repository. ## Architecture -`@meshtastic/sdk` organises its source by feature slice. Each slice follows the -same DDD layout: - -``` -features// - domain/ # entities & value objects — pure TypeScript types - application/ # use-cases (SendTextUseCase, FavoriteNodeUseCase, …) - infrastructure/ # protobuf ↔ domain mappers, admin-message adapters - state/ # signals-backed reactive stores - Client.ts # public facade exposing readable signals + command methods - index.ts -``` - -The shared kernel under `packages/sdk/src/core/` owns: - -- **`client/`** — `MeshClient`, the thin orchestrator that owns the transport, queue, event bus, and one instance of every slice client. -- **`transport/`** — the `Transport` interface every `transport-*` package implements. -- **`event-bus/`** — typed pub/sub channels populated by the packet codec. -- **`packet-codec/`** — frame parser (0x94 0xC3), `FromRadio` decoder, portnum router. -- **`queue/`**, **`xmodem/`** — packet ack/timeout pipeline and file-transfer protocol. -- **`signals/`** — signal and keyed-collection helpers consumed by every slice. -- **`logging/`** — `tslog` factory used consistently by every class. -- **`identifiers/`**, **`errors/`** — small primitives shared across slices. - -The protobuf boundary is strict: wire messages enter through the packet codec, -get mapped into domain entities inside `features/*/infrastructure/*Mapper.ts`, -and signals only ever expose the domain shape. - -``` - Transport ─▶ Packet codec ─▶ EventBus ─▶ Slice infrastructure - │ - ▼ - Signals (state) ─▶ sdk-react hooks ─▶ UI - ▲ - │ - Slice application (use-cases) ─▶ MeshClient.sendPacket ─▶ Queue ─▶ Transport -``` - -Expected domain errors are returned as `Result` via [`better-result`](https://www.npmjs.com/package/better-result); exceptions are reserved for programmer errors and truly exceptional conditions. +The web client never speaks the Meshtastic protocol itself. `apps/web` calls +the facade in `packages/sdk-kmp`, which drives the Kotlin SDK (framing, packet +queue, state, persistence) over a browser transport (Web Serial, Web Bluetooth, +or HTTP). Wire-level types come from `packages/protobufs`. See +`packages/sdk-kmp/README.md` for the facade surface and how the SDK version is +pinned. ## Getting Started @@ -130,8 +87,7 @@ not sequenced against workspace peers, so run `pnpm --filter @meshtastic/protobufs build` first if you are iterating on generated stubs consumed via a non-workspace protocol. -If you only need the web client, build it and its dependency graph without -touching every publishable package: +If you only need the web client, build it and its dependency graph: ```bash pnpm --filter meshtastic-web... build @@ -152,39 +108,10 @@ pnpm check:fix ## Developing -### Adding a new feature slice to `@meshtastic/sdk` - -1. Create `packages/sdk/src/features//` with `domain/`, `application/`, `infrastructure/`, `state/` subdirectories plus an `index.ts` barrel. -2. Implement a signals-backed store in `state/`. -3. Subscribe to the relevant `EventBus` channel(s) inside a `Client.ts` class and write mapped domain entities to the store. -4. Wire the new client into `MeshClient` and re-export types from `packages/sdk/mod.ts`. -5. Add vitest coverage: domain invariants, use-cases against `createFakeTransport()`, and round-trip mapper fixtures. -6. If the slice has React callers, add a matching hook under `packages/sdk-react/src/hooks/`. - -### Adding a new transport - -Implement the `Transport` interface exported from `@meshtastic/sdk/transport`: - -```ts -interface Transport { - toDevice: WritableStream; - fromDevice: ReadableStream; - disconnect(): Promise; -} -``` - -The SDK does the framing and decoding — transports only supply raw bytes. - ### Testing -Vitest is wired at the repo root and picks up `packages/*` projects. The SDK -ships `@meshtastic/sdk/testing` with `createFakeTransport()` for wiring tests -without real hardware. - -## Publishing - -Each publishable package has `build:npm` / `publish:npm` / `prepare:jsr` / -`publish:jsr` scripts. See each package's `package.json` for details. +Vitest is wired at the repo root (`pnpm test`) and picks up the `packages/*` and +`apps/*` projects. See `TESTING.md` for the testing strategy. ## Repository activity diff --git a/TESTING.md b/TESTING.md index 00cb21a7c..6104a6bbc 100644 --- a/TESTING.md +++ b/TESTING.md @@ -1,83 +1,39 @@ # Testing strategy -How this monorepo proves correctness, and where coverage currently sits. +How this monorepo proves correctness. The web client talks to devices through +the Kotlin meshtastic-sdk (`packages/sdk-kmp`), so protocol and persistence +behaviour is tested upstream in that SDK; this repo tests the facade and the UI. ## Levels -Tests live in five tiers. Each PR should add coverage at the **lowest level that catches the regression**, and only climb tiers when that's not possible. +Each PR should add coverage at the **lowest level that catches the regression**, and only climb tiers when that's not possible. | Tier | Scope | Tooling | Where | | --- | --- | --- | --- | -| 1. **Unit** | Pure functions, value objects, mappers, single classes with mocked deps | `vitest run` (Node env) | `*.test.ts` colocated with source | -| 2. **Slice integration** | Use-case + store + mapper exercised against in-memory deps; assert outbound bytes and signal state | `vitest` + `createFakeTransport()` | `*.test.ts` in slice dirs | -| 3. **Client integration** | `MeshClient` end-to-end with a fake transport feeding canned `FromRadio` packets | `vitest` + `@meshtastic/sdk/testing` | `packages/sdk/tests/integration/` | -| 4. **Storage integration** | Real Drizzle queries against sql.js in-memory; or against `@vitest/browser` for OPFS | `vitest` (Node + browser) | `packages/sdk-storage-sqlocal/{src,tests}` | -| 5. **Hook / DOM** | React hooks render under `` / ``, react to signals | `vitest` + `@testing-library/react` + `jsdom` | `packages/sdk-react/tests/` | -| 6. **E2E / simulator** | Whole stack: SDK → transport → simulator/firmware. Catches protocol drift | `@vitest/browser` for OPFS; `meshtasticd` simulator over TCP for protocol | future `tests/e2e/` | +| 1. **Unit** | Pure functions, stores, single classes with mocked deps | `vitest run` (Node env) | `*.test.ts` colocated with source | +| 2. **Facade** | The `@JsExport` facade and browser transports in `packages/sdk-kmp` | `vitest` | `packages/sdk-kmp` (`pnpm --filter @meshtastic/sdk-kmp test`) | +| 3. **Component / DOM** | React components and hooks, with the SDK facade mocked | `vitest` + `@testing-library/react` + `jsdom` | `apps/web/src/**` | +| 4. **E2E** | Whole web client in a real browser | Playwright | `e2e/` | -## Per-package coverage gates +## Per-package notes -| Package | Required floor | Notes | -| --- | --- | --- | -| `packages/sdk/core` | every primitive (signals, EventBus, Queue, packet-codec, identifiers) has a unit test; lifecycle covered by `MeshClient.test.ts` | adopt `c8` thresholds once stable | -| `packages/sdk/features/*` | each slice ships: 1 domain invariant test, 1 use-case test against fake transport, 1 mapper round-trip (where mappers exist) | Integration covered by `tests/integration/fake-transport.test.ts` | -| `packages/sdk-react` | each public hook has a `renderHook` test that asserts initial render + re-render on signal change | uses jsdom; provider wrapper required | -| `packages/sdk-storage-sqlocal` | every repository method tested against sql.js in-memory; **at least one OPFS-real test per repo** runs in browser mode | sql.js validates SQL correctness; OPFS validates VFS / Worker plumbing | -| `packages/transport-*` | minimum: framing round-trip, disconnect cleans up streams, error path emits status | low-level; ship as is | -| `packages/web` | component tests at `34` baseline; new SDK-driven UI components must add a hook-mock test | currently all green | - -## Current state (audit) - -| Package | Test files | Tests pass | Gaps | -| --- | --- | --- | --- | -| `packages/sdk` | 7 | 25 ✅ | nodes/channels/config/telemetry/position/traceroute/files slices have **no tests**; no `MeshClient` lifecycle test (only fake-transport integration); no schema migration test | -| `packages/sdk-react` | 1 | 2 ✅ | only `useMeshDevice` + a stubbed `useChat` test; missing `useNodes`, `useChannels`, `useConfig`, `useConnection`, `useTraceroute`, `useTelemetry`, `usePosition`, `useFileTransfer`, `useFavoriteNode`, `useIgnoreNode`, `useMeshRegistry`, `useClientById`, `useActiveClient`. No registry-aware re-render coverage. | -| `packages/sdk-storage-sqlocal` | 2 | 8 ✅ | sql.js only — **no real OPFS test**, no Worker boot test, no cross-tab BroadcastChannel test (mocked away), no migration v1→v2 test | -| `packages/web` | 34 | 294 ✅ | no `useConnections` test; new `meshRegistry` + `sdkStorage` modules untested; chat persistence end-to-end not exercised | -| `packages/transport-*` | 1 each (5 of 7) | varies | `transport-deno` + `transport-mock` have no tests; transports likely lack disconnect/error coverage | -| `packages/core` | 0 | n/a | legacy, slated for deletion in Phase C; tolerable | -| `packages/ui` | 0 | n/a | pure presentational; visual regression only | -| `packages/protobufs` | 0 | n/a | generated code; upstream's responsibility | - -## Concrete additions queued (priority order) - -1. **`packages/sdk` slice tests** — one Use-case + one Mapper test per slice (`nodes`, `channels`, `config`, `telemetry`, `position`, `traceroute`). Pattern: build a stub `MeshClient`, dispatch a synthetic event, assert signal value or outbound bytes. -2. **`packages/sdk-react` hook tests** — for every hook listed above, mount under ``, drive a signal change, assert `result.current`. One file, ~15 cases. -3. **`packages/sdk` `ChatClient` persistence test** — wire `InMemoryMessageRepository`, append messages, re-construct `ChatClient`, assert hydration. Validates the lazy-load contract. -4. **`packages/sdk-storage-sqlocal` migration test** — bootstrap empty DB, run `MIGRATIONS[]`, assert `_schema.version`. Then add a fake `version: 2` migration and prove it's applied idempotently. -5. **`packages/sdk-storage-sqlocal` browser mode** — add a second `vitest.browser.config.ts` using `@vitest/browser` (Playwright provider) so we exercise real OPFS + Worker. CI runs both modes. -6. **`packages/sdk-storage-sqlocal` BroadcastChannel test** — instantiate two `MultiTabCoordinator` instances in same process; one broadcasts, the other observes. (Node has no `BroadcastChannel` global; use `worker_threads`'s `BroadcastChannel` polyfill or jsdom env.) -7. **`packages/web` `meshRegistry` + `sdkStorage` lazy-init test** — assert `getStorageDb()` returns the same promise on repeated calls and only opens the DB once. -8. **`packages/sdk-react` registry test** — mount `` with two clients, switch active, confirm a hook re-renders against the new client. - -## E2E / simulator (Tier 6) — scope only - -Out of immediate scope; documenting for a follow-up PR. - -- Run `meshtasticd` (firmware simulator) in CI Docker via `services:` block. -- Spin up `MeshClient` with `TransportHTTP` pointed at the simulator's HTTP endpoint. -- Drive scripted scenarios: configure → send text → expect ack; channel update; node info exchange; traceroute. -- Use `@vitest/browser` so we also exercise the real OPFS persistence path during E2E. -- Run on `main` only (cost). Smoke subset on PR. - -Until that lands, `createFakeTransport()` covers the protocol layer at unit/integration speed. +| Package | Notes | +| --- | --- | +| `apps/web` | Component and store tests; new SDK-driven UI must mock the facade rather than the Kotlin build. | +| `packages/sdk-kmp` | Facade tests only; the underlying Kotlin SDK is tested in its own repository. | +| `packages/ui` | Pure presentational; no unit tests. | +| `packages/protobufs` | Generated code; upstream's responsibility. | ## Conventions -- Test file colocated with source: `Foo.ts` → `Foo.test.ts`. -- Integration tests under `tests/integration/`. -- Browser-mode tests use the suffix `.browser.test.ts` so they can be filtered. -- Protobuf fixtures live in `__fixtures__/*.fixtures.ts` next to mappers; binary data committed as base64, not raw bytes. -- Each test imports concrete classes from the source path (`./Foo.ts`), not the package barrel — fast type-check, zero re-export drift. -- No mocked SDK from inside SDK tests. Use `createFakeTransport()` and real `MeshClient` instances. +- Test file colocated with source: `Foo.ts` -> `Foo.test.ts`. +- Each test imports concrete classes from the source path (`./Foo.ts`), not the package barrel. ## Running ```sh -pnpm -r test # all packages, Node env -pnpm --filter @meshtastic/sdk test -pnpm --filter @meshtastic/sdk-storage-sqlocal test -pnpm --filter meshtastic-web test -# future: -pnpm --filter @meshtastic/sdk-storage-sqlocal test:browser +pnpm test # root vitest, all projects +pnpm --filter meshtastic-web test # web client only +pnpm --filter @meshtastic/sdk-kmp test +pnpm test:e2e # Playwright ``` diff --git a/package.json b/package.json index 8e6da009a..8e84124c3 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,6 @@ "check:fix": "pnpm lint:fix && pnpm format:fix", "build:all": "pnpm run --filter '*' build", "clean:all": "pnpm run --filter '*' clean", - "publish:packages": "pnpm run build --filter 'packages/transport-*'", "test": "vitest", "test:e2e": "playwright test", "test:e2e:ui": "playwright test --ui", @@ -36,7 +35,6 @@ "tslog": "^5.2.0" }, "devDependencies": { - "@meshtastic/sdk": "workspace:*", "@playwright/test": "^1.64.1", "@types/node": "^26.6.5", "@typescript/typescript6": "^6.0.2", diff --git a/packages/ui/package.json b/packages/ui/package.json index 97399d4f9..3fb4b491d 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -1,6 +1,7 @@ { "name": "@meshtastic/ui", "version": "0.1.0", + "private": true, "license": "GPL-3.0-only", "repository": { "type": "git", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7390c512e..ae4ff8292 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -24,9 +24,6 @@ importers: specifier: ^5.2.0 version: 5.2.0 devDependencies: - '@meshtastic/sdk': - specifier: workspace:* - version: link:packages/sdk '@playwright/test': specifier: ^1.64.1 version: 1.64.1 @@ -339,124 +336,8 @@ importers: specifier: ^6.1.3 version: 6.1.3 - packages/sdk: - dependencies: - '@bufbuild/protobuf': - specifier: ^2.16.0 - version: 2.16.0 - '@meshtastic/protobufs': - specifier: workspace:* - version: link:../protobufs - '@preact/signals-core': - specifier: ^1.14.4 - version: 1.14.4 - better-result: - specifier: ^3.0.1 - version: 3.0.1 - crc: - specifier: npm:crc@^4.3.2 - version: 4.3.2 - ste-simple-events: - specifier: ^4.0.0 - version: 4.0.0 - tslog: - specifier: ^5.2.0 - version: 5.2.0 - packages/sdk-kmp: {} - packages/sdk-react: - dependencies: - '@meshtastic/sdk': - specifier: workspace:* - version: link:../sdk - better-result: - specifier: ^3.0.1 - version: 3.0.1 - devDependencies: - '@testing-library/react': - specifier: ^16.3.3 - version: 16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) - '@types/react': - specifier: ^19.3.0 - version: 19.3.0 - jsdom: - specifier: ^30.1.3 - version: 30.1.3(@noble/hashes@2.4.0) - react: - specifier: ^19.3.1 - version: 19.3.1 - react-dom: - specifier: ^19.3.1 - version: 19.3.1(react@19.3.1) - - packages/sdk-storage-sqlocal: - dependencies: - '@meshtastic/sdk': - specifier: workspace:* - version: link:../sdk - drizzle-orm: - specifier: ^0.45.4 - version: 0.45.4(@types/sql.js@1.4.11)(sql.js@1.15.0) - sqlocal: - specifier: ^0.18.0 - version: 0.18.0(drizzle-orm@0.45.4(@types/sql.js@1.4.11)(sql.js@1.15.0))(react@19.3.1)(vite@8.3.4(@types/node@26.6.5)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)) - devDependencies: - '@types/sql.js': - specifier: ^1.4.11 - version: 1.4.11 - sql.js: - specifier: ^1.15.0 - version: 1.15.0 - - packages/transport-deno: - dependencies: - '@meshtastic/sdk': - specifier: workspace:* - version: link:../sdk - - packages/transport-http: - dependencies: - '@meshtastic/sdk': - specifier: workspace:* - version: link:../sdk - - packages/transport-node: - dependencies: - '@meshtastic/sdk': - specifier: workspace:* - version: link:../sdk - - packages/transport-node-serial: - dependencies: - '@meshtastic/sdk': - specifier: workspace:* - version: link:../sdk - serialport: - specifier: ^13.0.0 - version: 13.0.0 - - packages/transport-web-bluetooth: - dependencies: - '@meshtastic/sdk': - specifier: workspace:* - version: link:../sdk - '@types/web-bluetooth': - specifier: npm:@types/web-bluetooth@^0.0.21 - version: 0.0.21 - - packages/transport-web-serial: - dependencies: - '@meshtastic/sdk': - specifier: workspace:* - version: link:../sdk - '@types/w3c-web-serial': - specifier: npm:@types/w3c-web-serial@^1.0.8 - version: 1.0.8 - better-result: - specifier: ^3.0.1 - version: 3.0.1 - packages/ui: dependencies: '@radix-ui/react-collapsible': @@ -2370,70 +2251,6 @@ packages: cpu: [x64] os: [win32] - '@serialport/binding-mock@10.2.2': - resolution: {integrity: sha512-HAFzGhk9OuFMpuor7aT5G1ChPgn5qSsklTFOTUX72Rl6p0xwcSVsRtG/xaGp6bxpN7fI9D/S8THLBWbBgS6ldw==} - engines: {node: '>=12.0.0'} - - '@serialport/bindings-cpp@13.0.0': - resolution: {integrity: sha512-r25o4Bk/vaO1LyUfY/ulR6hCg/aWiN6Wo2ljVlb4Pj5bqWGcSRC4Vse4a9AcapuAu/FeBzHCbKMvRQeCuKjzIQ==} - engines: {node: '>=18.0.0'} - - '@serialport/bindings-interface@1.2.2': - resolution: {integrity: sha512-CJaUd5bLvtM9c5dmO9rPBHPXTa9R2UwpkJ0wdh9JCYcbrPWsKz+ErvR0hBLeo7NPeiFdjFO4sonRljiw4d2XiA==} - engines: {node: ^12.22 || ^14.13 || >=16} - - '@serialport/parser-byte-length@13.0.0': - resolution: {integrity: sha512-32yvqeTAqJzAEtX5zCrN1Mej56GJ5h/cVFsCDPbF9S1ZSC9FWjOqNAgtByseHfFTSTs/4ZBQZZcZBpolt8sUng==} - engines: {node: '>=20.0.0'} - - '@serialport/parser-cctalk@13.0.0': - resolution: {integrity: sha512-RErAe57g9gvnlieVYGIn1xymb1bzNXb2QtUQd14FpmbQQYlcrmuRnJwKa1BgTCujoCkhtaTtgHlbBWOxm8U2uA==} - engines: {node: '>=20.0.0'} - - '@serialport/parser-delimiter@12.0.0': - resolution: {integrity: sha512-gu26tVt5lQoybhorLTPsH2j2LnX3AOP2x/34+DUSTNaUTzu2fBXw+isVjQJpUBFWu6aeQRZw5bJol5X9Gxjblw==} - engines: {node: '>=12.0.0'} - - '@serialport/parser-delimiter@13.0.0': - resolution: {integrity: sha512-Qqyb0FX1avs3XabQqNaZSivyVbl/yl0jywImp7ePvfZKLwx7jBZjvL+Hawt9wIG6tfq6zbFM24vzCCK7REMUig==} - engines: {node: '>=20.0.0'} - - '@serialport/parser-inter-byte-timeout@13.0.0': - resolution: {integrity: sha512-a0w0WecTW7bD2YHWrpTz1uyiWA2fDNym0kjmPeNSwZ2XCP+JbirZt31l43m2ey6qXItTYVuQBthm75sPVeHnGA==} - engines: {node: '>=20.0.0'} - - '@serialport/parser-packet-length@13.0.0': - resolution: {integrity: sha512-60ZDDIqYRi0Xs2SPZUo4Jr5LLIjtb+rvzPKMJCohrO6tAqSDponcNpcB1O4W21mKTxYjqInSz+eMrtk0LLfZIg==} - engines: {node: '>=8.6.0'} - - '@serialport/parser-readline@12.0.0': - resolution: {integrity: sha512-O7cywCWC8PiOMvo/gglEBfAkLjp/SENEML46BXDykfKP5mTPM46XMaX1L0waWU6DXJpBgjaL7+yX6VriVPbN4w==} - engines: {node: '>=12.0.0'} - - '@serialport/parser-readline@13.0.0': - resolution: {integrity: sha512-dov3zYoyf0dt1Sudd1q42VVYQ4WlliF0MYvAMA3MOyiU1IeG4hl0J6buBA2w4gl3DOCC05tGgLDN/3yIL81gsA==} - engines: {node: '>=20.0.0'} - - '@serialport/parser-ready@13.0.0': - resolution: {integrity: sha512-JNUQA+y2Rfs4bU+cGYNqOPnNMAcayhhW+XJZihSLQXOHcZsFnOa2F9YtMg9VXRWIcnHldHYtisp62Etjlw24bw==} - engines: {node: '>=20.0.0'} - - '@serialport/parser-regex@13.0.0': - resolution: {integrity: sha512-m7HpIf56G5XcuDdA3DB34Z0pJiwxNRakThEHjSa4mG05OnWYv0IG8l2oUyYfuGMowQWaVnQ+8r+brlPxGVH+eA==} - engines: {node: '>=20.0.0'} - - '@serialport/parser-slip-encoder@13.0.0': - resolution: {integrity: sha512-fUHZEExm6izJ7rg0A1yjXwu4sOzeBkPAjDZPfb+XQoqgtKAk+s+HfICiYn7N2QU9gyaeCO8VKgWwi+b/DowYOg==} - engines: {node: '>=20.0.0'} - - '@serialport/parser-spacepacket@13.0.0': - resolution: {integrity: sha512-DoXJ3mFYmyD8X/8931agJvrBPxqTaYDsPoly9/cwQSeh/q4EjQND9ySXBxpWz5WcpyCU4jOuusqCSAPsbB30Eg==} - engines: {node: '>=20.0.0'} - - '@serialport/stream@13.0.0': - resolution: {integrity: sha512-F7xLJKsjGo2WuEWMSEO1SimRcOA+WtWICsY13r0ahx8s2SecPQH06338g28OT7cW7uRXI7oEQAk62qh5gHJW3g==} - engines: {node: '>=20.0.0'} - '@sqlite.org/sqlite-wasm@3.51.2-build9': resolution: {integrity: sha512-tj2Sa6X4gVZqS9SiT2xlEeChSUklSGq8Hz6zKNbHW6NRiGyrSXiFcspnrWru1wPBT76RX/VxweESKxawCxfDxg==} engines: {node: '>=22'} @@ -3634,15 +3451,6 @@ packages: resolution: {integrity: sha512-XGpFGbMLHwSt74YLTKho7Ib242qi6O8MSX+sRokV4oz7iKXvQWGYZthjIhjRGMxjzVkAubBO512dKGYcefmX3Q==} engines: {node: '>=6.4.0'} - crc@4.3.2: - resolution: {integrity: sha512-uGDHf4KLLh2zsHa8D8hIQ1H/HtFQhyHrc0uhHBcoKGol/Xnb+MPYfUMw7cvON6ze/GUESTudKayDcJC5HnJv1A==} - engines: {node: '>=12'} - peerDependencies: - buffer: '>=6.0.3' - peerDependenciesMeta: - buffer: - optional: true - cross-spawn@7.0.6: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} @@ -3697,15 +3505,6 @@ packages: resolution: {integrity: sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==} engines: {node: '>= 0.4'} - debug@4.4.0: - resolution: {integrity: sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==} - engines: {node: '>=6.0'} - peerDependencies: - supports-color: '*' - peerDependenciesMeta: - supports-color: - optional: true - debug@4.4.3: resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} engines: {node: '>=6.0'} @@ -4699,14 +4498,6 @@ packages: no-case@3.0.4: resolution: {integrity: sha512-fgAN3jGAh+RoxUGZHTSOLJIqUc2wmoBwGR4tbpNAKmmovFoWq0OdRkb0VkldReO2a2iBT/OEulG9XSUc10r3zg==} - node-addon-api@8.3.0: - resolution: {integrity: sha512-8VOpLHFrOQlAH+qA0ZzuGRlALRA6/LVh8QJldbrC4DY0hXoMP0l4Acq8TzFC018HztWiRqyCEj2aTWY2UvnJUg==} - engines: {node: ^18 || ^20 || >= 21} - - node-gyp-build@4.8.4: - resolution: {integrity: sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==} - hasBin: true - node-html-parser@5.4.2: resolution: {integrity: sha512-RaBPP3+51hPne/OolXxcz89iYvQvKOydaqoePpOgXcrOKZhjVIzmpKZz+Hd/RBO2/zN2q6CNJhQzucVz+u3Jyw==} @@ -5162,10 +4953,6 @@ packages: resolution: {integrity: sha512-GL2BWwVa6JydKO6l/ljVgjAZF4QJ3S7dWDWi53s5GZT8PJzD2fNxi67HANQGKAqPrwEpL5ba7gUBGi0Ls/sEoQ==} engines: {node: '>=20.0.0'} - serialport@13.0.0: - resolution: {integrity: sha512-PHpnTd8isMGPfFTZNCzOZp9m4mAJSNWle9Jxu6BPTcWq7YXl5qN7tp8Sgn0h+WIGcD6JFz5QDgixC2s4VW7vzg==} - engines: {node: '>=20.0.0'} - seroval-plugins@1.6.9: resolution: {integrity: sha512-kiDK/Tb8IWZ61WEU8pA2PDmAuw37gKph9Y77OZlD56mg0Y2g0Bg7gZ1HeHhs5d40w+nRoUq/wj08V26ilbez9g==} engines: {node: '>=10'} @@ -6001,6 +5788,7 @@ snapshots: '@csstools/css-parser-algorithms': 4.0.2(@csstools/css-tokenizer@4.0.2) '@csstools/css-tokenizer': 4.0.2 lru-cache: 11.5.3 + optional: true '@asamuzakjp/dom-selector@10.0.3': dependencies: @@ -6008,6 +5796,7 @@ snapshots: css-tree: 3.2.1 is-potential-custom-element-name: 1.0.1 lru-cache: 11.5.3 + optional: true '@babel/code-frame@7.29.7': dependencies: @@ -6675,6 +6464,7 @@ snapshots: '@bramus/specificity@2.4.3': dependencies: css-tree: 3.2.1 + optional: true '@bufbuild/protobuf@2.16.0': {} @@ -6694,12 +6484,14 @@ snapshots: transitivePeerDependencies: - supports-color - '@csstools/color-helpers@6.1.2': {} + '@csstools/color-helpers@6.1.2': + optional: true '@csstools/css-calc@3.4.3(@csstools/css-parser-algorithms@4.0.2(@csstools/css-tokenizer@4.0.2))(@csstools/css-tokenizer@4.0.2)': dependencies: '@csstools/css-parser-algorithms': 4.0.2(@csstools/css-tokenizer@4.0.2) '@csstools/css-tokenizer': 4.0.2 + optional: true '@csstools/css-color-parser@4.2.6(@csstools/css-parser-algorithms@4.0.2(@csstools/css-tokenizer@4.0.2))(@csstools/css-tokenizer@4.0.2)': dependencies: @@ -6707,20 +6499,25 @@ snapshots: '@csstools/css-calc': 3.4.3(@csstools/css-parser-algorithms@4.0.2(@csstools/css-tokenizer@4.0.2))(@csstools/css-tokenizer@4.0.2) '@csstools/css-parser-algorithms': 4.0.2(@csstools/css-tokenizer@4.0.2) '@csstools/css-tokenizer': 4.0.2 + optional: true '@csstools/css-parser-algorithms@4.0.2(@csstools/css-tokenizer@4.0.2)': dependencies: '@csstools/css-tokenizer': 4.0.2 + optional: true '@csstools/css-syntax-patches-for-csstree@1.1.15(css-tree@3.2.1)': optionalDependencies: css-tree: 3.2.1 + optional: true - '@csstools/css-tokenizer@4.0.2': {} + '@csstools/css-tokenizer@4.0.2': + optional: true '@exodus/bytes@1.16.0(@noble/hashes@2.4.0)': optionalDependencies: '@noble/hashes': 2.4.0 + optional: true '@floating-ui/core@1.8.0': dependencies: @@ -7699,60 +7496,6 @@ snapshots: '@rollup/rollup-win32-x64-msvc@4.64.7': optional: true - '@serialport/binding-mock@10.2.2': - dependencies: - '@serialport/bindings-interface': 1.2.2 - debug: 4.4.0 - transitivePeerDependencies: - - supports-color - - '@serialport/bindings-cpp@13.0.0': - dependencies: - '@serialport/bindings-interface': 1.2.2 - '@serialport/parser-readline': 12.0.0 - debug: 4.4.0 - node-addon-api: 8.3.0 - node-gyp-build: 4.8.4 - transitivePeerDependencies: - - supports-color - - '@serialport/bindings-interface@1.2.2': {} - - '@serialport/parser-byte-length@13.0.0': {} - - '@serialport/parser-cctalk@13.0.0': {} - - '@serialport/parser-delimiter@12.0.0': {} - - '@serialport/parser-delimiter@13.0.0': {} - - '@serialport/parser-inter-byte-timeout@13.0.0': {} - - '@serialport/parser-packet-length@13.0.0': {} - - '@serialport/parser-readline@12.0.0': - dependencies: - '@serialport/parser-delimiter': 12.0.0 - - '@serialport/parser-readline@13.0.0': - dependencies: - '@serialport/parser-delimiter': 13.0.0 - - '@serialport/parser-ready@13.0.0': {} - - '@serialport/parser-regex@13.0.0': {} - - '@serialport/parser-slip-encoder@13.0.0': {} - - '@serialport/parser-spacepacket@13.0.0': {} - - '@serialport/stream@13.0.0': - dependencies: - '@serialport/bindings-interface': 1.2.2 - debug: 4.4.0 - transitivePeerDependencies: - - supports-color - '@sqlite.org/sqlite-wasm@3.51.2-build9': {} '@standard-schema/spec@1.1.0': @@ -9632,8 +9375,6 @@ snapshots: dependencies: browserslist: 4.29.3 - crc@4.3.2: {} - cross-spawn@7.0.6: dependencies: path-key: 3.1.1 @@ -9659,6 +9400,7 @@ snapshots: dependencies: mdn-data: 2.27.1 source-map-js: 1.2.2 + optional: true css-what@6.2.2: {} @@ -9682,6 +9424,7 @@ snapshots: whatwg-url: 17.3.0(@noble/hashes@2.4.0) transitivePeerDependencies: - '@noble/hashes' + optional: true data-view-buffer@1.0.2: dependencies: @@ -9701,15 +9444,12 @@ snapshots: es-errors: 1.3.0 is-data-view: 1.0.2 - debug@4.4.0: - dependencies: - ms: 2.1.3 - debug@4.4.3: dependencies: ms: 2.1.3 - decimal.js@10.6.0: {} + decimal.js@10.6.0: + optional: true deepmerge@4.3.1: {} @@ -9800,7 +9540,8 @@ snapshots: entities@7.0.1: {} - entities@8.1.0: {} + entities@8.1.0: + optional: true es-abstract-get@1.0.0: dependencies: @@ -10124,6 +9865,7 @@ snapshots: '@exodus/bytes': 1.16.0(@noble/hashes@2.4.0) transitivePeerDependencies: - '@noble/hashes' + optional: true html-minifier-terser@6.1.0: dependencies: @@ -10258,7 +10000,8 @@ snapshots: dependencies: isobject: 3.0.1 - is-potential-custom-element-name@1.0.1: {} + is-potential-custom-element-name@1.0.1: + optional: true is-regex@1.2.1: dependencies: @@ -10353,6 +10096,7 @@ snapshots: xml-name-validator: 5.0.0 transitivePeerDependencies: - '@noble/hashes' + optional: true jsesc@3.1.0: {} @@ -10543,7 +10287,8 @@ snapshots: math-intrinsics@1.1.0: {} - mdn-data@2.27.1: {} + mdn-data@2.27.1: + optional: true merge2@1.4.1: {} @@ -10590,10 +10335,6 @@ snapshots: lower-case: 2.0.2 tslib: 2.8.1 - node-addon-api@8.3.0: {} - - node-gyp-build@4.8.4: {} - node-html-parser@5.4.2: dependencies: css-select: 4.3.0 @@ -10689,6 +10430,7 @@ snapshots: parse5@8.0.1: dependencies: entities: 8.1.0 + optional: true pascal-case@3.1.2: dependencies: @@ -10784,7 +10526,8 @@ snapshots: picocolors: 1.1.1 sade: 1.8.1 - punycode@2.3.1: {} + punycode@2.3.1: + optional: true qrcode-generator@2.0.4: {} @@ -11064,6 +10807,7 @@ snapshots: saxes@6.0.0: dependencies: xmlchars: 2.2.0 + optional: true scheduler@0.28.0: {} @@ -11071,25 +10815,6 @@ snapshots: serialize-javascript@7.1.2: {} - serialport@13.0.0: - dependencies: - '@serialport/binding-mock': 10.2.2 - '@serialport/bindings-cpp': 13.0.0 - '@serialport/parser-byte-length': 13.0.0 - '@serialport/parser-cctalk': 13.0.0 - '@serialport/parser-delimiter': 13.0.0 - '@serialport/parser-inter-byte-timeout': 13.0.0 - '@serialport/parser-packet-length': 13.0.0 - '@serialport/parser-readline': 13.0.0 - '@serialport/parser-ready': 13.0.0 - '@serialport/parser-regex': 13.0.0 - '@serialport/parser-slip-encoder': 13.0.0 - '@serialport/parser-spacepacket': 13.0.0 - '@serialport/stream': 13.0.0 - debug: 4.4.0 - transitivePeerDependencies: - - supports-color - seroval-plugins@1.6.9(seroval@1.6.9): dependencies: seroval: 1.6.9 @@ -11337,11 +11062,13 @@ snapshots: tinyqueue@3.0.0: {} - tldts-core@7.4.18: {} + tldts-core@7.4.18: + optional: true tldts@7.4.18: dependencies: tldts-core: 7.4.18 + optional: true tmp-promise@3.0.3: dependencies: @@ -11364,10 +11091,12 @@ snapshots: tough-cookie@6.0.2: dependencies: tldts: 7.4.18 + optional: true tr46@7.0.0: dependencies: punycode: 2.3.1 + optional: true tree-kill@1.2.2: {} @@ -11492,7 +11221,8 @@ snapshots: undici-types@8.9.0: {} - undici@8.12.2: {} + undici@8.12.2: + optional: true unicode-canonical-property-names-ecmascript@2.0.1: {} @@ -11684,14 +11414,17 @@ snapshots: w3c-xmlserializer@6.0.0: dependencies: xml-name-validator: 5.0.0 + optional: true - webidl-conversions@8.0.1: {} + webidl-conversions@8.0.1: + optional: true webpack-virtual-modules@0.6.2: {} whatwg-mimetype@3.0.0: {} - whatwg-mimetype@5.0.0: {} + whatwg-mimetype@5.0.0: + optional: true whatwg-url@17.3.0(@noble/hashes@2.4.0): dependencies: @@ -11700,6 +11433,7 @@ snapshots: webidl-conversions: 8.0.1 transitivePeerDependencies: - '@noble/hashes' + optional: true which-boxed-primitive@1.1.1: dependencies: @@ -11863,9 +11597,11 @@ snapshots: ws@8.22.0: {} - xml-name-validator@5.0.0: {} + xml-name-validator@5.0.0: + optional: true - xmlchars@2.2.0: {} + xmlchars@2.2.0: + optional: true yallist@3.1.1: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index ccec13507..4b0830cdd 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,5 +1,4 @@ allowBuilds: - "@serialport/bindings-cpp": false "@tailwindcss/oxide": false "core-js": false esbuild: false @@ -8,8 +7,7 @@ packages: - "packages/*" - "apps/*" -# Resolve every @meshtastic/protobufs dependency (including the jsr: one in -# packages/sdk, kept for publishing) to the workspace package, so the app and -# the SDK share one copy of the generated types. +# Resolve every @meshtastic/protobufs dependency to the workspace package so +# the whole repo shares one copy of the generated types. overrides: "@meshtastic/protobufs": "workspace:*" From efad9963dd9fd379fa5c9e3913fa586328a985a6 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 17:15:06 -0500 Subject: [PATCH 36/49] perf(sdk-kmp): stop forwarding packet frames on the raw FromRadio stream Every MeshPacket reached the web twice: as a raw FromRadio frame the session decoded and ignored, and re-encoded through onPacket. The tap now reads the frame's field tags and skips frames carrying a packet, so each packet is decoded once on the web side. Frames are no longer copied when nothing listens. Claude-Session: https://claude.ai/code/session_01K9vyKS6Q1tGo9xUfNGCUW5 --- apps/web/src/core/kmp/serialClient.test.ts | 67 ++++++++++++++++++- .../kotlin/org/meshtastic/sdk/js/Client.kt | 9 ++- .../kotlin/org/meshtastic/sdk/js/Framing.kt | 20 ++++++ .../meshtastic/sdk/js/FromRadioFilterTest.kt | 33 +++++++++ 4 files changed, 127 insertions(+), 2 deletions(-) create mode 100644 packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/FromRadioFilterTest.kt diff --git a/apps/web/src/core/kmp/serialClient.test.ts b/apps/web/src/core/kmp/serialClient.test.ts index f257be747..6009dd3fd 100644 --- a/apps/web/src/core/kmp/serialClient.test.ts +++ b/apps/web/src/core/kmp/serialClient.test.ts @@ -1,5 +1,5 @@ // @vitest-environment node -import { create, toBinary } from "@bufbuild/protobuf"; +import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; import { Protobuf } from "@core/protobuf.ts"; import type { ConnectionStateJs } from "@meshtastic/sdk-kmp"; import { @@ -211,6 +211,71 @@ describe("createSerialClient (Kotlin facade over a fake navigator.serial)", () = session.close(); }, 15_000); + it("delivers a mesh packet once, through onPacket and not the raw frame stream", async () => { + const radio = new FakeRadio(); + const port = new FakeSerialPort(ids, radio); + installSerial([port]); + const client = await createSerialClient(ids); + clients.push(client); + await client.connect(); + await connected(client); + const frames: Uint8Array[] = []; + const packets: Uint8Array[] = []; + client.onFromRadio((bytes) => frames.push(bytes)); + client.onPacket((bytes) => packets.push(bytes)); + + const text = toBinary( + Protobuf.Mesh.FromRadioSchema, + create(Protobuf.Mesh.FromRadioSchema, { + id: 41, + payloadVariant: { + case: "packet", + value: create(Protobuf.Mesh.MeshPacketSchema, { + from: 0x2000, + to: 0xffffffff, + id: 7, + payloadVariant: { + case: "decoded", + value: create(Protobuf.Mesh.DataSchema, { + portnum: Protobuf.Portnums.PortNum.TEXT_MESSAGE_APP, + payload: new TextEncoder().encode("hi"), + }), + }, + }), + }, + }), + ); + const notice = toBinary( + Protobuf.Mesh.FromRadioSchema, + create(Protobuf.Mesh.FromRadioSchema, { + id: 42, + payloadVariant: { + case: "clientNotification", + value: create(Protobuf.Mesh.ClientNotificationSchema, { + message: "ok", + }), + }, + }), + ); + port.push(new Uint8Array([...framed(text), ...framed(notice)])); + + await vi.waitFor(() => { + expect(frames).toHaveLength(1); + expect(packets).toHaveLength(1); + }); + expect( + frames.map( + (bytes) => + fromBinary(Protobuf.Mesh.FromRadioSchema, bytes).payloadVariant.case, + ), + ).toEqual(["clientNotification"]); + expect( + packets.map( + (bytes) => fromBinary(Protobuf.Mesh.MeshPacketSchema, bytes).id, + ), + ).toEqual([7]); + }, 15_000); + it("hands the session its own node and channels again after an auto-reconnect", async () => { const radio = new FakeRadio(0x0a0b0c0d, { nodes: 3, channels: 2 }); const port = new FakeSerialPort(ids, radio); diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt index 04a1a19e2..c8bdbb184 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt @@ -46,12 +46,18 @@ class MeshtasticClient internal constructor( private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) private val frameListeners = mutableSetOf<(Uint8Array) -> Unit>() private val client: RadioClient = RadioClient { - transport(TappingTransport(transport) { bytes -> frameListeners.toList().forEach { it(bytes.toUint8Array()) } }) + transport(TappingTransport(transport) { bytes -> forwardFrame(bytes) }) storage(if (storage == null) InMemoryStorageProvider() else JsStorageProvider(storage)) autoReconnect(AutoReconnectConfig(maxAttempts = maxAttempts)) logger(JsLogSink) } + private fun forwardFrame(bytes: ByteArray) { + if (frameListeners.isEmpty() || carriesMeshPacket(bytes)) return + val frame = bytes.toUint8Array() + frameListeners.toList().forEach { it(frame) } + } + init { client.connection .onEach { JsLogSink.log(LogLevel.INFO, "Client", "Connection state: ${it.describe()}", null) } @@ -93,6 +99,7 @@ class MeshtasticClient internal constructor( fun onTelemetry(nodeNum: Int, cb: (Uint8Array) -> Unit): () -> Unit = client.telemetry.observe(NodeId(nodeNum)).onEach { cb(Telemetry.ADAPTER.encode(it).toUint8Array()) }.subscribe() + /** Every `FromRadio` frame except those carrying a `MeshPacket`, which arrive through [onPacket]. */ fun onFromRadio(cb: (Uint8Array) -> Unit): () -> Unit { frameListeners.add(cb) return { frameListeners.remove(cb) } diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Framing.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Framing.kt index c59fd4d18..eda0d0784 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Framing.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Framing.kt @@ -1,5 +1,6 @@ package org.meshtastic.sdk.js +import com.squareup.wire.ProtoReader import okio.Buffer import okio.ByteString import okio.ByteString.Companion.toByteString @@ -89,3 +90,22 @@ internal class FrameAssembler(private val onFrame: (Frame) -> Unit) { } } } + +private const val FROM_RADIO_PACKET_FIELD = 2 + +/** Whether a `FromRadio` payload holds a `MeshPacket`, read from its field tags without decoding it. */ +internal fun carriesMeshPacket(payload: ByteArray): Boolean { + val reader = ProtoReader(Buffer().write(payload)) + try { + reader.beginMessage() + var tag = reader.nextTag() + while (tag != -1) { + if (tag == FROM_RADIO_PACKET_FIELD) return true + reader.skip() + tag = reader.nextTag() + } + } catch (_: Exception) { + return false + } + return false +} diff --git a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/FromRadioFilterTest.kt b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/FromRadioFilterTest.kt new file mode 100644 index 000000000..b8ad30ce0 --- /dev/null +++ b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/FromRadioFilterTest.kt @@ -0,0 +1,33 @@ +package org.meshtastic.sdk.js + +import org.meshtastic.proto.Channel +import org.meshtastic.proto.FromRadio +import org.meshtastic.proto.MeshPacket +import org.meshtastic.proto.MyNodeInfo +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class FromRadioFilterTest { + @Test + fun a_packet_frame_is_recognised_after_the_frame_id() { + val packet = MeshPacket.Builder().also { it.from = 5; it.id = 9 }.build() + val frame = FromRadio.Builder().also { it.id = 77; it.packet = packet }.build() + assertTrue(carriesMeshPacket(FromRadio.ADAPTER.encode(frame))) + } + + @Test + fun handshake_frames_are_not_packets() { + val info = MyNodeInfo.Builder().also { it.my_node_num = 42 }.build() + val myInfo = FromRadio.Builder().also { it.id = 1; it.my_info = info }.build() + val slot = Channel.Builder().also { it.index = 1 }.build() + val channel = FromRadio.Builder().also { it.id = 2; it.channel = slot }.build() + assertFalse(carriesMeshPacket(FromRadio.ADAPTER.encode(myInfo))) + assertFalse(carriesMeshPacket(FromRadio.ADAPTER.encode(channel))) + } + + @Test + fun a_malformed_payload_is_forwarded_rather_than_dropped() { + assertFalse(carriesMeshPacket(byteArrayOf(0x1A, 0x7F, 0x01))) + } +} From dea253daca466ae1f53c63ba7bfdeaf9ede5357d Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 17:15:08 -0500 Subject: [PATCH 37/49] perf(web): publish node updates once per task Each node change copied the whole node map and notified every reader, so a 500-node handshake made 500 copies and renders and every heard packet copied the map again. Changes now land in one draft map that is published in a microtask; reads see pending changes immediately. Claude-Session: https://claude.ai/code/session_01K9vyKS6Q1tGo9xUfNGCUW5 --- apps/web/src/core/kmp/nodes.test.ts | 98 +++++++++++++++++++++++++++ apps/web/src/core/kmp/nodes.ts | 55 +++++++++------ apps/web/src/core/kmp/session.test.ts | 3 +- 3 files changed, 136 insertions(+), 20 deletions(-) create mode 100644 apps/web/src/core/kmp/nodes.test.ts diff --git a/apps/web/src/core/kmp/nodes.test.ts b/apps/web/src/core/kmp/nodes.test.ts new file mode 100644 index 000000000..1f23925b9 --- /dev/null +++ b/apps/web/src/core/kmp/nodes.test.ts @@ -0,0 +1,98 @@ +import { create, toBinary } from "@bufbuild/protobuf"; +import { Protobuf } from "@core/protobuf.ts"; +import { Result } from "better-result"; +import { describe, expect, it } from "vitest"; +import { type NodesAdmin, NodesClient } from "./nodes.ts"; + +const admin: NodesAdmin = { + sendAdmin: () => Promise.resolve(Result.ok(undefined)), + firmwareVersion: () => "2.8.1", + myNodeNum: () => 1, +}; + +function nodeBytes(num: number): Uint8Array { + return toBinary( + Protobuf.Mesh.NodeInfoSchema, + create(Protobuf.Mesh.NodeInfoSchema, { + num, + user: create(Protobuf.Mesh.UserSchema, { longName: `Node ${num}` }), + }), + ); +} + +function heardFrom(from: number, rxTime: number): Protobuf.Mesh.MeshPacket { + return create(Protobuf.Mesh.MeshPacketSchema, { from, rxTime, rxSnr: 5 }); +} + +function countPublishes(client: NodesClient): () => number { + let count = 0; + client.list.subscribe(() => count++); + return () => count; +} + +describe("NodesClient publishing", () => { + it("publishes a handshake's worth of added nodes once", async () => { + const client = new NodesClient(admin); + const publishes = countPublishes(client); + + for (let num = 2; num <= 501; num++) { + client.applyChange({ + kind: "added", + node: nodeBytes(num), + nodes: null, + nodeNum: num, + }); + } + await Promise.resolve(); + + expect(publishes()).toBe(1); + expect(client.list.value).toHaveLength(500); + }); + + it("publishes a burst of heard packets once and keeps the latest values", async () => { + const client = new NodesClient(admin); + client.applyChange({ + kind: "added", + node: nodeBytes(7), + nodes: null, + nodeNum: 7, + }); + await Promise.resolve(); + const publishes = countPublishes(client); + + for (let t = 1; t <= 200; t++) client.heard(heardFrom(7, t)); + await Promise.resolve(); + + expect(publishes()).toBe(1); + expect(client.byNum(7)?.lastHeard).toBe(200); + expect(client.byNum(7)?.user?.longName).toBe("Node 7"); + }); + + it("reads its own pending writes before they publish", () => { + const client = new NodesClient(admin); + client.applyChange({ + kind: "added", + node: nodeBytes(9), + nodes: null, + nodeNum: 9, + }); + client.heard(heardFrom(9, 42)); + + expect(client.byNum(9)?.lastHeard).toBe(42); + expect(client.byNum(9)?.user?.longName).toBe("Node 9"); + }); + + it("drops pending writes when a snapshot replaces the node DB", async () => { + const client = new NodesClient(admin); + client.heard(heardFrom(3, 10)); + client.applyChange({ + kind: "snapshot", + nodes: [nodeBytes(4)], + node: null, + nodeNum: 0, + }); + await Promise.resolve(); + + expect(client.list.value.map((node) => node.num)).toEqual([4]); + }); +}); diff --git a/apps/web/src/core/kmp/nodes.ts b/apps/web/src/core/kmp/nodes.ts index 6a3c40c05..66b0bf980 100644 --- a/apps/web/src/core/kmp/nodes.ts +++ b/apps/web/src/core/kmp/nodes.ts @@ -99,6 +99,7 @@ export interface NodesAdmin { export class NodesClient { private readonly nodes = signal>(new Map()); private readonly errorMap = signal>(new Map()); + private pending: Map | undefined; private epoch = 0; readonly list: ReadonlySignal>; @@ -119,12 +120,9 @@ export class NodesClient { const next = new Map(); for (const bytes of change.nodes ?? []) { const info = fromBinary(Protobuf.Mesh.NodeInfoSchema, bytes); - next.set( - info.num, - this.merged(info, this.nodes.peek().get(info.num)), - ); + next.set(info.num, this.merged(info, this.current().get(info.num))); } - this.nodes.value = next; + this.replace(next); return; } case "added": @@ -146,10 +144,10 @@ export class NodesClient { } private handleIncoming(info: Protobuf.Mesh.NodeInfo): void { - const verdict = validateIncomingNode(info, this.nodes.peek()); + const verdict = validateIncomingNode(info, this.current()); if (verdict.error) this.setError(info.num, verdict.error); if (!verdict.accepted) return; - const node = this.merged(verdict.accepted, this.nodes.peek().get(info.num)); + const node = this.merged(verdict.accepted, this.current().get(info.num)); this.set(node); if (this.errorMap.peek().has(node.num)) this.clearError(node.num); } @@ -188,7 +186,7 @@ export class NodesClient { patch(nodeNum: number, partial: Partial): void { if (nodeNum === 0) return; - const existing = this.nodes.peek().get(nodeNum); + const existing = this.current().get(nodeNum); const next: Node = existing ? { ...existing, ...partial } : { num: nodeNum, isFavorite: false, isIgnored: false, ...partial }; @@ -207,15 +205,35 @@ export class NodesClient { } } - private set(node: Node): void { - const next = new Map(this.nodes.peek()); - next.set(node.num, node); + private current(): ReadonlyMap { + return this.pending ?? this.nodes.peek(); + } + + private draft(): Map { + if (!this.pending) { + this.pending = new Map(this.nodes.peek()); + queueMicrotask(() => this.publish()); + } + return this.pending; + } + + private publish(): void { + if (!this.pending) return; + this.nodes.value = this.pending; + this.pending = undefined; + } + + private replace(next: Map): void { + this.pending = undefined; this.nodes.value = next; } + private set(node: Node): void { + this.draft().set(node.num, node); + } + private delete(nodeNum: number): void { - const next = new Map(this.nodes.peek()); - if (next.delete(nodeNum)) this.nodes.value = next; + if (this.current().has(nodeNum)) this.draft().delete(nodeNum); this.clearError(nodeNum); void this.repository?.remove(nodeNum).catch(() => {}); } @@ -226,11 +244,10 @@ export class NodesClient { try { const persisted = await this.repository.loadAll(); if (epoch !== this.epoch) return; - const next = new Map(this.nodes.peek()); + const next = this.draft(); for (const node of persisted) { if (!next.has(node.num)) next.set(node.num, node); } - this.nodes.value = next; } catch { // nothing stored yet } @@ -239,13 +256,13 @@ export class NodesClient { rescope(scope: number): void { this.repository?.setScope?.(scope); this.epoch++; - this.nodes.value = new Map(); + this.replace(new Map()); this.errorMap.value = new Map(); void this.hydrate(); } byNum(nodeNum: number): Node | undefined { - return this.nodes.peek().get(nodeNum); + return this.current().get(nodeNum); } errorFor(nodeNum: number): NodeError | undefined { @@ -319,9 +336,9 @@ export class NodesClient { const myNodeNum = this.admin.myNodeNum(); const me = options.keepMyNode && myNodeNum !== undefined - ? this.nodes.peek().get(myNodeNum) + ? this.current().get(myNodeNum) : undefined; - this.nodes.value = me ? new Map([[me.num, me]]) : new Map(); + this.replace(me ? new Map([[me.num, me]]) : new Map()); this.errorMap.value = new Map(); try { await this.repository?.clear(); diff --git a/apps/web/src/core/kmp/session.test.ts b/apps/web/src/core/kmp/session.test.ts index a7c9fa731..5d681c43a 100644 --- a/apps/web/src/core/kmp/session.test.ts +++ b/apps/web/src/core/kmp/session.test.ts @@ -286,7 +286,7 @@ describe("MeshSession", () => { expect(channel.value[0]?.state).toBe(MessageState.Delivered); }); - it("mirrors the SDK's node DB and refuses a node presenting another node's key", () => { + it("mirrors the SDK's node DB and refuses a node presenting another node's key", async () => { const { kmp, session } = connected(); const key = new Uint8Array([1, 2, 3]); kmp.emitNodeChange({ @@ -314,6 +314,7 @@ describe("MeshSession", () => { node: null, nodeNum: 0x99, }); + await Promise.resolve(); expect(session.nodes.list.value.map((n) => n.num)).toEqual([PEER]); }); From 898eb0d4c2fac23a1cc17bf80d297b8b23ed5b0b Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 20:23:29 -0500 Subject: [PATCH 38/49] build(sdk-kmp): pin meshtastic-sdk with the browser storage target Points the submodule at the storage-sqldelight js target (cb9d17b). The commit exists only locally until PR1 is pushed; move the pin to the pushed sha before this branch leaves the machine. Claude-Session: https://claude.ai/code/session_01K9vyKS6Q1tGo9xUfNGCUW5 --- packages/sdk-kmp/vendor/meshtastic-sdk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/sdk-kmp/vendor/meshtastic-sdk b/packages/sdk-kmp/vendor/meshtastic-sdk index 7d2128966..cb9d17b1f 160000 --- a/packages/sdk-kmp/vendor/meshtastic-sdk +++ b/packages/sdk-kmp/vendor/meshtastic-sdk @@ -1 +1 @@ -Subproject commit 7d212896682d165ae227314cf6f01f9801ada42b +Subproject commit cb9d17b1f6ce67b47eb8367b55004c1f318199ac From b079c15f05397bb9ac72600fbf9bbecfac5ff484 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 20:26:15 -0500 Subject: [PATCH 39/49] feat(sdk-kmp): bounded SQLDelight browser storage for the SDK Claude-Session: https://claude.ai/code/session_01K9vyKS6Q1tGo9xUfNGCUW5 --- packages/sdk-kmp/build.gradle.kts | 2 + packages/sdk-kmp/settings.gradle.kts | 2 + .../org/meshtastic/sdk/js/BoundedStorage.kt | 83 ++++++++ .../kotlin/org/meshtastic/sdk/js/Client.kt | 10 +- .../kotlin/org/meshtastic/sdk/js/Data.kt | 37 ---- .../kotlin/org/meshtastic/sdk/js/Storage.kt | 129 ++---------- .../meshtastic/sdk/js/BoundedStorageTest.kt | 189 ++++++++++++++++++ 7 files changed, 303 insertions(+), 149 deletions(-) create mode 100644 packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/BoundedStorage.kt create mode 100644 packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/BoundedStorageTest.kt diff --git a/packages/sdk-kmp/build.gradle.kts b/packages/sdk-kmp/build.gradle.kts index a89f1bbb4..187ee56e6 100644 --- a/packages/sdk-kmp/build.gradle.kts +++ b/packages/sdk-kmp/build.gradle.kts @@ -20,9 +20,11 @@ kotlin { sourceSets { jsMain.dependencies { api("org.meshtastic:sdk-core:$sdkVersion") + api("org.meshtastic:sdk-storage-sqldelight:$sdkVersion") } jsTest.dependencies { implementation(kotlin("test")) + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.11.0") } } } diff --git a/packages/sdk-kmp/settings.gradle.kts b/packages/sdk-kmp/settings.gradle.kts index 0dc7bcb8f..2ad987b56 100644 --- a/packages/sdk-kmp/settings.gradle.kts +++ b/packages/sdk-kmp/settings.gradle.kts @@ -27,5 +27,7 @@ includeBuild("vendor/meshtastic-sdk") { substitute(module("org.meshtastic:sdk-core-js")).using(project(":core")) substitute(module("org.meshtastic:sdk-testing")).using(project(":testing")) substitute(module("org.meshtastic:sdk-testing-js")).using(project(":testing")) + substitute(module("org.meshtastic:sdk-storage-sqldelight")).using(project(":storage-sqldelight")) + substitute(module("org.meshtastic:sdk-storage-sqldelight-js")).using(project(":storage-sqldelight")) } } diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/BoundedStorage.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/BoundedStorage.kt new file mode 100644 index 000000000..cdf0bf077 --- /dev/null +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/BoundedStorage.kt @@ -0,0 +1,83 @@ +package org.meshtastic.sdk.js + +import kotlinx.coroutines.withTimeoutOrNull +import org.meshtastic.proto.Channel +import org.meshtastic.proto.NodeInfo +import org.meshtastic.sdk.ConfigBundle +import org.meshtastic.sdk.DeviceStorage +import org.meshtastic.sdk.InMemoryStorageProvider +import org.meshtastic.sdk.NodeId +import org.meshtastic.sdk.SessionPasskey +import org.meshtastic.sdk.StorageProvider +import org.meshtastic.sdk.TransportIdentity + +/** + * Wraps [inner] so a storage backend that hangs or fails can never stall the client: activation that + * does not finish within [timeoutMs] falls back to [fallback], and the first call on an activated + * store that times out or throws switches that store to answering immediately with empty results. + */ +internal class BoundedStorageProvider( + private val inner: StorageProvider, + private val timeoutMs: Long, + private val fallback: StorageProvider = InMemoryStorageProvider(), + private val log: (String) -> Unit, +) : StorageProvider { + override suspend fun activate(identity: TransportIdentity): DeviceStorage { + val activated = withTimeoutOrNull(timeoutMs) { runCatching { inner.activate(identity) } }?.getOrNull() + if (activated != null) return BoundedDeviceStorage(activated, timeoutMs, log) + log("Storage did not activate within ${timeoutMs}ms; continuing in memory") + return fallback.activate(identity) + } +} + +private class BoundedDeviceStorage( + private val inner: DeviceStorage, + private val timeoutMs: Long, + private val log: (String) -> Unit, +) : DeviceStorage { + private var degraded = false + + private suspend fun bounded(default: T, block: suspend () -> T): T { + if (degraded) return default + val result = withTimeoutOrNull(timeoutMs) { runCatching { block() } } + if (result == null || result.isFailure) { + degraded = true + log("Storage stopped responding (${result?.exceptionOrNull()?.message ?: "timed out"}); continuing without it") + return default + } + return result.getOrThrow() + } + + override suspend fun loadNodes(): Map = bounded(emptyMap()) { inner.loadNodes() } + + override suspend fun saveNode(node: NodeInfo) = bounded(Unit) { inner.saveNode(node) } + + override suspend fun removeNode(nodeId: NodeId) = bounded(Unit) { inner.removeNode(nodeId) } + + override suspend fun loadConfig(): ConfigBundle? = bounded(null) { inner.loadConfig() } + + override suspend fun saveConfig(config: ConfigBundle) = bounded(Unit) { inner.saveConfig(config) } + + override suspend fun loadChannels(): List = bounded(emptyList()) { inner.loadChannels() } + + override suspend fun saveChannels(channels: List) = bounded(Unit) { inner.saveChannels(channels) } + + override suspend fun recordOwnNode(nodeNum: NodeId, firmwareVersion: String) = + bounded(Unit) { inner.recordOwnNode(nodeNum, firmwareVersion) } + + override suspend fun clear() = bounded(Unit) { inner.clear() } + + override fun close() { + runCatching { inner.close() } + } + + override suspend fun saveSessionPasskey(passkey: SessionPasskey) = + bounded(Unit) { inner.saveSessionPasskey(passkey) } + + override suspend fun loadSessionPasskey(): SessionPasskey? = bounded(null) { inner.loadSessionPasskey() } + + override suspend fun saveHeartbeat(nodeId: NodeId, epochMillis: Long) = + bounded(Unit) { inner.saveHeartbeat(nodeId, epochMillis) } + + override suspend fun loadHeartbeats(): Map = bounded(emptyMap()) { inner.loadHeartbeats() } +} diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt index c8bdbb184..fc23d2ebb 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Client.kt @@ -41,13 +41,13 @@ import kotlin.js.Promise class MeshtasticClient internal constructor( transport: RadioTransport, private val maxAttempts: Int, - storage: StorageJs? = null, + storage: SdkStorage? = null, ) { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) private val frameListeners = mutableSetOf<(Uint8Array) -> Unit>() private val client: RadioClient = RadioClient { transport(TappingTransport(transport) { bytes -> forwardFrame(bytes) }) - storage(if (storage == null) InMemoryStorageProvider() else JsStorageProvider(storage)) + storage(storage?.provider ?: InMemoryStorageProvider()) autoReconnect(AutoReconnectConfig(maxAttempts = maxAttempts)) logger(JsLogSink) } @@ -182,7 +182,7 @@ fun createHttpClient( url: String, allowPrompt: Boolean = false, maxAttempts: Int = 10, - storage: StorageJs? = null, + storage: SdkStorage? = null, ): MeshtasticClient = MeshtasticClient(HttpTransport(url.trimEnd('/'), allowPrompt), maxAttempts, storage) /** @@ -196,7 +196,7 @@ fun createSerialClient( usbVendorId: Int?, usbProductId: Int?, maxAttempts: Int = 10, - storage: StorageJs? = null, + storage: SdkStorage? = null, ): MeshtasticClient = MeshtasticClient(WebSerialTransport(port, usbVendorId, usbProductId), maxAttempts, storage) /** @@ -209,5 +209,5 @@ fun createBluetoothClient( device: dynamic, deviceId: String?, maxAttempts: Int = 10, - storage: StorageJs? = null, + storage: SdkStorage? = null, ): MeshtasticClient = MeshtasticClient(WebBluetoothTransport(device, deviceId), maxAttempts, storage) diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Data.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Data.kt index d643f7f33..357a1455d 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Data.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Data.kt @@ -3,14 +3,7 @@ package org.meshtastic.sdk.js import org.khronos.webgl.Uint8Array -import org.meshtastic.proto.Channel -import org.meshtastic.proto.Config -import org.meshtastic.proto.DeviceMetadata -import org.meshtastic.proto.DeviceUIConfig -import org.meshtastic.proto.ModuleConfig -import org.meshtastic.proto.MyNodeInfo import org.meshtastic.proto.NodeInfo -import org.meshtastic.sdk.ConfigBundle import org.meshtastic.sdk.NodeChange import org.meshtastic.sdk.SendFailure import org.meshtastic.sdk.SendOutcome @@ -18,16 +11,6 @@ import kotlin.js.ExperimentalJsExport import kotlin.js.JsExport import kotlin.js.Promise -/** The device's config as the handshake delivered it; every field is an encoded protobuf. */ -@JsExport -external interface ConfigBundleJs { - val myInfo: Uint8Array - val metadata: Uint8Array - val configs: Array - val moduleConfigs: Array - val deviceUiConfig: Uint8Array? -} - /** * One change to the node database. `snapshot` carries `nodes`, `added` and * `updated` carry `node` (an encoded `NodeInfo`), `removed`, `went-offline` @@ -56,26 +39,6 @@ external interface SendHandleJs { val outcome: Promise } -internal fun ConfigBundle.toJs(): ConfigBundleJs { - val bundle = jso() - bundle.myInfo = MyNodeInfo.ADAPTER.encode(myInfo).toUint8Array() - bundle.metadata = DeviceMetadata.ADAPTER.encode(metadata).toUint8Array() - bundle.configs = configs.map { Config.ADAPTER.encode(it).toUint8Array() }.toTypedArray() - bundle.moduleConfigs = moduleConfigs.map { ModuleConfig.ADAPTER.encode(it).toUint8Array() }.toTypedArray() - bundle.deviceUiConfig = deviceUIConfig?.let { DeviceUIConfig.ADAPTER.encode(it).toUint8Array() } - return bundle.unsafeCast() -} - -internal fun ConfigBundleJs.toKotlin(): ConfigBundle = ConfigBundle( - myInfo = MyNodeInfo.ADAPTER.decode(myInfo.toByteArray()), - metadata = DeviceMetadata.ADAPTER.decode(metadata.toByteArray()), - configs = configs.map { Config.ADAPTER.decode(it.toByteArray()) }, - moduleConfigs = moduleConfigs.map { ModuleConfig.ADAPTER.decode(it.toByteArray()) }, - deviceUIConfig = deviceUiConfig?.let { DeviceUIConfig.ADAPTER.decode(it.toByteArray()) }, -) - -internal fun List.toJs(): Array = map { Channel.ADAPTER.encode(it).toUint8Array() }.toTypedArray() - internal fun NodeInfo.encodeJs(): Uint8Array = NodeInfo.ADAPTER.encode(this).toUint8Array() internal fun NodeChange.toJs(): NodeChangeJs { diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Storage.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Storage.kt index 33b3da113..8722e9d72 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Storage.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Storage.kt @@ -2,119 +2,34 @@ package org.meshtastic.sdk.js -import kotlinx.coroutines.await -import okio.ByteString.Companion.toByteString -import org.khronos.webgl.Uint8Array -import org.meshtastic.proto.Channel -import org.meshtastic.proto.NodeInfo -import org.meshtastic.sdk.ConfigBundle -import org.meshtastic.sdk.DeviceStorage -import org.meshtastic.sdk.NodeId -import org.meshtastic.sdk.SessionPasskey +import org.meshtastic.sdk.LogLevel import org.meshtastic.sdk.StorageProvider -import org.meshtastic.sdk.TransportIdentity +import org.meshtastic.sdk.storage.sqldelight.SqlDelightStorageProvider +import org.w3c.dom.Worker import kotlin.js.ExperimentalJsExport import kotlin.js.JsExport -import kotlin.js.Promise -/** A host-implemented store the SDK opens before connecting; see the SDK's `StorageProvider`. */ +/** An opaque storage handle created by [createBrowserStorage] and passed to a client factory. */ @JsExport -external interface StorageJs { - fun activate(identity: String): Promise -} - -@JsExport -external interface HeartbeatJs { - val nodeNum: Int - val epochMillis: Double -} - -@JsExport -external interface PasskeyJs { - val bytes: Uint8Array - val expiresAtEpochMs: Double -} +class SdkStorage internal constructor(internal val provider: StorageProvider) /** - * One device's persisted state, as the SDK's `DeviceStorage`. Protobufs - * cross as encoded bytes; `loadConfig` and `loadSessionPasskey` resolve to - * null when nothing is stored. + * Creates SQLDelight storage whose databases run in workers made by [createWorker], bounded so that + * a backend that hangs or fails degrades to in-memory instead of stalling the client. + * + * @param baseDir key prefix for the database index, or `""` for in-memory mode + * @param createWorker starts the worker for one database file + * @param timeoutMs how long one storage call may take before storage is abandoned */ @JsExport -external interface DeviceStorageJs { - fun loadNodes(): Promise> - fun saveNode(nodeInfo: Uint8Array): Promise - fun removeNode(nodeNum: Int): Promise - fun loadConfig(): Promise - fun saveConfig(bundle: ConfigBundleJs): Promise - fun loadChannels(): Promise> - fun saveChannels(channels: Array): Promise - fun recordOwnNode(nodeNum: Int, firmwareVersion: String): Promise - fun clear(): Promise - fun close() - fun saveSessionPasskey(passkey: PasskeyJs): Promise - fun loadSessionPasskey(): Promise - fun saveHeartbeat(nodeNum: Int, epochMillis: Double): Promise - fun loadHeartbeats(): Promise> -} - -internal class JsStorageProvider(private val js: StorageJs) : StorageProvider { - override suspend fun activate(identity: TransportIdentity): DeviceStorage = - JsDeviceStorage(js.activate(identity.raw).await()) -} - -internal class JsDeviceStorage(private val js: DeviceStorageJs) : DeviceStorage { - override suspend fun loadNodes(): Map = - js.loadNodes().await().map { NodeInfo.ADAPTER.decode(it.toByteArray()) }.associateBy { NodeId(it.num) } - - override suspend fun saveNode(node: NodeInfo) { - js.saveNode(node.encodeJs()).await() - } - - override suspend fun removeNode(nodeId: NodeId) { - js.removeNode(nodeId.raw).await() - } - - override suspend fun loadConfig(): ConfigBundle? = js.loadConfig().await()?.toKotlin() - - override suspend fun saveConfig(config: ConfigBundle) { - js.saveConfig(config.toJs()).await() - } - - override suspend fun loadChannels(): List = - js.loadChannels().await().map { Channel.ADAPTER.decode(it.toByteArray()) } - - override suspend fun saveChannels(channels: List) { - js.saveChannels(channels.toJs()).await() - } - - override suspend fun recordOwnNode(nodeNum: NodeId, firmwareVersion: String) { - js.recordOwnNode(nodeNum.raw, firmwareVersion).await() - } - - override suspend fun clear() { - js.clear().await() - } - - override fun close() { - js.close() - } - - override suspend fun saveSessionPasskey(passkey: SessionPasskey) { - val value = jso() - value.bytes = passkey.bytes.toUint8Array() - value.expiresAtEpochMs = passkey.expiresAtEpochMs.toDouble() - js.saveSessionPasskey(value.unsafeCast()).await() - } - - override suspend fun loadSessionPasskey(): SessionPasskey? = js.loadSessionPasskey().await()?.let { - SessionPasskey(it.bytes.toByteArray().toByteString(), it.expiresAtEpochMs.toLong()) - } - - override suspend fun saveHeartbeat(nodeId: NodeId, epochMillis: Long) { - js.saveHeartbeat(nodeId.raw, epochMillis.toDouble()).await() - } - - override suspend fun loadHeartbeats(): Map = - js.loadHeartbeats().await().associate { NodeId(it.nodeNum) to it.epochMillis.toLong() } -} +fun createBrowserStorage( + baseDir: String, + createWorker: (dbFile: String) -> Worker, + timeoutMs: Int = 5000, +): SdkStorage = SdkStorage( + BoundedStorageProvider( + SqlDelightStorageProvider(baseDir, createWorker), + timeoutMs.toLong(), + log = { JsLogSink.log(LogLevel.WARN, "Storage", it, null) }, + ), +) diff --git a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/BoundedStorageTest.kt b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/BoundedStorageTest.kt new file mode 100644 index 000000000..f948ae993 --- /dev/null +++ b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/BoundedStorageTest.kt @@ -0,0 +1,189 @@ +package org.meshtastic.sdk.js + +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.test.currentTime +import kotlinx.coroutines.test.runTest +import okio.ByteString.Companion.encodeUtf8 +import org.meshtastic.proto.Channel +import org.meshtastic.proto.DeviceMetadata +import org.meshtastic.proto.MyNodeInfo +import org.meshtastic.proto.NodeInfo +import org.meshtastic.sdk.ConfigBundle +import org.meshtastic.sdk.DeviceStorage +import org.meshtastic.sdk.NodeId +import org.meshtastic.sdk.SessionPasskey +import org.meshtastic.sdk.StorageProvider +import org.meshtastic.sdk.TransportIdentity +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +private class FakeDeviceStorage : DeviceStorage { + var hangLoadNodes = false + var failSaveConfig = false + val calls = mutableListOf() + + override suspend fun loadNodes(): Map { + calls += "loadNodes" + if (hangLoadNodes) awaitCancellation() + return mapOf(NodeId(1) to node(1)) + } + + override suspend fun saveNode(node: NodeInfo) { + calls += "saveNode:${node.num}" + } + + override suspend fun removeNode(nodeId: NodeId) { + calls += "removeNode:${nodeId.raw}" + } + + override suspend fun loadConfig(): ConfigBundle? { + calls += "loadConfig" + return null + } + + override suspend fun saveConfig(config: ConfigBundle) { + calls += "saveConfig" + if (failSaveConfig) error("boom") + } + + override suspend fun loadChannels(): List { + calls += "loadChannels" + return listOf(channel(2)) + } + + override suspend fun saveChannels(channels: List) { + calls += "saveChannels:${channels.size}" + } + + override suspend fun recordOwnNode(nodeNum: NodeId, firmwareVersion: String) { + calls += "recordOwnNode:${nodeNum.raw}:$firmwareVersion" + } + + override suspend fun clear() { + calls += "clear" + } + + override fun close() { + calls += "close" + } + + override suspend fun saveSessionPasskey(passkey: SessionPasskey) { + calls += "saveSessionPasskey" + } + + override suspend fun loadSessionPasskey(): SessionPasskey? { + calls += "loadSessionPasskey" + return SessionPasskey("k".encodeUtf8(), 9) + } + + override suspend fun saveHeartbeat(nodeId: NodeId, epochMillis: Long) { + calls += "saveHeartbeat:${nodeId.raw}:$epochMillis" + } + + override suspend fun loadHeartbeats(): Map { + calls += "loadHeartbeats" + return mapOf(NodeId(1) to 5L) + } +} + +private class FakeProvider(val storage: FakeDeviceStorage? = null) : StorageProvider { + override suspend fun activate(identity: TransportIdentity): DeviceStorage = storage ?: awaitCancellation() +} + +private fun node(num: Int) = NodeInfo.Builder().also { it.num = num }.build() + +private fun channel(index: Int) = Channel.Builder().also { it.index = index }.build() + +private val identity = TransportIdentity("test") + +class BoundedStorageTest { + private val warnings = mutableListOf() + + private fun bounded(inner: StorageProvider) = BoundedStorageProvider(inner, 5000, log = { warnings += it }) + + @Test + fun activateThatNeverAnswersFallsBackToMemory() = runTest { + val storage = bounded(FakeProvider()).activate(identity) + assertEquals(5000, currentTime) + val node = node(7) + storage.saveNode(node) + assertEquals(mapOf(NodeId(7) to node), storage.loadNodes()) + assertEquals(1, warnings.size) + } + + @Test + fun hungReadDegradesOnceThenAnswersImmediately() = runTest { + val inner = FakeDeviceStorage().apply { hangLoadNodes = true } + val storage = bounded(FakeProvider(inner)).activate(identity) + assertEquals(emptyMap(), storage.loadNodes()) + assertEquals(5000, currentTime) + assertEquals(emptyMap(), storage.loadNodes()) + assertEquals(5000, currentTime) + storage.saveNode(node(3)) + assertEquals(listOf("loadNodes"), inner.calls) + assertEquals(1, warnings.size) + } + + @Test + fun failingWriteCountsAsDone() = runTest { + val inner = FakeDeviceStorage().apply { failSaveConfig = true } + val storage = bounded(FakeProvider(inner)).activate(identity) + storage.saveConfig( + ConfigBundle( + MyNodeInfo.Builder().build(), + DeviceMetadata.Builder().build(), + emptyList(), + emptyList(), + ), + ) + assertNull(storage.loadConfig()) + assertEquals(listOf("saveConfig"), inner.calls) + assertEquals(1, warnings.size) + } + + @Test + fun healthyStoragePassesThrough() = runTest { + val inner = FakeDeviceStorage() + val storage = bounded(FakeProvider(inner)).activate(identity) + val node = node(1) + val bundle = ConfigBundle( + MyNodeInfo.Builder().build(), + DeviceMetadata.Builder().build(), + emptyList(), + emptyList(), + ) + assertEquals(mapOf(NodeId(1) to node), storage.loadNodes()) + storage.saveNode(node) + storage.removeNode(NodeId(1)) + assertNull(storage.loadConfig()) + storage.saveConfig(bundle) + assertEquals(listOf(channel(2)), storage.loadChannels()) + storage.saveChannels(listOf(channel(0))) + storage.recordOwnNode(NodeId(1), "2.5") + storage.clear() + storage.saveSessionPasskey(SessionPasskey("k".encodeUtf8(), 9)) + assertEquals(SessionPasskey("k".encodeUtf8(), 9), storage.loadSessionPasskey()) + storage.saveHeartbeat(NodeId(1), 5) + assertEquals(mapOf(NodeId(1) to 5L), storage.loadHeartbeats()) + storage.close() + assertEquals( + listOf( + "loadNodes", "saveNode:1", "removeNode:1", "loadConfig", "saveConfig", "loadChannels", + "saveChannels:1", "recordOwnNode:1:2.5", "clear", "saveSessionPasskey", "loadSessionPasskey", + "saveHeartbeat:1:5", "loadHeartbeats", "close", + ), + inner.calls, + ) + assertEquals(0, warnings.size) + } + + @Test + fun closeDelegatesWhenDegraded() = runTest { + val inner = FakeDeviceStorage().apply { hangLoadNodes = true } + val storage = bounded(FakeProvider(inner)).activate(identity) + storage.loadNodes() + storage.close() + assertEquals(listOf("loadNodes", "close"), inner.calls) + } +} From ee32e3284a21293fcb9f9fff6d76923ba68dda97 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 20:29:06 -0500 Subject: [PATCH 40/49] feat(web): bundle the SDK's SQLite worker Claude-Session: https://claude.ai/code/session_01K9vyKS6Q1tGo9xUfNGCUW5 --- apps/web/package.json | 1 + apps/web/src/core/kmp/browserStorage.test.ts | 28 +++++++++++++ apps/web/src/core/kmp/browserStorage.ts | 42 +++++++++++++++++++ apps/web/src/core/kmp/sqliteWorker.ts | 4 ++ packages/sdk-kmp/package.json | 4 ++ packages/sdk-kmp/scripts/build.mjs | 22 ++++++++++ .../types/sqlite-opfs-worker-core.d.mts | 3 ++ pnpm-lock.yaml | 3 ++ 8 files changed, 107 insertions(+) create mode 100644 apps/web/src/core/kmp/browserStorage.test.ts create mode 100644 apps/web/src/core/kmp/browserStorage.ts create mode 100644 apps/web/src/core/kmp/sqliteWorker.ts create mode 100644 packages/sdk-kmp/types/sqlite-opfs-worker-core.d.mts diff --git a/apps/web/package.json b/apps/web/package.json index 2c3c33639..5f531e162 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -57,6 +57,7 @@ "@radix-ui/react-toggle-group": "^1.2.1", "@radix-ui/react-tooltip": "^1.4.1", "@radix-ui/react-visually-hidden": "^1.2.13", + "@sqlite.org/sqlite-wasm": "3.51.2-build9", "@tailwindcss/vite": "^4.3.3", "@tanstack/react-router": "^1.170.44", "@tanstack/react-router-devtools": "^1.167.2", diff --git a/apps/web/src/core/kmp/browserStorage.test.ts b/apps/web/src/core/kmp/browserStorage.test.ts new file mode 100644 index 000000000..2ca8dd173 --- /dev/null +++ b/apps/web/src/core/kmp/browserStorage.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vitest"; +import { sqliteWorkerUrl } from "./browserStorage.ts"; + +describe("sqliteWorkerUrl", () => { + it("keeps the dev worker query and appends the db file", () => { + expect( + sqliteWorkerUrl( + "/src/core/kmp/sqliteWorker.ts?worker_file&type=module", + "ab12.db", + "http://localhost:3000/x", + ), + ).toBe( + "http://localhost:3000/src/core/kmp/sqliteWorker.ts?worker_file&type=module&db=ab12.db", + ); + }); + + it("encodes the db file for a production worker asset", () => { + expect( + sqliteWorkerUrl( + "/assets/sqliteWorker-Hx1.js", + ":memory:", + "https://client.meshtastic.org/", + ), + ).toBe( + "https://client.meshtastic.org/assets/sqliteWorker-Hx1.js?db=%3Amemory%3A", + ); + }); +}); diff --git a/apps/web/src/core/kmp/browserStorage.ts b/apps/web/src/core/kmp/browserStorage.ts new file mode 100644 index 000000000..8484c996c --- /dev/null +++ b/apps/web/src/core/kmp/browserStorage.ts @@ -0,0 +1,42 @@ +import type { SdkStorage } from "@meshtastic/sdk-kmp"; +import workerUrl from "./sqliteWorker.ts?worker&url"; +import { loadKmp } from "./client.ts"; + +const STORAGE_BASE_DIR = "meshtastic"; +const STORAGE_TIMEOUT_MS = 5000; + +let storage: Promise | undefined; + +/** + * Builds the URL of the SQLite worker for a database file, keeping any query + * the bundler added (Vite dev appends `?worker_file&type=module`). + */ +export function sqliteWorkerUrl( + workerUrl: string, + dbFile: string, + base: string, +): string { + const url = new URL(workerUrl, base); + const separator = url.search === "" ? "?" : "&"; + return `${url.href}${separator}db=${encodeURIComponent(dbFile)}`; +} + +/** The SDK's browser SQLite storage, created once on first use. */ +export function getSdkStorage(): Promise { + storage ??= loadKmp().then((kmp) => + kmp.createBrowserStorage( + STORAGE_BASE_DIR, + (dbFile) => + new Worker(sqliteWorkerUrl(workerUrl, dbFile, location.href), { + type: "module", + }), + STORAGE_TIMEOUT_MS, + ), + ); + return storage; +} + +/** Forgets the cached storage so the next call creates a fresh one. */ +export function resetSdkStorage(): void { + storage = undefined; +} diff --git a/apps/web/src/core/kmp/sqliteWorker.ts b/apps/web/src/core/kmp/sqliteWorker.ts new file mode 100644 index 000000000..1cd609441 --- /dev/null +++ b/apps/web/src/core/kmp/sqliteWorker.ts @@ -0,0 +1,4 @@ +import sqlite3InitModule from "@sqlite.org/sqlite-wasm"; +import { serveSqliteWorker } from "@meshtastic/sdk-kmp/sqlite-worker-core"; + +serveSqliteWorker(sqlite3InitModule); diff --git a/packages/sdk-kmp/package.json b/packages/sdk-kmp/package.json index 7263a7048..db70e91b8 100644 --- a/packages/sdk-kmp/package.json +++ b/packages/sdk-kmp/package.json @@ -19,6 +19,10 @@ ".": { "types": "./dist/sdk-kmp.d.mts", "default": "./dist/sdk-kmp.mjs" + }, + "./sqlite-worker-core": { + "types": "./dist/sqlite-opfs-worker-core.d.mts", + "default": "./dist/sqlite-opfs-worker-core.mjs" } }, "scripts": { diff --git a/packages/sdk-kmp/scripts/build.mjs b/packages/sdk-kmp/scripts/build.mjs index 73228531a..19bb5190f 100644 --- a/packages/sdk-kmp/scripts/build.mjs +++ b/packages/sdk-kmp/scripts/build.mjs @@ -65,6 +65,28 @@ for (const name of readdirSync(gradleOut)) { if (name === "package.json") continue; cpSync(path.join(gradleOut, name), path.join(dist, name)); } +const workerCoreFiles = [ + [ + path.join( + root, + "vendor/meshtastic-sdk/storage-sqldelight/src/jsMain/resources/sqlite-opfs-worker-core.mjs", + ), + "sqlite-opfs-worker-core.mjs", + ], + [ + path.join(root, "types/sqlite-opfs-worker-core.d.mts"), + "sqlite-opfs-worker-core.d.mts", + ], +]; +for (const [source, name] of workerCoreFiles) { + if (!existsSync(source)) { + console.error( + `@meshtastic/sdk-kmp: missing ${source}; the SQLite worker core must be copied into dist/.`, + ); + process.exit(1); + } + cpSync(source, path.join(dist, name)); +} console.log( `@meshtastic/sdk-kmp: wrote ${readdirSync(dist).length} files to dist/`, ); diff --git a/packages/sdk-kmp/types/sqlite-opfs-worker-core.d.mts b/packages/sdk-kmp/types/sqlite-opfs-worker-core.d.mts new file mode 100644 index 000000000..bb7f23801 --- /dev/null +++ b/packages/sdk-kmp/types/sqlite-opfs-worker-core.d.mts @@ -0,0 +1,3 @@ +export declare function serveSqliteWorker( + sqlite3InitModule: () => Promise, +): void; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ae4ff8292..99a79c662 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -126,6 +126,9 @@ importers: '@radix-ui/react-visually-hidden': specifier: ^1.2.13 version: 1.2.13(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@sqlite.org/sqlite-wasm': + specifier: 3.51.2-build9 + version: 3.51.2-build9 '@tailwindcss/vite': specifier: ^4.3.3 version: 4.3.3(vite@8.3.4(@types/node@26.6.5)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)) From c4b420e34ec68c94ad50bd50ceab5fd7984ad25f Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 20:33:37 -0500 Subject: [PATCH 41/49] feat(web): the SDK keeps its device state in its own SQLite database Claude-Session: https://claude.ai/code/session_01K9vyKS6Q1tGo9xUfNGCUW5 --- .../src/core/connections/repositories.test.ts | 51 ++- apps/web/src/core/connections/repositories.ts | 25 +- apps/web/src/core/kmp/client.ts | 10 +- .../src/core/storage/deviceStorage.test.ts | 178 --------- apps/web/src/core/storage/deviceStorage.ts | 350 ------------------ apps/web/src/core/storage/legacyRows.test.ts | 14 +- .../useConnections.devices.test.tsx | 7 + .../Connections/useConnections.kmp.test.ts | 44 ++- .../pages/Connections/useConnections.test.ts | 7 + .../src/pages/Connections/useConnections.ts | 6 +- 10 files changed, 118 insertions(+), 574 deletions(-) delete mode 100644 apps/web/src/core/storage/deviceStorage.test.ts delete mode 100644 apps/web/src/core/storage/deviceStorage.ts diff --git a/apps/web/src/core/connections/repositories.test.ts b/apps/web/src/core/connections/repositories.test.ts index a254f3987..73f75cf99 100644 --- a/apps/web/src/core/connections/repositories.test.ts +++ b/apps/web/src/core/connections/repositories.test.ts @@ -1,11 +1,22 @@ +import type { SdkStorage } from "@meshtastic/sdk-kmp"; import { createMemoryDb } from "@core/storage/memoryDb.ts"; -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { openRepositories } from "./repositories.ts"; const storage = vi.hoisted( (): { open?: () => Promise<{ db: unknown; persistent: boolean }> } => ({}), ); +const sdk = vi.hoisted((): { storage?: SdkStorage; reject?: Error } => ({})); + +vi.mock("@core/kmp/browserStorage.ts", () => ({ + getSdkStorage: async () => { + if (sdk.reject) throw sdk.reject; + if (!sdk.storage) throw new Error("unscripted"); + return sdk.storage; + }, +})); + vi.mock("@core/sdkStorage.ts", () => ({ getStorageDb: () => { if (!storage.open) throw new Error("unscripted"); @@ -14,39 +25,53 @@ vi.mock("@core/sdkStorage.ts", () => ({ coordinator: undefined, })); +const sentinel: SdkStorage = Object.create(null); + describe("openRepositories", () => { + beforeEach(() => { + sdk.storage = sentinel; + sdk.reject = undefined; + }); + afterEach(() => { vi.useRealTimers(); }); - it("hands the SDK the same database the repositories use", async () => { + it("hands the SDK the its own storage next to the repositories", async () => { const db = await createMemoryDb(); storage.open = async () => ({ db, persistent: true }); const opened = await openRepositories(42); expect(opened.persistent).toBe(true); - expect(opened.sdkStorage).toBeDefined(); + expect(opened.sdkStorage).toBe(sentinel); expect(opened.options.messages).toBeDefined(); - const activated = await opened.sdkStorage?.activate("http:radio"); - expect(activated).toBeDefined(); }); - it("leaves the SDK in memory when the open fails", async () => { + it("hands the SDK its own storage even when sqlocal is unavailable", async () => { storage.open = async () => { throw new Error("OPFS unavailable"); }; const opened = await openRepositories(42); - expect(opened).toEqual({ - persistent: false, - sdkStorage: undefined, - options: {}, - }); + expect(opened.persistent).toBe(false); + expect(opened.options).toEqual({}); + expect(opened.sdkStorage).toBe(sentinel); + }); + + it("leaves the SDK in memory when its own storage cannot be created", async () => { + const db = await createMemoryDb(); + storage.open = async () => ({ db, persistent: true }); + sdk.reject = new Error("no worker"); + + const opened = await openRepositories(42); + + expect(opened.persistent).toBe(true); + expect(opened.sdkStorage).toBeUndefined(); }); - it("leaves the SDK in memory when the open hangs past the timeout", async () => { + it("hands the SDK its storage when sqlocal hangs past the timeout", async () => { vi.useFakeTimers(); storage.open = () => new Promise(() => {}); @@ -55,6 +80,6 @@ describe("openRepositories", () => { const opened = await pending; expect(opened.persistent).toBe(false); - expect(opened.sdkStorage).toBeUndefined(); + expect(opened.sdkStorage).toBe(sentinel); }); }); diff --git a/apps/web/src/core/connections/repositories.ts b/apps/web/src/core/connections/repositories.ts index 96dcb9f5d..5178ff18a 100644 --- a/apps/web/src/core/connections/repositories.ts +++ b/apps/web/src/core/connections/repositories.ts @@ -1,8 +1,8 @@ import type { SessionOptions } from "@core/kmp/session.ts"; -import type { StorageJs } from "@meshtastic/sdk-kmp"; +import { getSdkStorage } from "@core/kmp/browserStorage.ts"; +import type { SdkStorage } from "@meshtastic/sdk-kmp"; import { createLogger } from "@core/log.ts"; import { coordinator, getStorageDb } from "@core/sdkStorage.ts"; -import { sqlocalStorage } from "@core/storage/deviceStorage.ts"; import { SqlocalDraftRepository } from "@core/storage/drafts.ts"; import { SqlocalMessageRepository } from "@core/storage/messages.ts"; import { SqlocalNodesRepository } from "@core/storage/nodes.ts"; @@ -28,20 +28,27 @@ const STORAGE_OPEN_TIMEOUT_MS = 5000; export const UNKNOWN_NODE_SCOPE = -1; /** - * Opens the message, draft, node and telemetry repositories, and the SDK's - * own storage (node DB, config bundle, channels, heartbeats), against the + * Opens the message, draft, node and telemetry repositories against the * shared OPFS-backed SQLite DB, scoped to `nodeNum` (the node this * connection reached last time) so every connection to the same radio * shares one history. If sqlocal is unavailable, hangs longer than * `STORAGE_OPEN_TIMEOUT_MS`, or fails, the session runs without - * persistence, `persistent` is false and `sdkStorage` is undefined so the - * SDK keeps its state in memory too. + * persistence and `persistent` is false. The SDK's own storage comes from + * `getSdkStorage()` independently of that; `sdkStorage` is undefined only + * when it cannot be created, so the SDK keeps its state in memory. */ export async function openRepositories(nodeNum?: number): Promise<{ options: SessionOptions; persistent: boolean; - sdkStorage: StorageJs | undefined; + sdkStorage: SdkStorage | undefined; }> { + const sdkStorage = await getSdkStorage().catch((err: unknown) => { + log.warn("openRepositories: SDK storage unavailable, running in memory", { + name: err instanceof Error ? err.name : undefined, + message: err instanceof Error ? err.message : String(err), + }); + return undefined; + }); const scope = nodeNum ?? UNKNOWN_NODE_SCOPE; try { const t0 = Date.now(); @@ -65,7 +72,7 @@ export async function openRepositories(nodeNum?: number): Promise<{ }); return { persistent, - sdkStorage: sqlocalStorage(async () => db, scope), + sdkStorage, options: { messages: new SqlocalMessageRepository(db, { deviceId: scope, @@ -83,6 +90,6 @@ export async function openRepositories(nodeNum?: number): Promise<{ name: err instanceof Error ? err.name : undefined, message: err instanceof Error ? err.message : String(err), }); - return { persistent: false, sdkStorage: undefined, options: {} }; + return { persistent: false, sdkStorage, options: {} }; } } diff --git a/apps/web/src/core/kmp/client.ts b/apps/web/src/core/kmp/client.ts index 838b84bc9..4499a2ba7 100644 --- a/apps/web/src/core/kmp/client.ts +++ b/apps/web/src/core/kmp/client.ts @@ -1,10 +1,10 @@ import { createLogger } from "@core/log.ts"; -import type { MeshtasticClient, StorageJs } from "@meshtastic/sdk-kmp"; +import type { MeshtasticClient, SdkStorage } from "@meshtastic/sdk-kmp"; export type { ConnectionStateJs, MeshtasticClient, - StorageJs, + SdkStorage, } from "@meshtastic/sdk-kmp"; /** Reconnect attempts the SDK makes before giving up, as the user approved. */ @@ -53,7 +53,7 @@ export function loadKmp(): Promise { export async function createHttpClient( url: string, allowPrompt: boolean, - storage?: StorageJs, + storage?: SdkStorage, ): Promise { const kmp = await loadKmp(); return kmp.createHttpClient( @@ -79,7 +79,7 @@ export interface BluetoothTarget { export async function createSerialClient( target: SerialTarget, - storage?: StorageJs, + storage?: SdkStorage, ): Promise { const kmp = await loadKmp(); return kmp.createSerialClient( @@ -93,7 +93,7 @@ export async function createSerialClient( export async function createBluetoothClient( target: BluetoothTarget, - storage?: StorageJs, + storage?: SdkStorage, ): Promise { const kmp = await loadKmp(); return kmp.createBluetoothClient( diff --git a/apps/web/src/core/storage/deviceStorage.test.ts b/apps/web/src/core/storage/deviceStorage.test.ts deleted file mode 100644 index 8d73315ac..000000000 --- a/apps/web/src/core/storage/deviceStorage.test.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; -import { Protobuf } from "@core/protobuf.ts"; -import { beforeEach, describe, expect, it, vi } from "vitest"; -import type { SqlocalDb } from "./db.ts"; -import type { DeviceStorageJs } from "@meshtastic/sdk-kmp"; -import { boundedDeviceStorage, SqlocalDeviceStorage } from "./deviceStorage.ts"; -import { createMemoryDb } from "./memoryDb.ts"; -import { SqlocalNodesRepository } from "./nodes.ts"; - -const NODE = 0x0a0b0c0d; - -const nodeInfo = (num: number, longName: string) => - toBinary( - Protobuf.Mesh.NodeInfoSchema, - create(Protobuf.Mesh.NodeInfoSchema, { - num, - lastHeard: 1234, - isFavorite: true, - user: create(Protobuf.Mesh.UserSchema, { longName }), - }), - ); - -const bundle = () => ({ - myInfo: toBinary( - Protobuf.Mesh.MyNodeInfoSchema, - create(Protobuf.Mesh.MyNodeInfoSchema, { myNodeNum: NODE }), - ), - metadata: toBinary( - Protobuf.Mesh.DeviceMetadataSchema, - create(Protobuf.Mesh.DeviceMetadataSchema, { firmwareVersion: "2.8.3" }), - ), - configs: [ - toBinary( - Protobuf.Config.ConfigSchema, - create(Protobuf.Config.ConfigSchema, { - payloadVariant: { case: "lora", value: { region: 4 } }, - }), - ), - ], - moduleConfigs: [], - deviceUiConfig: null, -}); - -describe("SqlocalDeviceStorage", () => { - let db: SqlocalDb; - let storage: SqlocalDeviceStorage; - - beforeEach(async () => { - db = await createMemoryDb(); - storage = new SqlocalDeviceStorage(db, NODE); - }); - - it("round-trips nodes and keeps the web's node repository reading them", async () => { - await storage.saveNode(nodeInfo(1, "one")); - await storage.saveNode(nodeInfo(2, "two")); - await storage.saveNode(nodeInfo(1, "uno")); - const loaded = (await storage.loadNodes()).map((bytes) => - fromBinary(Protobuf.Mesh.NodeInfoSchema, bytes), - ); - expect(loaded.map((n) => [n.num, n.user?.longName, n.isFavorite])).toEqual([ - [1, "uno", true], - [2, "two", true], - ]); - - const web = new SqlocalNodesRepository(db, { deviceId: NODE }); - expect((await web.get(1))?.user?.longName).toBe("uno"); - - await storage.removeNode(1); - expect((await storage.loadNodes()).length).toBe(1); - }); - - it("round-trips the config bundle and channels", async () => { - expect(await storage.loadConfig()).toBeNull(); - await storage.saveConfig(bundle()); - const config = await storage.loadConfig(); - expect( - fromBinary( - Protobuf.Mesh.MyNodeInfoSchema, - config?.myInfo ?? new Uint8Array(), - ).myNodeNum, - ).toBe(NODE); - expect(config?.configs).toHaveLength(1); - expect(config?.deviceUiConfig).toBeNull(); - - const channel = (index: number) => - toBinary( - Protobuf.Channel.ChannelSchema, - create(Protobuf.Channel.ChannelSchema, { index }), - ); - await storage.saveChannels([channel(0), channel(1)]); - await storage.saveChannels([channel(0)]); - expect(await storage.loadChannels()).toEqual([channel(0)]); - }); - - it("keeps heartbeats and an unexpired passkey", async () => { - await storage.saveHeartbeat(7, 1000); - await storage.saveHeartbeat(7, 2000); - await storage.saveHeartbeat(8, 3000); - expect(await storage.loadHeartbeats()).toEqual([ - { nodeNum: 7, epochMillis: 2000 }, - { nodeNum: 8, epochMillis: 3000 }, - ]); - - expect(await storage.loadSessionPasskey()).toBeNull(); - await storage.saveSessionPasskey({ - bytes: new Uint8Array([1, 2]), - expiresAtEpochMs: Date.now() + 60_000, - }); - expect((await storage.loadSessionPasskey())?.bytes).toEqual( - new Uint8Array([1, 2]), - ); - await storage.saveSessionPasskey({ - bytes: new Uint8Array([3]), - expiresAtEpochMs: Date.now() - 1, - }); - expect(await storage.loadSessionPasskey()).toBeNull(); - }); - - it("moves to the node the handshake names instead of wiping", async () => { - const unknown = new SqlocalDeviceStorage(db, -1); - await storage.saveNode(nodeInfo(1, "known")); - expect(await unknown.loadNodes()).toEqual([]); - await unknown.recordOwnNode(NODE, "2.8.3"); - expect((await unknown.loadNodes()).length).toBe(1); - - await unknown.clear(); - expect(await storage.loadNodes()).toEqual([]); - }); -}); - -describe("boundedDeviceStorage", () => { - const hanging = (): DeviceStorageJs => ({ - loadNodes: () => new Promise(() => {}), - saveNode: () => new Promise(() => {}), - removeNode: () => new Promise(() => {}), - loadConfig: () => new Promise(() => {}), - saveConfig: () => new Promise(() => {}), - loadChannels: () => new Promise(() => {}), - saveChannels: () => new Promise(() => {}), - recordOwnNode: () => new Promise(() => {}), - clear: () => new Promise(() => {}), - close: () => {}, - saveSessionPasskey: () => new Promise(() => {}), - loadSessionPasskey: () => new Promise(() => {}), - saveHeartbeat: () => new Promise(() => {}), - loadHeartbeats: () => new Promise(() => {}), - }); - - it("answers every read with its empty value when the database never responds", async () => { - vi.useFakeTimers(); - try { - const storage = boundedDeviceStorage(hanging(), 50); - const reads = Promise.all([ - storage.loadConfig(), - storage.loadNodes(), - storage.loadChannels(), - storage.loadSessionPasskey(), - storage.loadHeartbeats(), - ]); - await vi.advanceTimersByTimeAsync(60); - expect(await reads).toEqual([null, [], [], null, []]); - } finally { - vi.useRealTimers(); - } - }); - - it("lets a write that never responds complete, so connect is not held up", async () => { - vi.useFakeTimers(); - try { - const storage = boundedDeviceStorage(hanging(), 50); - const write = storage.saveChannels([]); - await vi.advanceTimersByTimeAsync(60); - await expect(write).resolves.toBeUndefined(); - } finally { - vi.useRealTimers(); - } - }); -}); diff --git a/apps/web/src/core/storage/deviceStorage.ts b/apps/web/src/core/storage/deviceStorage.ts deleted file mode 100644 index 10fb300d0..000000000 --- a/apps/web/src/core/storage/deviceStorage.ts +++ /dev/null @@ -1,350 +0,0 @@ -import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; -import { createLogger } from "@core/log.ts"; -import { Protobuf } from "@core/protobuf.ts"; -import type { - ConfigBundleJs, - DeviceStorageJs, - HeartbeatJs, - PasskeyJs, - StorageJs, -} from "@meshtastic/sdk-kmp"; -import { and, eq } from "drizzle-orm"; -import type { SqlocalDb } from "./db.ts"; -import { - nodes, - sdkChannels, - sdkConfig, - sdkHeartbeats, - sdkOwnNode, - sdkPasskey, -} from "./schema.ts"; -import { base64Decode, base64Encode } from "./types.ts"; - -/** - * The Kotlin SDK's DeviceStorage over the shared sqlocal DB. Rows are - * keyed by node number, like the web's own history, so every connection to - * the same radio shares them: the scope starts as the node this connection - * reached last time and moves to the node the handshake names. - */ -const log = createLogger("deviceStorage"); - -export class SqlocalDeviceStorage implements DeviceStorageJs { - private scope: number; - - constructor( - private readonly db: SqlocalDb, - scope: number, - ) { - this.scope = scope; - } - - async loadNodes(): Promise { - const rows = await this.db - .select() - .from(nodes) - .where(eq(nodes.deviceId, this.scope)); - return rows.map((row) => - row.nodeInfo - ? base64Decode(row.nodeInfo) - : toBinary(Protobuf.Mesh.NodeInfoSchema, legacyNodeInfo(row)), - ); - } - - async saveNode(bytes: Uint8Array): Promise { - const info = fromBinary(Protobuf.Mesh.NodeInfoSchema, bytes); - const row = { - deviceId: this.scope, - num: info.num, - lastHeard: info.lastHeard || null, - snr: info.snr || null, - isFavorite: info.isFavorite, - isIgnored: info.isIgnored, - userJson: info.user - ? base64Encode(toBinary(Protobuf.Mesh.UserSchema, info.user)) - : null, - positionJson: info.position - ? base64Encode(toBinary(Protobuf.Mesh.PositionSchema, info.position)) - : null, - metricsJson: info.deviceMetrics - ? base64Encode( - toBinary( - Protobuf.Telemetry.DeviceMetricsSchema, - info.deviceMetrics, - ), - ) - : null, - nodeInfo: base64Encode(bytes), - }; - await this.db - .insert(nodes) - .values(row) - .onConflictDoUpdate({ target: [nodes.deviceId, nodes.num], set: row }); - } - - async removeNode(nodeNum: number): Promise { - await this.db - .delete(nodes) - .where(and(eq(nodes.deviceId, this.scope), eq(nodes.num, nodeNum))); - } - - async loadConfig(): Promise { - const rows = await this.db - .select() - .from(sdkConfig) - .where(eq(sdkConfig.deviceId, this.scope)) - .limit(1); - const row = rows[0]; - if (!row) return null; - return { - myInfo: base64Decode(row.myInfo), - metadata: base64Decode(row.metadata), - configs: decodeList(row.configs), - moduleConfigs: decodeList(row.moduleConfigs), - deviceUiConfig: row.deviceUiConfig - ? base64Decode(row.deviceUiConfig) - : null, - }; - } - - async saveConfig(bundle: ConfigBundleJs): Promise { - const row = { - deviceId: this.scope, - myInfo: base64Encode(bundle.myInfo), - metadata: base64Encode(bundle.metadata), - configs: encodeList(bundle.configs), - moduleConfigs: encodeList(bundle.moduleConfigs), - deviceUiConfig: bundle.deviceUiConfig - ? base64Encode(bundle.deviceUiConfig) - : null, - }; - await this.db - .insert(sdkConfig) - .values(row) - .onConflictDoUpdate({ target: sdkConfig.deviceId, set: row }); - } - - async loadChannels(): Promise { - const rows = await this.db - .select() - .from(sdkChannels) - .where(eq(sdkChannels.deviceId, this.scope)) - .orderBy(sdkChannels.idx); - return rows.map((row) => base64Decode(row.channel)); - } - - async saveChannels(channels: Uint8Array[]): Promise { - await this.db - .delete(sdkChannels) - .where(eq(sdkChannels.deviceId, this.scope)); - if (channels.length === 0) return; - await this.db.insert(sdkChannels).values( - channels.map((bytes, idx) => ({ - deviceId: this.scope, - idx, - channel: base64Encode(bytes), - })), - ); - } - - /** - * The handshake named the radio. History is keyed by node number, so a - * different node means a different key space rather than a wipe. - */ - async recordOwnNode(nodeNum: number, firmwareVersion: string): Promise { - this.scope = nodeNum; - const row = { deviceId: nodeNum, nodeNum, firmwareVersion }; - await this.db - .insert(sdkOwnNode) - .values(row) - .onConflictDoUpdate({ target: sdkOwnNode.deviceId, set: row }); - } - - async clear(): Promise { - const scope = this.scope; - await this.db.delete(nodes).where(eq(nodes.deviceId, scope)); - await this.db.delete(sdkConfig).where(eq(sdkConfig.deviceId, scope)); - await this.db.delete(sdkChannels).where(eq(sdkChannels.deviceId, scope)); - await this.db - .delete(sdkHeartbeats) - .where(eq(sdkHeartbeats.deviceId, scope)); - await this.db.delete(sdkPasskey).where(eq(sdkPasskey.deviceId, scope)); - await this.db.delete(sdkOwnNode).where(eq(sdkOwnNode.deviceId, scope)); - } - - close(): void {} - - async saveSessionPasskey(passkey: PasskeyJs): Promise { - const row = { - deviceId: this.scope, - passkey: base64Encode(passkey.bytes), - expiresAt: passkey.expiresAtEpochMs, - }; - await this.db - .insert(sdkPasskey) - .values(row) - .onConflictDoUpdate({ target: sdkPasskey.deviceId, set: row }); - } - - async loadSessionPasskey(): Promise { - const rows = await this.db - .select() - .from(sdkPasskey) - .where(eq(sdkPasskey.deviceId, this.scope)) - .limit(1); - const row = rows[0]; - if (!row || row.expiresAt <= Date.now()) return null; - return { - bytes: base64Decode(row.passkey), - expiresAtEpochMs: row.expiresAt, - }; - } - - async saveHeartbeat(nodeNum: number, epochMillis: number): Promise { - const row = { deviceId: this.scope, nodeNum, epochMs: epochMillis }; - await this.db - .insert(sdkHeartbeats) - .values(row) - .onConflictDoUpdate({ - target: [sdkHeartbeats.deviceId, sdkHeartbeats.nodeNum], - set: { epochMs: epochMillis }, - }); - } - - async loadHeartbeats(): Promise { - const rows = await this.db - .select() - .from(sdkHeartbeats) - .where(eq(sdkHeartbeats.deviceId, this.scope)); - return rows.map((row) => ({ - nodeNum: row.nodeNum, - epochMillis: row.epochMs, - })); - } -} - -/** A NodeInfo from the columns the TypeScript SDK's repository wrote. */ -function legacyNodeInfo( - row: typeof nodes.$inferSelect, -): Protobuf.Mesh.NodeInfo { - return create(Protobuf.Mesh.NodeInfoSchema, { - num: row.num, - user: row.userJson - ? fromBinary(Protobuf.Mesh.UserSchema, base64Decode(row.userJson)) - : undefined, - position: row.positionJson - ? fromBinary(Protobuf.Mesh.PositionSchema, base64Decode(row.positionJson)) - : undefined, - deviceMetrics: row.metricsJson - ? fromBinary( - Protobuf.Telemetry.DeviceMetricsSchema, - base64Decode(row.metricsJson), - ) - : undefined, - lastHeard: row.lastHeard ?? 0, - snr: row.snr ?? 0, - isFavorite: row.isFavorite, - isIgnored: row.isIgnored, - }); -} - -function encodeList(items: ReadonlyArray): string { - return JSON.stringify(items.map(base64Encode)); -} - -function decodeList(json: string): Uint8Array[] { - const parsed: unknown = JSON.parse(json); - if (!Array.isArray(parsed)) return []; - return parsed.flatMap((item) => - typeof item === "string" ? [base64Decode(item)] : [], - ); -} - -/** A `StorageJs` for the facade's factories, opening the DB on activation. */ -const STORAGE_CALL_TIMEOUT_MS = 5000; - -function bounded( - call: () => Promise, - fallback: T, - what: string, - timeoutMs: number, -): Promise { - return new Promise((resolve) => { - const timer = setTimeout(() => { - log.warn(`${what} did not answer within ${timeoutMs}ms, continuing`); - resolve(fallback); - }, timeoutMs); - call().then( - (value) => { - clearTimeout(timer); - resolve(value); - }, - (err) => { - clearTimeout(timer); - log.warn(`${what} failed, continuing`, { - message: err instanceof Error ? err.message : String(err), - }); - resolve(fallback); - }, - ); - }); -} - -/** - * The same storage, with every call answered within `timeoutMs`: a read - * falls back to its empty value and a write is treated as done. A database - * whose OPFS handle another tab still holds can then never stall the SDK's - * connect. - */ -export function boundedDeviceStorage( - inner: DeviceStorageJs, - timeoutMs = STORAGE_CALL_TIMEOUT_MS, -): DeviceStorageJs { - const run = (what: string, call: () => Promise, fallback: T) => - bounded(call, fallback, what, timeoutMs); - return { - loadNodes: () => run("loadNodes", () => inner.loadNodes(), []), - saveNode: (node) => run("saveNode", () => inner.saveNode(node), undefined), - removeNode: (nodeNum) => - run("removeNode", () => inner.removeNode(nodeNum), undefined), - loadConfig: () => run("loadConfig", () => inner.loadConfig(), null), - saveConfig: (bundle) => - run("saveConfig", () => inner.saveConfig(bundle), undefined), - loadChannels: () => run("loadChannels", () => inner.loadChannels(), []), - saveChannels: (channels) => - run("saveChannels", () => inner.saveChannels(channels), undefined), - recordOwnNode: (nodeNum, firmwareVersion) => - run( - "recordOwnNode", - () => inner.recordOwnNode(nodeNum, firmwareVersion), - undefined, - ), - clear: () => run("clear", () => inner.clear(), undefined), - close: () => inner.close(), - saveSessionPasskey: (passkey) => - run( - "saveSessionPasskey", - () => inner.saveSessionPasskey(passkey), - undefined, - ), - loadSessionPasskey: () => - run("loadSessionPasskey", () => inner.loadSessionPasskey(), null), - saveHeartbeat: (nodeNum, epochMillis) => - run( - "saveHeartbeat", - () => inner.saveHeartbeat(nodeNum, epochMillis), - undefined, - ), - loadHeartbeats: () => - run("loadHeartbeats", () => inner.loadHeartbeats(), []), - }; -} - -export function sqlocalStorage( - openDb: () => Promise, - scope: number, -): StorageJs { - return { - activate: async () => - boundedDeviceStorage(new SqlocalDeviceStorage(await openDb(), scope)), - }; -} diff --git a/apps/web/src/core/storage/legacyRows.test.ts b/apps/web/src/core/storage/legacyRows.test.ts index 349442539..fbd80cb76 100644 --- a/apps/web/src/core/storage/legacyRows.test.ts +++ b/apps/web/src/core/storage/legacyRows.test.ts @@ -1,10 +1,9 @@ -import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; +import { create, toBinary } from "@bufbuild/protobuf"; import { Protobuf, Types } from "@core/protobuf.ts"; import { drizzle } from "drizzle-orm/sql-js"; import initSqlJs from "sql.js"; import { describe, expect, it } from "vitest"; import type { SqlocalDb } from "./db.ts"; -import { SqlocalDeviceStorage } from "./deviceStorage.ts"; import { SqlocalDraftRepository } from "./drafts.ts"; import { SqlocalMessageRepository } from "./messages.ts"; import { SqlocalNodesRepository } from "./nodes.ts"; @@ -138,17 +137,6 @@ describe("rows written by the TypeScript SDK storage", () => { ? readings[0].value.batteryLevel : undefined, ).toBe(88); - - // The SDK's node DB sees the old row as a NodeInfo until it rewrites it. - const storage = new SqlocalDeviceStorage(db, NODE); - const infos = (await storage.loadNodes()).map((bytes) => - fromBinary(Protobuf.Mesh.NodeInfoSchema, bytes), - ); - expect(infos.map((n) => [n.num, n.user?.shortName, n.snr])).toEqual([ - [PEER, "PR", 7], - ]); - expect(await storage.loadConfig()).toBeNull(); - expect(await storage.loadHeartbeats()).toEqual([]); }); it("is not visible under another node's key", async () => { diff --git a/apps/web/src/pages/Connections/useConnections.devices.test.tsx b/apps/web/src/pages/Connections/useConnections.devices.test.tsx index a7465e60a..840e8ae81 100644 --- a/apps/web/src/pages/Connections/useConnections.devices.test.tsx +++ b/apps/web/src/pages/Connections/useConnections.devices.test.tsx @@ -35,6 +35,13 @@ vi.mock("@core/sdkStorage.ts", () => ({ coordinator: undefined, })); +vi.mock("@core/kmp/browserStorage.ts", () => ({ + getSdkStorage: async () => { + throw new Error("no SDK storage in tests"); + }, + resetSdkStorage: () => {}, +})); + vi.mock("@core/kmp/client.ts", async () => { const { FakeKmpClient } = await import("@core/kmp/fakeClient.ts"); return { diff --git a/apps/web/src/pages/Connections/useConnections.kmp.test.ts b/apps/web/src/pages/Connections/useConnections.kmp.test.ts index fc010b7a6..e04e04932 100644 --- a/apps/web/src/pages/Connections/useConnections.kmp.test.ts +++ b/apps/web/src/pages/Connections/useConnections.kmp.test.ts @@ -4,18 +4,24 @@ import type { Connection } from "@app/core/stores/deviceStore/types"; import { meshRegistry } from "@core/kmp/registry.ts"; import { useDeviceStore } from "@core/stores"; import { Protobuf } from "@core/protobuf.ts"; -import type { StorageJs } from "@meshtastic/sdk-kmp"; +import type { SdkStorage } from "@meshtastic/sdk-kmp"; import { act, renderHook } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { disconnectAllConnections, useConnections } from "./useConnections.ts"; +const calls = vi.hoisted((): string[] => []); + const storage = vi.hoisted(() => ({ close: vi.fn(async () => {}) })); +const sdkStorage = vi.hoisted(() => ({ + reset: vi.fn((): void => {}), +})); + const kmp = vi.hoisted( (): { client?: FakeKmpClient; clients: FakeKmpClient[]; - storages: Array; + storages: Array; connectError?: Error; holdFactory?: Promise; } => ({ clients: [], storages: [] }), @@ -29,13 +35,20 @@ vi.mock("@core/sdkStorage.ts", () => ({ coordinator: undefined, })); +vi.mock("@core/kmp/browserStorage.ts", () => ({ + getSdkStorage: async () => { + throw new Error("no SDK storage in tests"); + }, + resetSdkStorage: sdkStorage.reset, +})); + vi.mock("@core/kmp/client.ts", async () => { const { FakeKmpClient } = await import("@core/kmp/fakeClient.ts"); return { createHttpClient: async ( _url: string, _allowPrompt: boolean, - storage?: StorageJs, + storage?: SdkStorage, ) => { kmp.storages.push(storage); await kmp.holdFactory; @@ -129,6 +142,29 @@ describe("useConnections over the Kotlin SDK (HTTP)", () => { expect(storage.close).toHaveBeenCalledTimes(1); }); + it("takeover forgets the SDK storage", async () => { + const { result } = renderHook(() => useConnections()); + const conn = addRadio(result); + await act(() => result.current.connect(conn.id)); + const client = kmp.client; + if (!client) throw new Error("no client created"); + const disconnect = client.disconnect.bind(client); + client.disconnect = async () => { + await disconnect(); + calls.push("disconnected"); + }; + sdkStorage.reset.mockReset(); + sdkStorage.reset.mockImplementation(() => { + calls.push("reset"); + }); + calls.length = 0; + + await act(() => disconnectAllConnections()); + + expect(sdkStorage.reset).toHaveBeenCalledTimes(1); + expect(calls).toEqual(["disconnected", "reset"]); + }); + it("abandons a connect that was in flight when the app is handed to another tab", async () => { let releaseFactory: () => void = () => {}; kmp.holdFactory = new Promise( @@ -334,7 +370,7 @@ describe("useConnections over the Kotlin SDK (HTTP)", () => { expect(client.disconnects).toHaveLength(1); }); - it("runs the SDK in memory when the web's storage could not be opened", async () => { + it("runs the SDK in memory when its storage could not be created", async () => { const { result } = renderHook(() => useConnections()); const conn = addRadio(result); await act(() => result.current.connect(conn.id)); diff --git a/apps/web/src/pages/Connections/useConnections.test.ts b/apps/web/src/pages/Connections/useConnections.test.ts index dc560832d..2538a0d56 100644 --- a/apps/web/src/pages/Connections/useConnections.test.ts +++ b/apps/web/src/pages/Connections/useConnections.test.ts @@ -21,6 +21,13 @@ vi.mock("@core/sdkStorage.ts", () => ({ coordinator: undefined, })); +vi.mock("@core/kmp/browserStorage.ts", () => ({ + getSdkStorage: async () => { + throw new Error("no SDK storage in tests"); + }, + resetSdkStorage: () => {}, +})); + vi.mock("@core/kmp/client.ts", async () => { const { FakeKmpClient } = await import("@core/kmp/fakeClient.ts"); return { createSerialClient: async () => new FakeKmpClient() }; diff --git a/apps/web/src/pages/Connections/useConnections.ts b/apps/web/src/pages/Connections/useConnections.ts index f6eedc382..edef5de37 100644 --- a/apps/web/src/pages/Connections/useConnections.ts +++ b/apps/web/src/pages/Connections/useConnections.ts @@ -26,7 +26,7 @@ import { createSerialClient, type MeshtasticClient, type SerialTarget, - type StorageJs, + type SdkStorage, } from "@core/kmp/client.ts"; import { editorFor } from "@core/kmp/configEditorIo.ts"; import { @@ -34,6 +34,7 @@ import { reconnectAttempt, toConnectionStatus, } from "@core/kmp/connectionState.ts"; +import { resetSdkStorage } from "@core/kmp/browserStorage.ts"; import { meshRegistry } from "@core/kmp/registry.ts"; import { MeshSession } from "@core/kmp/session.ts"; import { createLogger } from "@core/log.ts"; @@ -118,7 +119,7 @@ async function bluetoothTarget( return { device, deviceId: device.id }; } -type ClientFactory = (storage?: StorageJs) => Promise; +type ClientFactory = (storage?: SdkStorage) => Promise; async function clientFactory( conn: Connection, @@ -193,6 +194,7 @@ export async function disconnectAllConnections(): Promise { for (const id of [...sessionTeardowns.keys()]) { await disconnectConnection(id); } + resetSdkStorage(); await closeStorageDb(); } From ba7eef501a2998426951acb064992749f9a68687 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 20:45:10 -0500 Subject: [PATCH 42/49] fix(web): keep the node list's own table current until the SDK serves it NodesClient writes each published batch of changed nodes, and every node of a snapshot, to its repository with one upsertBatch so a later session hydrates the list it last saw. Claude-Session: https://claude.ai/code/session_01K9vyKS6Q1tGo9xUfNGCUW5 --- apps/web/src/core/kmp/nodes.test.ts | 119 ++++++++++++++++++++++++++++ apps/web/src/core/kmp/nodes.ts | 25 ++++-- 2 files changed, 139 insertions(+), 5 deletions(-) diff --git a/apps/web/src/core/kmp/nodes.test.ts b/apps/web/src/core/kmp/nodes.test.ts index 1f23925b9..170184132 100644 --- a/apps/web/src/core/kmp/nodes.test.ts +++ b/apps/web/src/core/kmp/nodes.test.ts @@ -1,5 +1,6 @@ import { create, toBinary } from "@bufbuild/protobuf"; import { Protobuf } from "@core/protobuf.ts"; +import type { Node, NodesRepository } from "@core/storage/types.ts"; import { Result } from "better-result"; import { describe, expect, it } from "vitest"; import { type NodesAdmin, NodesClient } from "./nodes.ts"; @@ -24,6 +25,44 @@ function heardFrom(from: number, rxTime: number): Protobuf.Mesh.MeshPacket { return create(Protobuf.Mesh.MeshPacketSchema, { from, rxTime, rxSnr: 5 }); } +class FakeNodesRepository implements NodesRepository { + readonly rows = new Map(); + readonly batches: Node[][] = []; + + loadAll(): Promise { + return Promise.resolve([...this.rows.values()]); + } + + get(nodeNum: number): Promise { + return Promise.resolve(this.rows.get(nodeNum)); + } + + upsert(node: Node): Promise { + this.rows.set(node.num, node); + return Promise.resolve(); + } + + upsertBatch(nodes: ReadonlyArray): Promise { + this.batches.push([...nodes]); + for (const node of nodes) this.rows.set(node.num, node); + return Promise.resolve(); + } + + remove(nodeNum: number): Promise { + this.rows.delete(nodeNum); + return Promise.resolve(); + } + + clear(): Promise { + this.rows.clear(); + return Promise.resolve(); + } +} + +function settle(): Promise { + return new Promise((resolve) => setTimeout(resolve, 0)); +} + function countPublishes(client: NodesClient): () => number { let count = 0; client.list.subscribe(() => count++); @@ -96,3 +135,83 @@ describe("NodesClient publishing", () => { expect(client.list.value.map((node) => node.num)).toEqual([4]); }); }); + +describe("NodesClient persistence", () => { + it("writes a handshake's worth of added nodes in one batch", async () => { + const repository = new FakeNodesRepository(); + const client = new NodesClient(admin, repository); + await settle(); + + for (let num = 2; num <= 501; num++) { + client.applyChange({ + kind: "added", + node: nodeBytes(num), + nodes: null, + nodeNum: num, + }); + } + await settle(); + + expect(repository.batches).toHaveLength(1); + expect(repository.batches[0]).toHaveLength(500); + }); + + it("writes a burst of heard packets as one node with the latest lastHeard", async () => { + const repository = new FakeNodesRepository(); + const client = new NodesClient(admin, repository); + await settle(); + client.applyChange({ + kind: "added", + node: nodeBytes(7), + nodes: null, + nodeNum: 7, + }); + await settle(); + repository.batches.length = 0; + + for (let t = 1; t <= 200; t++) client.heard(heardFrom(7, t)); + await settle(); + + expect(repository.batches).toHaveLength(1); + expect(repository.batches[0]?.map((node) => node.num)).toEqual([7]); + expect(repository.batches[0]?.[0]?.lastHeard).toBe(200); + }); + + it("writes every node of a snapshot in one batch", async () => { + const repository = new FakeNodesRepository(); + const client = new NodesClient(admin, repository); + await settle(); + + client.applyChange({ + kind: "snapshot", + nodes: [nodeBytes(4), nodeBytes(5), nodeBytes(6)], + node: null, + nodeNum: 0, + }); + await settle(); + + expect(repository.batches).toHaveLength(1); + expect(repository.batches[0]?.map((node) => node.num)).toEqual([4, 5, 6]); + }); + + it("hydrates a fresh client from the nodes a previous client wrote", async () => { + const repository = new FakeNodesRepository(); + const first = new NodesClient(admin, repository); + await settle(); + first.applyChange({ + kind: "added", + node: nodeBytes(11), + nodes: null, + nodeNum: 11, + }); + first.heard(heardFrom(11, 77)); + await settle(); + + const second = new NodesClient(admin, repository); + await settle(); + + expect(second.list.value.map((node) => node.num)).toEqual([11]); + expect(second.byNum(11)?.lastHeard).toBe(77); + expect(second.byNum(11)?.user?.longName).toBe("Node 11"); + }); +}); diff --git a/apps/web/src/core/kmp/nodes.ts b/apps/web/src/core/kmp/nodes.ts index 66b0bf980..6286c2486 100644 --- a/apps/web/src/core/kmp/nodes.ts +++ b/apps/web/src/core/kmp/nodes.ts @@ -92,14 +92,14 @@ export interface NodesAdmin { /** * The device's node DB as the SDK reports it, plus the per-node errors the * web tracks (PKI collisions and routing failures) and the stored snapshot - * shown until the handshake's node DB arrives. The SDK's storage writes - * every node column this reads, so nothing is written back here except - * removals and resets. + * shown until the handshake's node DB arrives. Every batch of changed nodes + * is written back to the repository so the stored snapshot stays current. */ export class NodesClient { private readonly nodes = signal>(new Map()); private readonly errorMap = signal>(new Map()); private pending: Map | undefined; + private changed = new Set(); private epoch = 0; readonly list: ReadonlySignal>; @@ -123,6 +123,7 @@ export class NodesClient { next.set(info.num, this.merged(info, this.current().get(info.num))); } this.replace(next); + this.persist([...next.values()]); return; } case "added": @@ -218,18 +219,32 @@ export class NodesClient { } private publish(): void { - if (!this.pending) return; - this.nodes.value = this.pending; + const published = this.pending; + if (!published) return; + this.nodes.value = published; this.pending = undefined; + const changed = [...this.changed].flatMap((num) => { + const node = published.get(num); + return node ? [node] : []; + }); + this.changed = new Set(); + this.persist(changed); + } + + private persist(nodes: ReadonlyArray): void { + if (nodes.length === 0) return; + void this.repository?.upsertBatch(nodes).catch(() => {}); } private replace(next: Map): void { this.pending = undefined; + this.changed = new Set(); this.nodes.value = next; } private set(node: Node): void { this.draft().set(node.num, node); + this.changed.add(node.num); } private delete(nodeNum: number): void { From 1f25fe23dd55be98e24bb699842336667c4ac43e Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 20:46:03 -0500 Subject: [PATCH 43/49] fix(sdk-kmp): stay degraded across activations and warn once Once any bounded store degrades or activation falls back, later activations go straight to memory without touching the inner provider. The warning is logged only when the degraded flag flips, an activation failure names its cause, and build --if-missing also rebuilds when the SQLite worker core is missing from dist. Claude-Session: https://claude.ai/code/session_01K9vyKS6Q1tGo9xUfNGCUW5 --- packages/sdk-kmp/scripts/build.mjs | 7 ++- .../org/meshtastic/sdk/js/BoundedStorage.kt | 41 +++++++++------ .../meshtastic/sdk/js/BoundedStorageTest.kt | 52 ++++++++++++++++++- 3 files changed, 83 insertions(+), 17 deletions(-) diff --git a/packages/sdk-kmp/scripts/build.mjs b/packages/sdk-kmp/scripts/build.mjs index 19bb5190f..a8b03cdd6 100644 --- a/packages/sdk-kmp/scripts/build.mjs +++ b/packages/sdk-kmp/scripts/build.mjs @@ -8,8 +8,13 @@ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const dist = path.join(root, "dist"); const gradleOut = path.join(root, "build/dist/js/productionLibrary"); const entry = path.join(dist, "sdk-kmp.mjs"); +const workerCore = path.join(dist, "sqlite-opfs-worker-core.mjs"); -if (process.argv.includes("--if-missing") && existsSync(entry)) { +if ( + process.argv.includes("--if-missing") && + existsSync(entry) && + existsSync(workerCore) +) { process.exit(0); } diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/BoundedStorage.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/BoundedStorage.kt index cdf0bf077..ea064c58f 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/BoundedStorage.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/BoundedStorage.kt @@ -11,38 +11,49 @@ import org.meshtastic.sdk.SessionPasskey import org.meshtastic.sdk.StorageProvider import org.meshtastic.sdk.TransportIdentity -/** - * Wraps [inner] so a storage backend that hangs or fails can never stall the client: activation that - * does not finish within [timeoutMs] falls back to [fallback], and the first call on an activated - * store that times out or throws switches that store to answering immediately with empty results. - */ internal class BoundedStorageProvider( private val inner: StorageProvider, private val timeoutMs: Long, private val fallback: StorageProvider = InMemoryStorageProvider(), - private val log: (String) -> Unit, + log: (String) -> Unit, ) : StorageProvider { + private val health = StorageHealth(log) + override suspend fun activate(identity: TransportIdentity): DeviceStorage { - val activated = withTimeoutOrNull(timeoutMs) { runCatching { inner.activate(identity) } }?.getOrNull() - if (activated != null) return BoundedDeviceStorage(activated, timeoutMs, log) - log("Storage did not activate within ${timeoutMs}ms; continuing in memory") + if (health.degraded) return fallback.activate(identity) + val attempt = withTimeoutOrNull(timeoutMs) { runCatching { inner.activate(identity) } } + val activated = attempt?.getOrNull() + if (activated != null) return BoundedDeviceStorage(activated, timeoutMs, health) + val cause = attempt?.exceptionOrNull()?.message ?: "did not answer within ${timeoutMs}ms" + health.degrade("Storage did not activate ($cause); continuing in memory") return fallback.activate(identity) } } +private class StorageHealth(private val log: (String) -> Unit) { + var degraded = false + private set + + fun degrade(message: String) { + if (!degraded) { + degraded = true + log(message) + } + } +} + private class BoundedDeviceStorage( private val inner: DeviceStorage, private val timeoutMs: Long, - private val log: (String) -> Unit, + private val health: StorageHealth, ) : DeviceStorage { - private var degraded = false - private suspend fun bounded(default: T, block: suspend () -> T): T { - if (degraded) return default + if (health.degraded) return default val result = withTimeoutOrNull(timeoutMs) { runCatching { block() } } if (result == null || result.isFailure) { - degraded = true - log("Storage stopped responding (${result?.exceptionOrNull()?.message ?: "timed out"}); continuing without it") + health.degrade( + "Storage stopped responding (${result?.exceptionOrNull()?.message ?: "timed out"}); continuing without it", + ) return default } return result.getOrThrow() diff --git a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/BoundedStorageTest.kt b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/BoundedStorageTest.kt index f948ae993..29c6f5050 100644 --- a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/BoundedStorageTest.kt +++ b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/BoundedStorageTest.kt @@ -1,5 +1,6 @@ package org.meshtastic.sdk.js +import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.test.currentTime import kotlinx.coroutines.test.runTest @@ -17,9 +18,11 @@ import org.meshtastic.sdk.TransportIdentity import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull +import kotlin.test.assertTrue private class FakeDeviceStorage : DeviceStorage { var hangLoadNodes = false + var hangLoadConfig = false var failSaveConfig = false val calls = mutableListOf() @@ -39,6 +42,7 @@ private class FakeDeviceStorage : DeviceStorage { override suspend fun loadConfig(): ConfigBundle? { calls += "loadConfig" + if (hangLoadConfig) awaitCancellation() return null } @@ -88,7 +92,12 @@ private class FakeDeviceStorage : DeviceStorage { } private class FakeProvider(val storage: FakeDeviceStorage? = null) : StorageProvider { - override suspend fun activate(identity: TransportIdentity): DeviceStorage = storage ?: awaitCancellation() + var activations = 0 + + override suspend fun activate(identity: TransportIdentity): DeviceStorage { + activations++ + return storage ?: awaitCancellation() + } } private fun node(num: Int) = NodeInfo.Builder().also { it.num = num }.build() @@ -178,6 +187,47 @@ class BoundedStorageTest { assertEquals(0, warnings.size) } + @Test + fun degradedStorageKeepsLaterActivationsInMemory() = runTest { + val inner = FakeDeviceStorage().apply { hangLoadConfig = true } + val provider = FakeProvider(inner) + val bounded = bounded(provider) + assertNull(bounded.activate(identity).loadConfig()) + assertEquals(5000, currentTime) + val second = bounded.activate(identity) + assertEquals(5000, currentTime) + assertEquals(1, provider.activations) + val node = node(8) + second.saveNode(node) + assertEquals(mapOf(NodeId(8) to node), second.loadNodes()) + assertEquals(listOf("loadConfig"), inner.calls) + assertEquals(1, warnings.size) + } + + @Test + fun concurrentHungCallsWarnOnce() = runTest { + val inner = FakeDeviceStorage().apply { + hangLoadNodes = true + hangLoadConfig = true + } + val storage = bounded(FakeProvider(inner)).activate(identity) + val nodes = async { storage.loadNodes() } + val config = async { storage.loadConfig() } + assertEquals(emptyMap(), nodes.await()) + assertNull(config.await()) + assertEquals(1, warnings.size) + } + + @Test + fun failedActivationLogsItsCause() = runTest { + val failing = object : StorageProvider { + override suspend fun activate(identity: TransportIdentity): DeviceStorage = error("no opfs") + } + bounded(failing).activate(identity) + assertEquals(1, warnings.size) + assertTrue("no opfs" in warnings.single()) + } + @Test fun closeDelegatesWhenDegraded() = runTest { val inner = FakeDeviceStorage().apply { hangLoadNodes = true } From 20c9a7f541cdbb1073fc6e54ecc445d5ccf573bc Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 20:48:25 -0500 Subject: [PATCH 44/49] build(sdk-kmp): re-pin meshtastic-sdk with the bind-failure fix Claude-Session: https://claude.ai/code/session_01K9vyKS6Q1tGo9xUfNGCUW5 --- packages/sdk-kmp/vendor/meshtastic-sdk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/sdk-kmp/vendor/meshtastic-sdk b/packages/sdk-kmp/vendor/meshtastic-sdk index cb9d17b1f..c3eb54ac3 160000 --- a/packages/sdk-kmp/vendor/meshtastic-sdk +++ b/packages/sdk-kmp/vendor/meshtastic-sdk @@ -1 +1 @@ -Subproject commit cb9d17b1f6ce67b47eb8367b55004c1f318199ac +Subproject commit c3eb54ac3623e77fade42f2608945e64f9fef8e1 From 5bd291b4736f414d24cfdd5327f7efce1ca56fb2 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 20:50:18 -0500 Subject: [PATCH 45/49] chore(web): lint override and storage wiring test oxlint cannot resolve the default export of a ?worker&url import, so import/default is off for browserStorage.ts only. A new test proves the SDK storage openRepositories resolves reaches the client factory, and the storage sentinels are plain frozen objects. Claude-Session: https://claude.ai/code/session_01K9vyKS6Q1tGo9xUfNGCUW5 --- apps/web/.oxlintrc.json | 6 ++++++ .../src/core/connections/repositories.test.ts | 4 ++-- .../Connections/useConnections.kmp.test.ts | 17 ++++++++++++++++- 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/apps/web/.oxlintrc.json b/apps/web/.oxlintrc.json index e457f9f52..05c851ddb 100644 --- a/apps/web/.oxlintrc.json +++ b/apps/web/.oxlintrc.json @@ -20,6 +20,12 @@ "@typescript-eslint/no-explicit-any": "off", "@typescript-eslint/no-non-null-assertion": "off" } + }, + { + "files": ["src/core/kmp/browserStorage.ts"], + "rules": { + "import/default": "off" + } } ] } diff --git a/apps/web/src/core/connections/repositories.test.ts b/apps/web/src/core/connections/repositories.test.ts index 73f75cf99..a84a55aba 100644 --- a/apps/web/src/core/connections/repositories.test.ts +++ b/apps/web/src/core/connections/repositories.test.ts @@ -25,7 +25,7 @@ vi.mock("@core/sdkStorage.ts", () => ({ coordinator: undefined, })); -const sentinel: SdkStorage = Object.create(null); +const sentinel: SdkStorage = Object.freeze({}); describe("openRepositories", () => { beforeEach(() => { @@ -37,7 +37,7 @@ describe("openRepositories", () => { vi.useRealTimers(); }); - it("hands the SDK the its own storage next to the repositories", async () => { + it("hands the SDK its own storage next to the repositories", async () => { const db = await createMemoryDb(); storage.open = async () => ({ db, persistent: true }); diff --git a/apps/web/src/pages/Connections/useConnections.kmp.test.ts b/apps/web/src/pages/Connections/useConnections.kmp.test.ts index e04e04932..5d3188ef7 100644 --- a/apps/web/src/pages/Connections/useConnections.kmp.test.ts +++ b/apps/web/src/pages/Connections/useConnections.kmp.test.ts @@ -17,6 +17,8 @@ const sdkStorage = vi.hoisted(() => ({ reset: vi.fn((): void => {}), })); +const sdkOpened = vi.hoisted((): { storage?: SdkStorage } => ({})); + const kmp = vi.hoisted( (): { client?: FakeKmpClient; @@ -37,7 +39,8 @@ vi.mock("@core/sdkStorage.ts", () => ({ vi.mock("@core/kmp/browserStorage.ts", () => ({ getSdkStorage: async () => { - throw new Error("no SDK storage in tests"); + if (!sdkOpened.storage) throw new Error("no SDK storage in tests"); + return sdkOpened.storage; }, resetSdkStorage: sdkStorage.reset, })); @@ -92,6 +95,7 @@ describe("useConnections over the Kotlin SDK (HTTP)", () => { kmp.clients = []; kmp.storages = []; kmp.connectError = undefined; + sdkOpened.storage = undefined; useDeviceStore.setState({ savedConnections: [] }); }); @@ -378,6 +382,17 @@ describe("useConnections over the Kotlin SDK (HTTP)", () => { expect(kmp.storages).toEqual([undefined]); }); + it("hands the client factory the SDK storage it opened", async () => { + const opened: SdkStorage = Object.freeze({}); + sdkOpened.storage = opened; + const { result } = renderHook(() => useConnections()); + const conn = addRadio(result); + await act(() => result.current.connect(conn.id)); + + expect(kmp.storages).toHaveLength(1); + expect(kmp.storages[0]).toBe(opened); + }); + it("marks a denied Local Network Access permission as a terminal error", async () => { kmp.connectError = named("lna-denied"); const { result } = renderHook(() => useConnections()); From 4ac6a5ec6ec460c39703f7ccc673ffd6fa23b0b0 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 21:03:36 -0500 Subject: [PATCH 46/49] fix(web): drop the toast after disconnecting a connection The drawer already shows the connection as disconnected; the toast only repeated it. Claude-Session: https://claude.ai/code/session_01K9vyKS6Q1tGo9xUfNGCUW5 --- apps/web/public/i18n/locales/en/connections.json | 2 -- .../components/ConnectionsDrawer/ConnectionsList.tsx | 11 +---------- 2 files changed, 1 insertion(+), 12 deletions(-) diff --git a/apps/web/public/i18n/locales/en/connections.json b/apps/web/public/i18n/locales/en/connections.json index 71a74a7c2..cdabe2577 100644 --- a/apps/web/public/i18n/locales/en/connections.json +++ b/apps/web/public/i18n/locales/en/connections.json @@ -45,8 +45,6 @@ }, "toasts": { "connected": "Connected", - "nowDisconnected": "{{name}} is now disconnected", - "disconnected": "Disconnected", "failed": "Failed to connect", "checkConnection": "Check your device or settings and try again", "defaultSet": "Default set", diff --git a/apps/web/src/components/ConnectionsDrawer/ConnectionsList.tsx b/apps/web/src/components/ConnectionsDrawer/ConnectionsList.tsx index c18fafd71..e8c9e7cf0 100644 --- a/apps/web/src/components/ConnectionsDrawer/ConnectionsList.tsx +++ b/apps/web/src/components/ConnectionsDrawer/ConnectionsList.tsx @@ -189,16 +189,7 @@ export const ConnectionsList = ({ addButtonRef }: ConnectionsListProps) => { onCancelDelete={() => setConfirmingId(undefined)} onConnect={() => connectAndClose(c, "toasts.checkConnection")} onRetry={() => connectAndClose(c, "toasts.pickConnectionAgain")} - onDisconnect={async () => { - await disconnect(c.id); - toast({ - title: t("toasts.disconnected"), - description: t("toasts.nowDisconnected", { - name: c.name, - interpolation: { escapeValue: false }, - }), - }); - }} + onDisconnect={() => disconnect(c.id)} onSetDefault={() => { setDefaultConnection(c.id); toast({ From dd087b9582bb5d43c9dfe3e234c7c897c5d34596 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 21:47:27 -0500 Subject: [PATCH 47/49] perf(sdk-kmp): read every queued frame per HTTP poll The HTTP handshake fetched one FromRadio per round trip (~180 ms each, ~250 frames), and after a write it slept until the next 3 s poll, so a connect took ~48 s. Poll with all=true, split the firmware's back-to-back FromRadio messages at each payload field, and wake the poll loop after every send. Connect now takes ~4 s on a Heltec V4. Claude-Session: https://claude.ai/code/session_01K9vyKS6Q1tGo9xUfNGCUW5 --- .../kotlin/org/meshtastic/sdk/js/Framing.kt | 44 ++++++++++++++ .../org/meshtastic/sdk/js/HttpTransport.kt | 12 ++-- .../meshtastic/sdk/js/FromRadioSplitTest.kt | 37 ++++++++++++ .../meshtastic/sdk/js/HttpTransportTest.kt | 59 +++++++++++++++++++ 4 files changed, 148 insertions(+), 4 deletions(-) create mode 100644 packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/FromRadioSplitTest.kt diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Framing.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Framing.kt index eda0d0784..a1f13a7f0 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Framing.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Framing.kt @@ -109,3 +109,47 @@ internal fun carriesMeshPacket(payload: ByteArray): Boolean { } return false } + +private const val FROM_RADIO_ID_FIELD = 1 + +/** + * Splits a `fromradio?all=true` body into its `FromRadio` payloads. The firmware + * writes them back to back with no length prefix; each carries one payload field, + * optionally preceded by its `id`, so every field other than `id` ends a message. + */ +internal fun splitFromRadio(body: ByteArray): List { + val messages = mutableListOf() + var start = 0 + var pos = 0 + fun varint(): Long { + var result = 0L + var shift = 0 + while (pos < body.size && shift < 64) { + val b = body[pos++].toInt() and 0xFF + result = result or ((b and 0x7F).toLong() shl shift) + if (b < 0x80) return result + shift += 7 + } + throw ClientException("transport", "truncated fromradio body") + } + while (pos < body.size) { + val tag = varint() + when ((tag and 7).toInt()) { + 0 -> varint() + 1 -> pos += 8 + 2 -> { + val length = varint().toInt() + pos += length + } + 5 -> pos += 4 + else -> throw ClientException("transport", "unreadable fromradio body") + } + if (pos > body.size) throw ClientException("transport", "truncated fromradio body") + if ((tag ushr 3).toInt() != FROM_RADIO_ID_FIELD) { + messages.add(body.copyOfRange(start, pos)) + start = pos + } + } + if (start != body.size) throw ClientException("transport", "truncated fromradio body") + return messages +} diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/HttpTransport.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/HttpTransport.kt index be7daaa3d..2bf3abc8b 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/HttpTransport.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/HttpTransport.kt @@ -6,7 +6,6 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.await import kotlinx.coroutines.cancel import kotlinx.coroutines.channels.Channel -import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -14,6 +13,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.isActive import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull import org.khronos.webgl.ArrayBuffer import org.khronos.webgl.Uint8Array import org.meshtastic.sdk.Frame @@ -31,6 +31,7 @@ internal class HttpTransport( private val _state = MutableStateFlow(TransportState.Disconnected) override val state: StateFlow = _state.asStateFlow() private val inbound = Channel(Channel.UNLIMITED) + private val wake = Channel(Channel.CONFLATED) private var scope: CoroutineScope? = null override suspend fun connect() { @@ -59,7 +60,7 @@ internal class HttpTransport( _state.value = TransportState.Error(cause, recoverable = cause.kind() != Lna.DENIED) return@launch } - delay(pollMillis) + withTimeoutOrNull(pollMillis) { wake.receive() } } } } @@ -67,10 +68,12 @@ internal class HttpTransport( private suspend fun drain() { while (true) { - val response = request("$baseUrl/api/v1/fromradio?all=false", "GET") + val response = request("$baseUrl/api/v1/fromradio?all=true", "GET") val buffer = (response.arrayBuffer() as Promise).await() if (buffer.byteLength == 0) return - inbound.trySend(Frame(framed(Uint8Array(buffer).toByteArray()))) + for (payload in splitFromRadio(Uint8Array(buffer).toByteArray())) { + inbound.trySend(Frame(framed(payload))) + } } } @@ -86,6 +89,7 @@ internal class HttpTransport( init.body = payloadOf(frame).toUint8Array() val response = fetch("$baseUrl/api/v1/toradio", init).await() if (response.ok != true) throw ClientException("transport", "toradio ${response.status}") + wake.trySend(Unit) } override fun frames(): Flow = inbound.receiveAsFlow() diff --git a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/FromRadioSplitTest.kt b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/FromRadioSplitTest.kt new file mode 100644 index 000000000..1edd55e26 --- /dev/null +++ b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/FromRadioSplitTest.kt @@ -0,0 +1,37 @@ +package org.meshtastic.sdk.js + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith + +class FromRadioSplitTest { + private val myInfo = byteArrayOf(0x1A, 0x02, 0x08, 0x01) + private val nodeInfo = byteArrayOf(0x22, 0x03, 0x08, 0x02, 0x10) + private val configComplete = byteArrayOf(0x38, 0xB9.toByte(), 0x60) + + @Test + fun splits_back_to_back_messages_at_each_payload_field() { + val parts = splitFromRadio(myInfo + nodeInfo + configComplete) + + assertEquals(listOf(myInfo, nodeInfo, configComplete).map { it.toList() }, parts.map { it.toList() }) + } + + @Test + fun keeps_an_id_with_the_payload_that_follows_it() { + val withId = byteArrayOf(0x08, 0x07) + nodeInfo + + val parts = splitFromRadio(myInfo + withId) + + assertEquals(listOf(myInfo, withId).map { it.toList() }, parts.map { it.toList() }) + } + + @Test + fun an_empty_body_holds_no_messages() { + assertEquals(emptyList(), splitFromRadio(ByteArray(0))) + } + + @Test + fun a_truncated_body_is_rejected() { + assertFailsWith { splitFromRadio(myInfo + nodeInfo.copyOfRange(0, 3)) } + } +} diff --git a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/HttpTransportTest.kt b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/HttpTransportTest.kt index a46b7d198..55c5b08ab 100644 --- a/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/HttpTransportTest.kt +++ b/packages/sdk-kmp/src/jsTest/kotlin/org/meshtastic/sdk/js/HttpTransportTest.kt @@ -1,9 +1,13 @@ package org.meshtastic.sdk.js import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.take +import kotlinx.coroutines.flow.toList import kotlinx.coroutines.promise import kotlinx.coroutines.withTimeout +import org.meshtastic.sdk.Frame import org.meshtastic.sdk.TransportState import kotlin.js.Promise import kotlin.test.AfterTest @@ -46,6 +50,61 @@ class HttpTransportTest { js("globalThis.fetch = fetch") } + private class RecordingFetch(var bodies: List) { + val urls = mutableListOf() + } + + private fun installRecordingFetch(recording: RecordingFetch) { + val fetch: (String, dynamic) -> Promise = { url, init -> + if (init.method == "GET") recording.urls.add(url) + val body = if (init.method == "GET" && recording.bodies.isNotEmpty()) { + recording.bodies.first().also { recording.bodies = recording.bodies.drop(1) } + } else { + ByteArray(0) + } + val response = js("({ ok: true, status: 200 })") + response.arrayBuffer = { Promise.resolve(body.toUint8Array().buffer) } + Promise.resolve(response) + } + js("globalThis.fetch = fetch") + } + + @Test + fun one_poll_delivers_every_queued_message_as_its_own_frame() = GlobalScope.promise { + installPage { "granted" } + val myInfo = byteArrayOf(0x1A, 0x02, 0x08, 0x01) + val configComplete = byteArrayOf(0x38, 0x05) + val recording = RecordingFetch(listOf(myInfo + configComplete)) + installRecordingFetch(recording) + val transport = HttpTransport("http://192.168.1.10", allowPrompt = false, pollMillis = 10) + transport.connect() + + val frames = withTimeout(1_000) { transport.frames().take(2).toList() } + transport.disconnect() + + assertEquals(listOf(Frame(framed(myInfo)), Frame(framed(configComplete))), frames) + assertTrue(recording.urls.all { it.endsWith("/api/v1/fromradio?all=true") }) + } + + @Test + fun a_send_polls_at_once_instead_of_waiting_for_the_next_interval() = GlobalScope.promise { + installPage { "granted" } + val recording = RecordingFetch(emptyList()) + installRecordingFetch(recording) + val transport = HttpTransport("http://192.168.1.10", allowPrompt = false, pollMillis = 60_000) + transport.connect() + withTimeout(1_000) { while (recording.urls.isEmpty()) delay(5) } + val polledBeforeSend = recording.urls.size + recording.bodies = listOf(byteArrayOf(0x38, 0x05)) + + transport.send(Frame(framed(byteArrayOf(0x18, 0x05)))) + val frame = withTimeout(1_000) { transport.frames().first() } + transport.disconnect() + + assertEquals(Frame(framed(byteArrayOf(0x38, 0x05))), frame) + assertTrue(recording.urls.size > polledBeforeSend) + } + private suspend fun pollErrorWith(permissionAfterFailure: String): TransportState.Error { var polled = false installPage { if (polled) permissionAfterFailure else "granted" } From 66956d78fcf8a1214aed320497203efa95855c93 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 22:00:46 -0500 Subject: [PATCH 48/49] fix(web): stop the sidebar crashing when a connection drops Sidebar picked its connection with useActiveConnection() || useDefaultConnection() || useFirstSavedConnection(), so it called fewer hooks while a connection was active. When the connection dropped, React saw the hook order change and the store selector read the wrong slot, throwing "Cannot read properties of undefined (reading 'length')" into the error boundary. useDisplayedConnection calls all three every render. Claude-Session: https://claude.ai/code/session_01K9vyKS6Q1tGo9xUfNGCUW5 --- apps/web/src/components/Sidebar.tsx | 12 +---- .../stores/deviceStore/selectors.test.tsx | 51 +++++++++++++++++++ .../src/core/stores/deviceStore/selectors.ts | 11 ++++ apps/web/src/core/stores/index.ts | 1 + 4 files changed, 65 insertions(+), 10 deletions(-) create mode 100644 apps/web/src/core/stores/deviceStore/selectors.test.tsx diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 0a4dee100..05cb4fbd2 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1,4 +1,3 @@ -import { useFirstSavedConnection } from "@app/core/stores/deviceStore/selectors.ts"; import { SidebarButton } from "@components/UI/Sidebar/SidebarButton.tsx"; import { SidebarSection } from "@components/UI/Sidebar/SidebarSection.tsx"; import { Spinner } from "@components/UI/Spinner.tsx"; @@ -9,10 +8,9 @@ import { } from "@core/hooks/useNodesAsProto.ts"; import { type Page, - useActiveConnection, useAppStore, - useDefaultConnection, useDevice, + useDisplayedConnection, useSidebar, } from "@core/stores"; import { useIsMobile } from "@core/hooks/useIsMobile.ts"; @@ -88,13 +86,7 @@ export const Sidebar = ({ children }: SidebarProps) => { const { t } = useTranslation("ui"); const navigate = useNavigate({ from: "/" }); - // Get the active connection from selector (connected > default > first) - const activeConnection = - useActiveConnection() || - // biome-ignore lint/correctness/useHookAtTopLevel: not a react hook - useDefaultConnection() || - // biome-ignore lint/correctness/useHookAtTopLevel: not a hook - useFirstSavedConnection(); + const activeConnection = useDisplayedConnection(); const pathname = useLocation({ select: (location) => location.pathname.replace(/^\//, ""), diff --git a/apps/web/src/core/stores/deviceStore/selectors.test.tsx b/apps/web/src/core/stores/deviceStore/selectors.test.tsx new file mode 100644 index 000000000..11ae05543 --- /dev/null +++ b/apps/web/src/core/stores/deviceStore/selectors.test.tsx @@ -0,0 +1,51 @@ +import { act, renderHook } from "@testing-library/react"; +import { beforeEach, describe, expect, it } from "vitest"; +import { useDeviceStore } from "./index.ts"; +import { useDisplayedConnection } from "./selectors.ts"; +import type { Connection } from "./types.ts"; + +const http: Connection = { + id: 1, + type: "http", + name: "http", + url: "http://meshtastic.local", + createdAt: 0, + status: "connected", +}; +const serial: Connection = { + id: 2, + type: "serial", + name: "Serial", + createdAt: 0, + status: "disconnected", + isDefault: true, +}; + +describe("useDisplayedConnection", () => { + beforeEach(() => { + act(() => { + useDeviceStore.setState({ savedConnections: [http, serial] }); + useDeviceStore.getState().setActiveConnectionId(null); + }); + }); + + it("prefers the active connection, then the default, then the first saved", () => { + act(() => { + useDeviceStore.getState().setActiveConnectionId(http.id); + }); + const { result } = renderHook(() => useDisplayedConnection()); + expect(result.current?.id).toBe(http.id); + + act(() => { + useDeviceStore.getState().setActiveConnectionId(null); + }); + expect(result.current?.id).toBe(serial.id); + + act(() => { + useDeviceStore.setState({ + savedConnections: [http, { ...serial, isDefault: false }], + }); + }); + expect(result.current?.id).toBe(http.id); + }); +}); diff --git a/apps/web/src/core/stores/deviceStore/selectors.ts b/apps/web/src/core/stores/deviceStore/selectors.ts index 7a7852700..93e03309a 100644 --- a/apps/web/src/core/stores/deviceStore/selectors.ts +++ b/apps/web/src/core/stores/deviceStore/selectors.ts @@ -23,6 +23,17 @@ export function useFirstSavedConnection(): Connection | undefined { return useDeviceStore((s) => s.savedConnections.at(0)); } +/** + * Hook to get the connection to show for this device: the active one, else + * the default, else the first saved. + */ +export function useDisplayedConnection(): Connection | undefined { + const active = useActiveConnection(); + const fallback = useDefaultConnection(); + const first = useFirstSavedConnection(); + return active ?? fallback ?? first; +} + export function useAddSavedConnection() { return useDeviceStore((s) => s.addSavedConnection); } diff --git a/apps/web/src/core/stores/index.ts b/apps/web/src/core/stores/index.ts index 135070e82..318d60b5d 100644 --- a/apps/web/src/core/stores/index.ts +++ b/apps/web/src/core/stores/index.ts @@ -17,6 +17,7 @@ export { useConnectionStatus, useDefaultConnection, useDeviceForConnection, + useDisplayedConnection, useFirstSavedConnection, useIsConnected, useIsConnecting, From 85f9acc5d23c402e126a55087a45a16eeca21c01 Mon Sep 17 00:00:00 2001 From: Dan Ditomaso Date: Sun, 15 Nov 2026 22:21:05 -0500 Subject: [PATCH 49/49] build(sdk-kmp): pin the SDK to the pushed storage branch Point the submodule at danditomaso/meshtastic-sdk feat/storage-sqldelight-js (f16c8db, meshtastic/meshtastic-sdk#216, stacked on #215) instead of a local-only commit, and map the SDK's new SendFailure.RateLimited to RATE_LIMIT_EXCEEDED so chat keeps showing "rate limit exceeded". Claude-Session: https://claude.ai/code/session_01K9vyKS6Q1tGo9xUfNGCUW5 --- .gitmodules | 2 +- .../sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Data.kt | 1 + packages/sdk-kmp/vendor/meshtastic-sdk | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.gitmodules b/.gitmodules index c78ab77bc..16b8ee914 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,4 +1,4 @@ [submodule "packages/sdk-kmp/vendor/meshtastic-sdk"] path = packages/sdk-kmp/vendor/meshtastic-sdk url = https://github.com/danditomaso/meshtastic-sdk.git - branch = feat/js-target + branch = feat/storage-sqldelight-js diff --git a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Data.kt b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Data.kt index 357a1455d..1af943681 100644 --- a/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Data.kt +++ b/packages/sdk-kmp/src/jsMain/kotlin/org/meshtastic/sdk/js/Data.kt @@ -93,6 +93,7 @@ internal fun SendFailure.kind(): String = when (this) { SendFailure.MaxRetransmit -> "max-retransmit" SendFailure.Timeout -> "timeout" SendFailure.DutyCycleLimit -> "duty-cycle-limit" + SendFailure.RateLimited -> "RATE_LIMIT_EXCEEDED" SendFailure.Disconnected -> "disconnected" SendFailure.HandshakeFailed -> "handshake-failed" SendFailure.Cancelled -> "cancelled" diff --git a/packages/sdk-kmp/vendor/meshtastic-sdk b/packages/sdk-kmp/vendor/meshtastic-sdk index c3eb54ac3..f16c8db24 160000 --- a/packages/sdk-kmp/vendor/meshtastic-sdk +++ b/packages/sdk-kmp/vendor/meshtastic-sdk @@ -1 +1 @@ -Subproject commit c3eb54ac3623e77fade42f2608945e64f9fef8e1 +Subproject commit f16c8db24515b51b423eb70d4d17a5e6e4cbfd6d