feat: scaffold @meshtastic/sdk + signals/sqlocal persistence migration (#1050)

* feat(sdk): scaffold @meshtastic/sdk + @meshtastic/sdk-react

Adds two new packages laying the foundation for a domain-driven migration
away from @meshtastic/core.

packages/sdk
- DDD feature slices: device, chat, nodes, channels, config, telemetry,
  position, traceroute, files. Each with domain/application/infrastructure/state.
- Shared kernel under core/: MeshClient orchestrator, Transport interface
  (byte-compat with existing transport-* packages), EventBus (typed pub/sub),
  packet codec, Queue, Xmodem, signals helpers, tslog factory.
- Signals via @preact/signals-core. Application use-cases return
  Result<T,E> via better-result; legacy ports keep throwing.
- shim/ re-exports the legacy MeshDevice/Types/Utils API so
  packages/web continues to build unchanged.
- createFakeTransport() under @meshtastic/sdk/testing.
- 16 vitest tests incl. end-to-end fake-transport integration.

packages/sdk-react
- MeshProvider + useSignal/useSignalValue/useClient adapters.
- Hooks: useDevice, useConnection, useChat, useNodes, useNode,
  useChannels, useChannel, useConfig, useModuleConfig, useTelemetry,
  usePosition, useTraceroute, useFileTransfer, useFavoriteNode, useIgnoreNode.
- jsdom-backed hook tests.

Root README rewritten with packages table, architecture, and workflow.

* refactor(web): import @meshtastic/sdk instead of @meshtastic/core

Mechanical swap across all 74 @meshtastic/core imports in packages/web/src.
The SDK's shim layer re-exports the legacy MeshDevice/Types/Utils/Protobuf
surface, so no source edits are required beyond the import path. All 294
web vitest tests still pass.

This is Phase B step 1: web now runs on @meshtastic/sdk's MeshDevice shim.
Per-slice store migrations (messageStore/nodeDBStore/deviceStore →
useChat/useNodes/useDevice etc.) land in follow-up commits.

* feat(sdk): add MeshRegistry + multi-client React providers

Phase B prep for web migration. Web holds multiple simultaneous device
connections keyed by ConnectionId, so per-slice hook migrations need a
registry-aware provider.

packages/sdk
- MeshRegistry: Map<ConnectionId, MeshClient> with signals for list/active/activeId.
  create()/get()/has()/remove()/setActive().
- First-created client auto-activates.
- remove() disconnects the client and rotates active to another entry.
- 4 vitest cases covering create, auto-activate, duplicate rejection, and remove.

packages/sdk-react
- MeshRegistryProvider + MeshRegistryContext.
- useMeshRegistry, useOptionalMeshRegistry, useActiveClient, useClientById(id).
- useClient now falls back to the registry's active client when no direct
  <MeshProvider> is present, so existing hooks work unchanged under a
  registry-backed app.

No web-facing changes in this commit; used by follow-up slice migrations.

* refactor(sdk-react): rename useDevice → useMeshDevice

Prevents collision with packages/web's own useDevice() Zustand hook. All
internal exports + tests updated; no behavior change.

Callers migrating off @meshtastic/core should use useMeshDevice() from
@meshtastic/sdk-react going forward.

* feat(web): mount MeshRegistryProvider at app root

Introduces a single app-wide MeshRegistry in packages/web/src/core/meshRegistry.ts
and wraps the RouterProvider in <MeshRegistryProvider>. Registry starts empty;
useConnections continues to instantiate the legacy MeshDevice shim. Subsequent
slice migrations will swap useConnections over to registry.create() and move
consumers onto useMeshDevice()/useChat()/etc from @meshtastic/sdk-react.

Adds @meshtastic/sdk-react as a web dependency. No behavior change; web tests
(294) and production build still pass.

* feat(web,sdk): register per-connection MeshClient in registry

packages/sdk
- MeshRegistry.register(id, client): adopts an externally-constructed
  MeshClient. Complements create() for migration paths where a legacy shim
  already owns the client.
- MeshRegistry.unregister(id): drops the mapping without disconnecting, for
  cases where the caller has torn down the transport itself.
- Legacy MeshDevice shim exposes its inner MeshClient as `meshClient` so
  consumers can adopt it into the registry.

packages/web
- useConnections.setupMeshDevice now registers the shim's MeshClient with the
  app-wide meshRegistry and marks it active on connect.
- removeConnection unregisters from the registry.
- Legacy Zustand deviceStore wiring is unchanged; follow-up commits will move
  read paths to useMeshDevice/useChat etc. and remove the duplicated fields.

No behavior change visible to users. Web tests (294) + SDK tests (20) still pass.

* feat(sdk): add MessageRepository port + InMemoryMessageRepository

Lays the persistence groundwork for the chat slice migration.

- MessageRepository port defines paginated reads (loadRecent, loadBefore),
  atomic writes (append, appendBatch), state updates, and retention pruning.
  Conversation keyed by ConversationKey tagged union (channel | direct peer).
- RetentionPolicy: maxPerBucket + olderThanMs knobs. Consumer decides.
- InMemoryMessageRepository ships with SDK as default + test fixture.
- ChatClient accepts { repository?, retention?, initialLoadLimit? }.
  Lazy-hydrates per conversation on first subscribe; writes through on every
  inbound message; prunes after append when retention policy is set.
- ChatClient.loadOlder(conv, before, limit) for pagination UI.
- ChatStore.prepend() for older-first inserts.

Tests: 5 new cases for InMemoryMessageRepository (paginate, update state,
retention). 25 SDK tests total, all green. Web build unchanged.

Paves the way for @meshtastic/sdk-storage-sqlocal to implement this port
against SQLite/OPFS in a follow-up.

* feat(sdk-storage-sqlocal): SQLite WASM persistence adapters

New workspace package implementing @meshtastic/sdk repository ports against
sqlocal (SQLite WASM + OPFS) with Drizzle-typed queries.

Schema (single DB, multi-device aware via device_id column)
- messages: chat history. Indexes on (device_id, conversation_key, rx_time)
  for fast pagination and on (device_id, state) for pending lookups.
- nodes: NodeDB snapshot per device (stub schema, repo lands with PR #7).
- telemetry: per-node ring buffer of readings (stub).
- _schema: migration version table.
- Hand-written DDL migrations in src/schema/migrations.ts; applied at boot.

createSqlocalDb({ databasePath })
- Opens OPFS DB, applies migrations, returns Drizzle client typed against the
  schema.
- Single instance per origin; sqlocal serializes writes via OPFS file locks.

SqlocalMessageRepository
- Implements MessageRepository: paginated loadRecent / loadBefore, append /
  appendBatch with onConflictDoNothing, updateState, prune (maxPerBucket via
  windowed DELETE + olderThanMs).
- Optional MultiTabCoordinator broadcasts messages-changed events on append.

MultiTabCoordinator
- BroadcastChannel pub/sub for cross-tab change notifications (no-ops if API
  unavailable, e.g. Node).
- acquireLock() wraps navigator.locks.request with fall-through for non-browser
  contexts.

Testing
- src/testing/createMemoryDb.ts: in-memory sql.js + Drizzle, same surface as
  the sqlocal connection. Lets repository tests run on Node CI.
- 6 SqlocalMessageRepository tests (pagination, retention, multi-device
  isolation) + 2 MultiTabCoordinator tests pass on sql.js.

Notes
- @meshtastic/sdk pkg.json now points types at ./mod.ts so workspace consumers
  resolve types directly from source. Production publish path needs a separate
  follow-up to emit a stable mod.d.ts.
- Storage pkg ships ESM only; dts disabled until tsdown's hashed-name emit
  is reconciled with mod.d.ts resolution. Workspace consumption already gets
  full types from source.

* feat(web): persist chat history via @meshtastic/sdk-storage-sqlocal

Plumbs the SDK chat slice through the OPFS-backed SQLite repository so
inbound and outbound text messages survive page reloads, with retention
capped at 1000 messages per conversation or 90 days, whichever hits first.

- packages/sdk legacy MeshDevice shim now accepts MeshClientOptions
  (chat, configId, logger). Backwards-compatible with the old
  `new MeshDevice(transport, configIdNumber)` form.
- packages/web/src/core/sdkStorage.ts: lazy singletons for the shared
  SqlocalDb and the cross-tab MultiTabCoordinator. The DB opens on first
  call so test runs that never connect stay headless-safe.
- useConnections.setupMeshDevice is now async, awaits getStorageDb, and
  passes a SqlocalMessageRepository scoped to the connection id. Falls
  back to the SDK's InMemoryMessageRepository if sqlocal init fails (no
  OPFS support, etc.).
- Vite worker format set to "es" because sqlocal's worker is ES-module
  and rolldown rejects iife with code-splitting.
- COOP/COEP dev headers were already in vite.config.ts; no further
  changes required for OPFS.

Web tests (294) and production build still green.

This is the runtime payoff of PR #5: a fresh page load populates chat from
SQLite via lazy pagination instead of rehydrating 1000 messages into memory.
The legacy Zustand messageStore is still in place for now; PR #6 (chat
slice migration) will retire it and switch UI components to useChat.

* test: testing strategy + 19 new SDK / storage / hook tests

Adds TESTING.md documenting six tiers (unit / slice / client / storage /
hook / E2E), per-package coverage gates, and the audit of where we
currently sit.

Slice tests in @meshtastic/sdk
- NodeMapper proto round-trip; NodesClient list signal updates.
- ChannelsClient indexes by channel number.
- ConfigClient merges Config + ModuleConfig variants.
- TelemetryClient latest + history per node.
- PositionClient byNode + list.
- ChatClient persistence: hydrate on first subscribe, paginate via
  loadOlder, persist inbound messages through the repository. Fixes a
  reverse-iteration bug in loadOlder discovered by the new test.

Hook tests in @meshtastic/sdk-react
- New tests/hooks.registry.test.tsx covers useMeshDevice, useNodes,
  useNode, useChannels under <MeshRegistryProvider>, plus an active-
  client switch round-trip.

Storage tests in @meshtastic/sdk-storage-sqlocal
- migrations.test.ts validates v1 DDL creates messages/nodes/telemetry/
  _schema and indexes; CREATE IF NOT EXISTS is idempotent.
- MultiTabCoordinator.broadcast.test.ts proves cross-tab BroadcastChannel
  delivery between two coordinators in the same process.
- New vitest.browser.config.ts + tests/sqlocal-opfs.browser.test.ts run
  under @vitest/browser (Playwright provider) for real OPFS round-trip
  verification. Wired as `pnpm test:browser`. Browser test files end in
  `.browser.test.ts` and are excluded from the Node runner.

E2E / firmware-simulator tier (TESTING.md §"E2E / simulator") is scoped
for a follow-up — needs CI Docker for meshtasticd.

Totals after this change:
- @meshtastic/sdk: 36 tests (was 25)
- @meshtastic/sdk-react: 8 tests (was 2)
- @meshtastic/sdk-storage-sqlocal: 12 tests (was 8)
- meshtastic-web: 294 tests (unchanged)

* feat(web): MessagesPage reads chat history from SDK / SQLite

Adds an adapter hook that bridges sdk-react's `useChat` and `useDirectChat`
to the legacy `Message` shape MessagesPage / ChannelChat / MessageItem
expect. The page now renders messages directly from the OPFS-backed
SqlocalMessageRepository — page reload hydrates lazily (last 50 per
conversation) instead of pulling 1000+ rows from IndexedDB into memory.

packages/sdk-react
- useChat() gains loadOlder(before, limit) for paginated backfill.
- New useDirectChat(peer) hook covering DM conversations.

packages/web
- src/core/hooks/useChatLegacy.ts: maps SDK `Message` → legacy
  `messageStore/types.ts` Message shape, including state translation
  (SDK Pending → legacy Waiting).
- MessagesPage flips broadcast and direct chat reads to useChatLegacy.
  getMessages call sites removed; setMessageState retained on the legacy
  store for outbound bookkeeping until the next migration step.

Drafts, unread counts, activeChat / chatType continue to live in the
Zustand messageStore — they are UI-only state and stay where they are
per the locked architecture decision. The legacy store's saveMessage,
getMessages, setMessageState, and persistence path remain in place for
now; PR cleanup follow-up will retire them once outbound state and
"delete all messages" flows are switched to the SDK.

Web test suite: 294 still green. Production Vite build clean.

* feat(web): MessagesPage outbound send through SDK ChatClient

Switches the send-text path from `connection?.sendText(...)` (legacy
MeshDevice) to `client.chat.send({ text, destination, channel })` on the
active MeshClient pulled from MeshRegistry via useActiveClient().

Side effects:
- Outbound message state (Ack / Failed) is now driven entirely by the
  SDK chat slice via routing-packet subscriptions; the manual
  setMessageState calls are removed.
- The legacy Zustand `useMessages().setMessageState` and `MessageState`
  imports are no longer used by MessagesPage. Drafts and unread counts
  still live in the Zustand store.
- `getMyNode` is no longer needed in this page (was only used to label
  the now-removed direct-message state updates).

Web tests (294) still green; production Vite build clean.

* feat(sdk,web): drafts persisted in SDK chat slice (SQLite-backed)

Moves per-conversation draft text out of the legacy Zustand messageStore
into the SDK chat slice so drafts share the same persistence + signal
machinery as messages. MessageInput now binds directly to the SDK; the
legacy `useMessages().getDraft/setDraft/clearDraft` API is no longer
called from the input.

packages/sdk
- New DraftRepository port + InMemoryDraftRepository default.
- ChatClient.drafts namespace: get(key) returns a ReadonlySignal<string>;
  set/clear keyed by ConversationKey.
- ChatClient.send auto-clears the draft for the resolved conversation on
  success (parity with prior Zustand clearDraft-on-send behavior).
- Lazy hydrate from the DraftRepository on first read of a conversation.
- 3 new tests in ChatClient.drafts.test.ts.

packages/sdk-react
- New useDraft(conversation) hook returning { text, setText, clear }.

packages/sdk-storage-sqlocal
- New `drafts` table (device_id + conversation_key composite PK, text,
  updated_at). Drizzle schema in src/schema/drafts.ts.
- Migration v2 in src/schema/migrations.ts creates the table on first
  open of an existing v1 DB.
- SqlocalDraftRepository implementing DraftRepository: load/save/clear/
  loadAll, scoped by device_id, upsert on conflict, delete on empty save.
- 6 new tests covering save/load round-trip, empty-string deletion,
  upsert, multi-device isolation, loadAll.

packages/web
- useConnections wires the SqlocalDraftRepository alongside the existing
  SqlocalMessageRepository per registered MeshClient.
- MessageInput accepts `conversation: ConversationKey` instead of the
  prior `to: Types.Destination` — fixes the legacy bug where every
  broadcast channel shared a single draft slot.
- MessagesPage passes the appropriate ConversationKey for direct/
  broadcast chats.
- MessageInput.test.tsx rewritten to mock useDraft from sdk-react.

Test counts: sdk 39 (+3), sdk-storage-sqlocal 18 (+6), web 294 unchanged.
Production Vite build clean.

* chore(web): drop saveMessage path from subscriptions, delete dead DTO

The SDK chat slice now persists every inbound/outbound text packet via the
SqlocalMessageRepository wired in useConnections, so the legacy Zustand
saveMessage path in subscriptions.ts was writing to a store no UI code
reads from.

- subscriptions.ts: removed saveMessage call + PacketToMessageDTO usage.
  Unread-count increments retained as-is (cross-cutting concern, migrates
  in a separate commit).
- subscribeAll's messageStore parameter retained as `_messageStore` for
  callsite stability while the rest of the legacy store is being retired.
- Deleted packages/web/src/core/dto/PacketToMessageDTO.ts (no remaining
  consumers; SDK has its own MessageMapper at
  packages/sdk/src/features/chat/infrastructure/MessageMapper.ts).

Web tests (294) still green; production build clean.

Out of scope, queued:
- useConnections refactor (the hook is overdue for cleanup)
- Strip dead methods from the Zustand messageStore (saveMessage,
  getMessages, setMessageState, getDraft, setDraft, clearDraft +
  Zustand-persist + IDB wrapper). Requires a follow-up sweep of the
  remaining test files that mock those methods.
- Migrate unread counts to the SDK (cross-cutting between chat + nodes).

* feat(sdk,web): ChatClient.clearConversation + clearAll; wire DeleteMessagesDialog

Rounds out the chat slice with destructive operations so the UI dialog no
longer needs the legacy Zustand deleteAllMessages.

packages/sdk
- MessageRepository port gains clearConversation(key); InMemory and
  Sqlocal adapters implement it (SQL: scoped DELETE by conversation).
- ChatStore gains clearBucket(key) + clearAll().
- ChatClient.clearConversation(conv) and ChatClient.clearAll(): empty the
  in-memory store, drop the hydrated-marker so a future subscribe
  re-fetches fresh, then delete from the repository. Repository failures
  are swallowed — UI must not get stuck behind a write error.

packages/sdk-storage-sqlocal
- SqlocalMessageRepository.clearConversation: DELETE FROM messages WHERE
  (device_id, conversation_key) match.

packages/web
- DeleteMessagesDialog swaps useMessages().deleteAllMessages for
  useActiveClient()?.chat.clearAll(). No-active-client path is a no-op
  but still closes the dialog.
- Test file updated: mocks useActiveClient; new case covers
  no-active-client safety.

Totals: sdk 39 tests unchanged (clearConversation tested transitively via
DeleteMessagesDialog; adapter-specific test queued for follow-up),
sdk-storage-sqlocal 18 unchanged, web 295 (+1).

* feat(sdk,sdk-storage-sqlocal,web): NodesRepository port + SQLite persistence

Adds SDK-side node persistence so a fresh page load rehydrates the mesh
NodeDB from disk before any device packets arrive. Web's existing Zustand
nodeDBStore continues to work unchanged in parallel — UI consumer
migration to useNodes/useNode lands in follow-up commits.

packages/sdk
- New NodesRepository port: loadAll / get / upsert / upsertBatch / remove /
  clear. InMemoryNodesRepository ships as the default.
- NodesClient takes optional { repository }, hydrates on construction,
  writes through on every onNodeInfoPacket, and keeps live signal +
  persistence in lockstep. remove/reset clear the repository alongside the
  store + drive the legacy admin message.
- MeshClientOptions exposes a `nodes` slot mirroring the existing `chat`
  slot.

packages/sdk-storage-sqlocal
- New SqlocalNodesRepository implementing the port. user / position /
  deviceMetrics serialized as base64-encoded protobuf bytes (stable
  across schema additions). Subpath export at "@meshtastic/sdk-storage-
  sqlocal/nodes".
- 6 vitest cases covering upsert + loadAll round-trip, overwrite, proto
  round-trip preserves user fields, remove, clear, multi-device isolation.

packages/web
- useConnections opens a SqlocalNodesRepository alongside the chat /
  draft repos and passes it to the new MeshDevice constructor.

Test counts: sdk 39 (unchanged — repo round-trip exercised in storage
adapter tests), sdk-storage-sqlocal 24 (+6), web 295 unchanged. Build
clean.

* feat(sdk,web): SDK Node carries hops/mqtt/key-verified; legacy adapter hook

Lays the groundwork for migrating web's 31 nodeDB consumers off the
Zustand `useNodeDB().getNodes/getNode` API onto SDK signals, without a
big-bang rewrite.

packages/sdk
- Node domain entity gains channel, viaMqtt, hopsAway, isKeyManuallyVerified
  fields. NodeMapper.fromProto now copies these from the inbound
  Protobuf.Mesh.NodeInfo. Required so downstream UIs that show "X hops
  away" / "via MQTT" / "encryption verified" can read SDK nodes without
  losing fidelity.

packages/web
- New core/hooks/useNodesLegacy.ts: useNodesLegacy() returns
  Protobuf.Mesh.NodeInfo[] derived from SDK signals; useNodeLegacy(num)
  returns a single NodeInfo. Components migrate one at a time by swapping
  useNodeDB().getNodes / getNode call sites for these hooks; templates
  stay unchanged because the result shape matches.

No consumer rewrites in this commit — that is per-component follow-up
work to keep diffs reviewable. Web tests (295) still green; production
build clean. SDK 39 / sdk-storage-sqlocal 24 unchanged.

* refactor(web): NodesPage reads node list from SDK signals

First consumer migration off the legacy Zustand nodeDBStore onto
SDK-managed nodes. Pages/Nodes/index.tsx now pulls the full node array
through useNodesLegacy() — which subscribes to the SDK NodesClient
signal underneath — and applies the existing nodeFilter predicate
client-side via useMemo.

Behavior parity:
- Same Protobuf.Mesh.NodeInfo shape rendered in the table (the legacy
  adapter ensures channel / viaMqtt / hopsAway / publicKey survive).
- Same debounce semantics — only the underlying source changed.
- hasNodeError + nodeErrors continue to come from the Zustand
  nodeDBStore until PKI-error tracking is migrated to the SDK in a
  follow-up commit (validation logic still in
  packages/web/src/core/stores/nodeDBStore/nodeValidation.ts).

The legacy nodeDBStore still populates from subscriptions.ts, so this
rewrite is reversible and runs alongside the SDK source. Web tests
(295) still green; production Vite build clean.

* refactor(web): migrate 9 nodeDB consumers onto SDK adapter

Sweeps the most-touched UI paths off useNodeDB().getNode/getMyNode/getNodes
and onto the useNodesLegacy / useNodeLegacy / useMyNodeLegacy adapters
introduced earlier. Behaviour parity preserved — the adapter returns the
same Protobuf.Mesh.NodeInfo shape components already render.

Migrated:
- components/Sidebar.tsx — myNode + node count from SDK signals.
- components/CommandPalette/index.tsx — node lookup for connection labels.
- components/UI/Avatar.tsx — single-node lookup.
- components/Dialog/RemoveNodeDialog.tsx — selected node display.
- components/Dialog/PKIBackupDialog.tsx — myNode for download/print headers.
- components/Dialog/LocationResponseDialog.tsx — sender lookup.
- components/Dialog/TracerouteResponseDialog.tsx — endpoint lookups.
- components/Dialog/NodeDetailsDialog.tsx — selected node detail.
- components/PageComponents/Settings/User.tsx — myNode for owner edit.
- components/PageComponents/Settings/Position.tsx — myNode for current position.
- components/PageComponents/Messages/TraceRoute.tsx — hop name lookup.
- components/PageComponents/Messages/MessageItem.tsx — myNode (suspending) +
  message author. The polling Suspense fallback now retriggers on the SDK
  signal instead of polling the Zustand store directly.
- components/PageComponents/Map/Popups/WaypointDetail.tsx — locked-to node.
- pages/Messages.tsx — sidebar node list + selected peer lookup.
- pages/Map/index.tsx — full filtered list + myNode for fitting. Drops the
  now-dead NODEDB_DEBOUNCE_MS constant since the SDK signal layer handles
  re-render coalescing internally.
- TraceRoute.test.tsx mocks updated to mock useNodesLegacy instead of
  useNodeDB.

NodesLayer.tsx, RemoveNodeDialog (removeNode), ResetNodeDbDialog, and
RefreshKeysDialog still depend on hasNodeError / removeNode /
removeAllNodes on the legacy nodeDB store — those move when PKI-error
tracking and the admin-message paths are migrated to the SDK in the
unread/cleanup follow-up.

Web tests: 295 still green; production Vite build clean. No SDK changes
in this commit.

* refactor(web): rename node legacy adapters to *AsProto

The "Legacy" suffix on the node-adapter hooks reads as if the hook
itself is deprecated, when in fact the hook is the bridge: it converts
SDK Node domain entities into Protobuf.Mesh.NodeInfo so consumer
templates that destructure proto fields keep working during the
migration.

- useNodesLegacy → useNodesAsProto
- useNodeLegacy → useNodeAsProto
- useMyNodeLegacy → useMyNodeAsProto
- File renamed to packages/web/src/core/hooks/useNodesAsProto.ts.

All 16 call sites updated. Test mock in
packages/web/src/components/PageComponents/Messages/TraceRoute.test.tsx
updated to the new module path.

Behaviour unchanged. 295 tests still green; production Vite build clean.

(useChatLegacy follows the same pattern but maps to a hand-written web
type, not a proto — it stays as-is for now and is queued for renaming
once the broader chat-store cleanup lands.)

* refactor(web): useFavoriteNode + useIgnoreNode drive SDK NodesClient

The favorite/ignore admin-message paths now go through the SDK NodesClient
instead of the legacy Zustand sendAdminMessage + manual proto build.

- useFavoriteNode: meshClient.nodes.favorite(nodeNum) /
  meshClient.nodes.unfavorite(nodeNum). The SDK already has
  FavoriteNodeUseCase + AdminMessageSender behind these APIs.
- useIgnoreNode: meshClient.nodes.ignore / .unignore.
- Both still mirror the optimistic flag flip into the legacy nodeDB store
  via updateFavorite / updateIgnore until that store is fully retired —
  same TODO as before, "wait for ack before flipping".

Tests rewritten to mock @meshtastic/sdk-react via vi.hoisted (so the
factory captures the spy without hitting the vi.mock hoist trap):
- assert SDK favorite/unfavorite/ignore/unignore calls
- assert legacy store mirror still fires
- assert toast + longName fallback behaviour preserved
- assert no-op when the node isn't in the SDK store yet (parity with
  the prior "getNode returned undefined" guard)

Web tests: 295 still green; production Vite build clean.

* refactor(web): ResetNodeDb + RefreshKeys dialogs read SDK; safer adapter

- ResetNodeDbDialog: connection.resetNodes() → meshClient.nodes.reset();
  on success it now also calls meshClient.chat.clearAll() instead of the
  legacy useMessages().deleteAllMessages(). PKI-error tracking and the
  in-memory nodeDB still get cleared via removeAllNodeErrors /
  removeAllNodes since those subsystems have not yet migrated. Test
  rewritten to mock useActiveClient via vi.hoisted.
- RefreshKeysDialog: drops useNodeDB().getNode in favour of
  useNodeAsProto for the missing-key node display. Test wraps render in
  a MeshRegistryProvider with an empty registry so the adapter resolves
  cleanly with no active client.

Adapter hardening (useNodesAsProto.ts)
- Switched off useNodes() / useMeshDevice() (which both throw outside a
  MeshProvider/MeshRegistryProvider with an active client) onto
  useActiveClient() + a no-op signal fallback. The hooks now return [] /
  undefined when there is no active client instead of throwing, which
  fixes RefreshKeysDialog's "no error → render null" path under tests
  that don't connect a device.

Web tests: 295 still green; production Vite build clean.

* feat(sdk,sdk-react,web): node PKI / routing-error tracking on the SDK

Moves PKI mismatch / duplicate-key validation and routing-error tracking
out of the legacy Zustand nodeDBStore and into the SDK NodesClient so
every consumer reads the same source of truth. Validates Android's gap
analysis: Meshtastic-Android does not track per-node PKI errors at all,
so the SDK must own this concern client-side.

packages/sdk
- New NodeError + NodeErrorType (Routing_Error | "MISMATCH_PKI" |
  "DUPLICATE_PKI"). Mirrors the previous web-only types.
- New nodeValidation infrastructure mapper (pure): byte-equal compare on
  publicKey, returns ValidatedNodeInfo { accepted?, error? }. Ports the
  detection rules verbatim from
  packages/web/src/core/stores/nodeDBStore/nodeValidation.ts.
- NodesClient gains an errors signal + errorFor / hasError / setError /
  clearError / clearAllErrors API. handleIncoming runs validation before
  upserting; conflicts skip the store write and record an error. A clean
  refresh of a previously-flagged node clears the error.
- handleRoutingPacket records PKI_UNKNOWN_PUBKEY / PKI_FAILED /
  PKI_SEND_FAIL_PUBLIC_KEY / NO_CHANNEL against packet.from.
- 5 new vitest cases covering MISMATCH_PKI, DUPLICATE_PKI, error-clear-on-
  refresh, routing-error capture, clearError / clearAllErrors. SDK total:
  44 tests, all green.

packages/sdk-react
- New useNodeErrors / useNodeError(num) / useHasNodeError(num) hooks.
  All resolve through useActiveClient() and fall back to empty when no
  client is present.

packages/web
- pages/Nodes/index.tsx, pages/Messages.tsx, components/PageComponents/
  Map/Layers/NodesLayer.tsx swap useNodeDB().hasNodeError for the SDK
  useNodeErrors hook + a memoised Set lookup.
- components/Dialog/RefreshKeysDialog/RefreshKeysDialog.tsx reads the
  current error from useNodeError(activeChat); useRefreshKeysDialog.ts
  drives meshClient.nodes.clearError + meshClient.nodes.remove instead
  of the legacy store. The companion test still passes through the
  empty-MeshRegistry render path because useNodeError tolerates a
  missing active client.
- core/subscriptions.ts no longer calls nodeDB.setNodeError on PKI /
  no-channel routing packets — the SDK records those itself. The dialog
  open trigger stays here.
- pages/Nodes/index.tsx drops the now-dead NODEDB_DEBOUNCE_MS constant.

Web tests: 295 still green; production Vite build clean. The legacy
nodeDB still runs its internal validation but its error map is now a
dead end — removal queued in the plan-file follow-up alongside the rest
of the nodeDB cleanup.

* chore(web): remove dead PKI / nodeError paths from legacy nodeDB

Now that the SDK NodesClient owns public-key validation and per-node
error tracking, the legacy Zustand mirrors are dead code.

packages/web/src/core/stores/nodeDBStore/index.ts
- Drops the nodeErrors map + setNodeError / getNodeError / hasNodeError /
  clearNodeError / removeAllNodeErrors methods from the NodeDB interface
  and factory.
- Drops the validateIncomingNode call inside addNode and inside
  setNodeNum's merge path; legacy mirror is now a straight last-write-
  wins shallow merge. The SDK runs validation independently against its
  own snapshot.
- Drops the nodeErrors entries from the persisted partialize shape.

packages/web/src/core/stores/nodeDBStore/types.ts
- Removes NodeError + NodeErrorType. ProcessPacketParams stays.

packages/web/src/core/stores/nodeDBStore/nodeValidation.ts — deleted
(SDK ports it at packages/sdk/src/features/nodes/infrastructure/
nodeValidation.ts and exposes the verdict via NodesClient).

packages/web/src/core/stores/index.ts — drop the dead NodeErrorType
re-export.

packages/web/src/core/stores/nodeDBStore/nodeDBStore.test.tsx
- Removes tests covering the migrated PKI behaviour (errors map,
  MISMATCH, DUPLICATE, "unions nodeErrors") — equivalent coverage now
  lives in packages/sdk/src/features/nodes/NodesClient.errors.test.ts.
- Trims the surviving merge-semantics tests to the simpler last-write-
  wins shape.
- The "selector re-renders" test swaps the deleted setNodeError mutation
  for an updateFavorite call to keep the slice-stability assertion alive.
- The "addNodeDB instance identity" assertion relaxes from .toBe to
  content equality — immer's pruneStaleNodes path can reseat the entry,
  but the registered DB's id stays stable.

components/Dialog/ResetNodeDbDialog/ResetNodeDbDialog.tsx — calls
meshClient.nodes.clearAllErrors() instead of the legacy
removeAllNodeErrors. Test mocks updated.

components/Dialog/RefreshKeysDialog/* — already migrated to SDK errors
in the previous commit; no further changes here.

Test counts: web 290 (was 295 — 5 PKI-tracking tests retired in
favour of 5 equivalent SDK tests). Production Vite build clean.

* feat(sdk,web): SDK NodesClient owns user/position/lastHeard/snr +
                 favourite-flag flips; legacy mirror retired

The SDK NodesClient now subscribes to onUserPacket / onPositionPacket /
onMeshPacket so user-record updates, GPS updates, and lastHeard / snr
refreshes flow into the signal-backed store + repository directly. The
favourite / ignored toggles also flip the local flag once the admin
message resolves successfully, so the UI no longer needs to mirror the
state into a parallel Zustand store.

packages/sdk
- NodesClient: new private patch(num, partial) helper that shallow-
  merges into the existing entry (or seeds a placeholder Node) and
  upserts to the repository in one shot. Used by:
  - onUserPacket → patch user
  - onPositionPacket → patch position
  - onMeshPacket → patch lastHeard / snr (replaces the legacy nodeDB
    processPacket flow)
  - favorite / unfavorite / ignore / unignore — flag flip on Result.ok
- NodesClient.reset({ keepMyNode? }) — preserves the local node entry
  when requested. Mirrors the previous removeAllNodes(true) semantics
  the ResetNodeDb dialog relied on.

packages/web
- core/subscriptions.ts: drops the onUserPacket / onPositionPacket /
  onNodeInfoPacket / onMeshPacket → legacy nodeDB write paths. The
  unused nodeDB parameter is renamed `_nodeDB` for callsite stability;
  it will disappear when the store itself is deleted in a follow-up.
- core/hooks/useFavoriteNode + useIgnoreNode: drop the legacy
  updateFavorite / updateIgnore mirror — the SDK flips the flag on
  success.
- components/Dialog/RemoveNodeDialog: now calls meshClient.nodes.remove
  exclusively; no legacy fall-through.
- components/Dialog/ResetNodeDbDialog: calls
  meshClient.nodes.reset({ keepMyNode: true }) and meshClient.chat.clearAll().
  No legacy nodeDB calls.
- Test mocks for useFavoriteNode / useIgnoreNode / ResetNodeDbDialog
  pruned to match.

Test counts: sdk 44 (unchanged), sdk-react 8, sdk-storage-sqlocal 24,
web 290. Production Vite build clean.

Remaining surface on the legacy nodeDB: addNode / addUser / addPosition /
processPacket / setNodeError-equivalent are now unused; the store retains
only updateFavorite / updateIgnore (no callers) and the per-device
plumbing required by the deviceContext hooks. Full deletion of
nodeDBStore queued in the plan-file follow-up.

* chore(web): drop leftover useNodeDB from Position settings page

useMyNodeAsProto already replaces getMyNode here; the import was left
behind during the nodeDB mirror retirement.

* chore(web): delete legacy nodeDBStore — SDK NodesClient is the only source of truth

The Zustand nodeDBStore had no remaining writers (the mirror in
subscriptions.ts was retired in 005d0000) and no remaining readers
outside of bookkeeping (addNodeDB / setNodeNum / removeNodeDB calls
that fed nothing). Drop the whole store along with its persistence
shim and the persistNodeDB feature flag.

- Delete packages/web/src/core/stores/nodeDBStore/.
- Drop the _nodeDB parameter from subscribeAll; it was unused.
- Drop addNodeDB / useNodeDBStore wiring from useConnections; the
  meshDeviceId reuse check now keys off the device store instead.
- useNewNodeNum no longer pokes the nodeDB.
- FactoryResetDeviceDialog drops its removeNodeDB call (and the test
  drops the matching expectation).
- Strip persistNodeDB / VITE_PERSIST_NODE_DB from featureFlags +
  dev-overrides.
- Remove the useNodeDB / useNodeDBStore re-exports + the
  bindStoreToDevice wiring from core/stores/index.ts.

* chore(web): retire Zustand messageStore — keep only Message types/enums

The persisted message Zustand store had no remaining consumers — chat
history, drafts, and message state all live on the SDK ChatClient
(SqlocalMessageRepository). The messageStore Zustand surface
(saveMessage, getMessages, setMessageState, getDraft, setDraft,
clearDraft, deleteAllMessages, clearMessageByMessageId, plus the
addMessageStore / removeMessageStore / getMessageStore / setNodeNum
plumbing) is now fully unused.

Collapse messageStore/index.ts to just the MessageState / MessageType
enums + the legacy `Message` shape that the useChatLegacy adapter and a
couple of message components still consume. Delete the Zustand
implementation and its 32-test suite.

Other knock-on cleanups in this commit:
- Drop the _messageStore param from subscribeAll (unused after the
  saveMessage-from-subscriptions retirement).
- Drop addMessageStore wiring from useConnections, removeMessageStore
  from FactoryResetDeviceDialog, setNodeNum from useNewNodeNum.
- Drop the message branch from the router context (no readers).
- RefreshKeysDialog stops keying off `useMessages().activeChat` (which
  was permanently 0 — a dead handle that quietly broke key-refresh
  UX). Use the SDK NodesClient's first error directly via
  `useNodeErrors()[0]`. The dialog manager already opens the dialog on
  PKI_UNKNOWN_PUBKEY, so picking the first error matches the intended
  flow.

* chore(web): rename useChatLegacy → useChatAsLegacyMessages

The "legacy" suffix on its own read like the hook itself was deprecated;
the actual purpose is "use SDK chat history but project it into the
legacy Message shape." Rename for clarity. Companion type names follow
suit (UseChatAsLegacyMessages{Broadcast,Direct,Params}).

* feat(sdk-react,web): migrate read-only channel consumers to SDK ChannelsClient

Phase one of the channels-slice migration (PR #8 in plan). Moves the
non-changeRegistry-coupled consumers off the legacy deviceStore.channels
Map onto the SDK signal-backed ChannelsClient.

- sdk-react useChannels: switch from useClient to useActiveClient and
  fall back to an empty signal when no client is active. Matches the
  no-throw pattern already used by useNodes / useNodeErrors so isolated
  component tests and pre-connect renders don't throw.
- Messages.tsx reads channels via useChannels(); filteredChannels is
  derived with useMemo, currentChannel via .find(). The SDK Channel
  shape (index/role/settings) matches everything this page touches.
- QRDialog reads channels directly via useChannels(); the channels Map
  prop is dropped from QRDialogProps + DialogManager.
- getChannelName loosens its parameter type to the SDK-compatible
  subset { index, settings?: { name? } } so it accepts both proto
  Channel and SDK Channel without conversion.

Channels.tsx, ImportDialog and Settings/index.tsx still read from the
deviceStore — they are coupled to changeRegistry / setChange and will
move with PR #9 (ConfigEditor).

* feat(sdk,sdk-react): scaffold ConfigEditor for the radio/module/channels edit flow

Replaces the (broken) web changeRegistry with a section-grain editor that
lives on the SDK. Per-connection state, signal-backed, exposed via
client.config.editor.

ConfigEditor (domain):
- baseline   = what the device most recently sent. Updated automatically
  from onConfigPacket / onModuleConfigPacket / onChannelPacket.
- working    = UI edits. setRadioSection / setModuleSection / setChannel.
- dirtyRadioSections / dirtyModuleSections / dirtyChannels signals plus
  an aggregate isDirty signal.
- Inbound baseline updates do NOT discard pending working changes — if a
  section is already dirty, the new baseline is recorded but working stays
  put; dirty bookkeeping recomputes against the updated baseline.
- reset() restores working = baseline.
- commit() wraps beginEditSettings → setConfig per dirty radio variant +
  setModuleConfig per dirty module variant + setChannel per dirty channel
  → commitEditSettings, then optimistically promotes working to baseline.
- Disconnect clears both baseline and working so a stale working copy can
  never leak across reconnects.

Domain types:
- RadioConfig and ModuleConfig are now derived directly from the proto
  Config / ModuleConfig payloadVariant union (Extract<{case: V}> shape) so
  new variants stay typed without manual list maintenance. This adds
  deviceUi (radio) and statusmessage (module) automatically.

sdk-react:
- New useConfigEditor() hook returns the editor for the active client, or
  undefined when no client is active. Components subscribe to the editor's
  signals via the existing useSignal helper.

Tests:
- 5 new ConfigEditor tests covering: clean start, dirty tracking, multi-
  section dirty, reset, mid-edit baseline update preservation, and
  disconnect-clears-state. SDK suite 49 passing.

This commit is scaffolding only — no web settings page rewires yet. The
~25 settings pages move to editor.set* / editor.commit() in follow-up
commits, replacing setChange / commitEditSettings call sites and unblocking
deletion of changeRegistry from the device store.

* feat(web): pilot Position / LoRa / MQTT pages on ConfigEditor; Android-aligned layout + labels

First three settings pages migrated off the legacy changeRegistry to the
SDK ConfigEditor. Section structure, field order, and visible strings
are taken from the Meshtastic-Android source of truth so the web and
mobile UIs converge.

Position (radio config):
- Four cards in Android order: Position Packet → Device GPS → Position
  Flags → Advanced Device GPS.
- Card 1 fields: positionBroadcastSecs, positionBroadcastSmartEnabled,
  broadcastSmartMinimumIntervalSecs (renamed "Smart Interval"),
  broadcastSmartMinimumDistance ("Smart Distance").
- Card 2 fields: fixedPosition, lat/lng/altitude (when fixed), gpsMode
  ("GPS Mode (Physical Hardware)"), gpsUpdateInterval ("GPS Polling
  Interval"). gpsMode + gpsUpdateInterval disable when fixedPosition is
  on; lat/lng/altitude disable when it's off.
- Card 3 fields: positionFlags multiselect (description from Android).
- Card 4 fields: rxGpio ("GPS Receive GPIO"), txGpio ("GPS Transmit
  GPIO"), gpsEnGpio ("GPS EN GPIO").
- onSubmit now calls editor.setRadioSection("position", payload). The
  setFixedPosition admin message path is unchanged.

LoRa (radio config):
- Two cards: Options + Advanced (was three: Mesh / Waveform / Radio).
- Options: region, usePreset, modemPreset (when usePreset),
  bandwidth/spreadFactor/codingRate (when !usePreset).
- Advanced: ignoreMqtt, configOkToMqtt, txEnabled, overrideDutyCycle,
  hopLimit (now "Number of Hops", select 0..7), channelNum,
  sx126xRxBoostedGain ("RX Boosted Gain"), overrideFrequency
  ("Frequency Override"), txPower.
- Drop frequencyOffset (Android does not surface it).
- onSubmit calls editor.setRadioSection("lora", payload).

MQTT (module config):
- Two cards: MQTT Config + Map reporting (new card).
- Card 1: enabled ("MQTT enabled"), address, username, password,
  encryptionEnabled, jsonEnabled, tlsEnabled, root ("Root topic"),
  proxyToClientEnabled.
- Card 2: mapReportingEnabled, mapReportSettings.shouldReportLocation
  (consent gate, "I agree."), positionPrecision (12-15 buckets),
  publishIntervalSecs ("Map reporting interval (seconds)").
- positionPrecision + publishIntervalSecs disable until both
  mapReportingEnabled and shouldReportLocation are true.
- onSubmit calls editor.setModuleSection("mqtt", payload).
- Validation schema gains shouldReportLocation; address/username/
  password limits widened to 63 to match proto, root capped at 31.

Settings/index.tsx handleSave:
- After the legacy changeRegistry flow, runs editor.commit() when the
  editor is dirty. Two beginEdit/commitEdit windows are fine — the
  device handles them sequentially. Once the rest of the settings pages
  migrate, the legacy flow goes away and only editor.commit() remains.
- Save button gating includes editor.isDirty so users can save
  ConfigEditor-only changes (e.g. just a LoRa region tweak).

i18n:
- New section labels (config.json position.{positionPacket,deviceGps,
  advancedDeviceGps}; lora.{optionsCard,advancedCard}; moduleConfig.json
  mqtt.{mqttConfigCard,mapReportingCard}).
- Field labels reworded to match Android strings.xml.
- mqtt.mapReportSettings.shouldReportLocation gains label, description,
  consentHeader, consentText (consent text quoted verbatim from
  Android).

* feat(web): migrate Bluetooth/Device/Display/Power/Network/Security pages to ConfigEditor

Phase 3a of PR #9. Six more radio-config pages off changeRegistry onto
the SDK ConfigEditor. Section structure + field order + labels taken
from Meshtastic-Android source of truth.

Bluetooth: single "Bluetooth Config" card. Drops the legacy disable-
mode-when-disabled rule; mode and PIN remain editable while bluetooth
is off (matches Android).

Device: four cards (Options / Hardware / Time Zone / GPIO).
- Options: role, rebroadcastMode, nodeInfoBroadcastSecs.
- Hardware: doubleTapAsButtonPress, disableTripleClick,
  ledHeartbeatDisabled. Web keeps the proto-aligned (un-inverted) field
  names; Android renders them inverted as "Triple Click Ad Hoc Ping" /
  "LED Heartbeat" — equivalent semantics, simpler binding.
- Time Zone: tzdef.
- GPIO: buttonGpio, buzzerGpio.
- Drops debug-only "Device Storage & UI" card (debug-only on Android).
- Drops the inline "Use phone time zone" action button (queued for a
  follow-up; needs a browser-tz implementation).

Display: two cards (Device Display / Advanced).
- Device Display: compassNorthTop ("Always point north"),
  use12hClock, headingBold, units.
- Advanced: screenOnSecs, autoScreenCarouselSecs, wakeOnTapOrMotion,
  flipScreen, displaymode, oled, compassOrientation (new — was missing
  from web).
- Drops gpsFormat (deprecated in proto; moved to DeviceUIConfig).

Power: single "Power Config" card. Order: isPowerSaving,
onBatteryShutdownAfterSecs, adcMultiplierOverride (web keeps the single
number input; Android splits into a switch + conditional float input —
deferred), waitBluetoothSecs, sdsSecs, minWakeSecs,
deviceBatteryInaAddress. Drops lsSecs (Android does not surface it).

Network: three cards (WiFi Options / Ethernet Options / Advanced).
- WiFi Options: wifiEnabled, wifiSsid, wifiPsk.
- Ethernet Options: ethEnabled.
- Advanced: ntpServer, rsyslogServer, enabledProtocols ("Enabled" /
  forward mesh over UDP), addressMode ("IPv4 mode"), then ipv4 ip /
  gateway / subnet / dns when STATIC.
- Drops the read-only "current connections" card (no analog state on
  web today). IPv4 int↔string conversion is unchanged.

Security: four cards (Direct Message Key / Admin Keys / Logs /
Administration).
- Direct Message Key: privateKey + publicKey (read-only) + Generate +
  Backup buttons.
- Admin Keys: three slots, gated on Legacy Admin channel toggle.
- Logs: serialEnabled, debugLogApiEnabled (Android order: serial
  first).
- Administration: isManaged, adminChannelEnabled.
- Byte-array conversions and the Pki regenerate / managed-mode dialogs
  are unchanged.

i18n: config.json gains card-level keys (bluetoothConfig, options,
hardware, timeZone, gpio, deviceDisplay, advanced, powerConfig,
wifiOptions, ethernetOptionsCard, advancedCard, directMessageKey,
adminKeysCard, logsCard, administration, compassOrientation,
useBrowserTimeZone) and updates field labels to Android strings.xml
values where they differ (e.g. "Bluetooth enabled", "Always point
north", "Use 12h clock format", "Shutdown on power loss", "Wait for
Bluetooth duration", "Battery INA_2XX I2C address", "WiFi enabled",
"Ethernet enabled", "Legacy Admin channel", "Serial console").

* feat(web): migrate 11 module-config pages to ConfigEditor; Android-aligned labels

Phase 3b of PR #9. All remaining module pages off changeRegistry onto
the SDK ConfigEditor. Section structure + field order + labels taken
from Meshtastic-Android source of truth.

Pages migrated (single "<X> Config" card unless noted):

Serial: enabled, echo, rxd ("RX"), txd ("TX"), baud, timeout, mode,
overrideConsoleSerialPort. Drops the per-field disable-when-!enabled
gating (Android keeps fields editable while the module is off).

ExternalNotification: four cards (External Notification Config /
Notifications on message receipt / Notifications on alert/bell receipt
/ Advanced). New card layout matches Android. Schema + page now
include useI2sAsBuzzer. Per-field disable-when-!enabled gating dropped.
Card 1: enabled. Card 2: alertMessage*. Card 3: alertBell*. Card 4:
output, active, outputBuzzer, usePwm, outputVibra, outputMs,
nagTimeout, useI2sAsBuzzer.

StoreForward: adds isServer ("Server"). Removes per-field disable-on-
!enabled. Schema gains isServer.

RangeTest: relabel to Android strings ("Range test enabled", "Sender
message interval (seconds)", "Save .CSV in storage (ESP32 only)").
Removes per-field disable-on-!enabled.

Telemetry: adds deviceTelemetryEnabled ("Send Device Telemetry" — gated
on firmware ≥ v2.7.12 capability flag on Android; web shows
unconditionally for now) and powerScreenEnabled ("Power metrics on-
screen enabled"). Schema gains both. Field labels updated.

CannedMessage: relabels per Android ("Canned message enabled", "GPIO
pin for rotary encoder A/B/Press port", "Generate input event on
Press/CW/CCW", "Up/Down/Select input enabled", "Allow input source",
"Send bell"). The free-form `messages` text field is a separate admin
RPC (setCannedMessages on Android) — queued as a follow-up.

Audio: relabel ("CODEC 2 enabled", "PTT pin", "CODEC2 sample rate",
"I2S word select / data in / data out / clock").

NeighborInfo: adds transmitOverLora toggle. Schema gains it.

AmbientLighting: relabel ("Ambient Lighting Config" card). Same fields.

DetectionSensor: relabel + reorder per Android (enabled,
minimumBroadcastSecs, stateBroadcastSecs, sendBell, name, monitorPin,
detectionTriggerType, usePullup).

Paxcounter: relabel ("Paxcounter enabled", "Update interval", "WiFi
RSSI threshold (defaults to -80)", "BLE RSSI threshold").

i18n: moduleConfig.json gains card-level keys (serialConfig,
externalNotificationConfig, notificationsOnMessage, notificationsOnAlert,
advanced, storeForwardConfig, rangeTestConfig, telemetryConfig,
cannedMessageConfig, audioConfig, neighborInfoConfig,
ambientLightingConfig, detectionSensorConfig, paxcounterConfig) and
new field keys (deviceTelemetryEnabled, powerScreenEnabled,
transmitOverLora, isServer, useI2sAsBuzzer, minimumBroadcastSecs,
stateBroadcastSecs, sendBell, name, monitorPin, detectionTriggerType,
usePullup), with field labels reworked to match Android strings.xml
values.

The User module page is the last consumer of changeRegistry. After it
moves, the deviceStore changeRegistry plumbing + getEffectiveConfig +
setChange / removeChange / getAllConfigChanges / etc. can be deleted.

* feat(sdk,web): migrate User + Channel + ImportDialog off changeRegistry; ConfigEditor gains owner support

Phase 3c-1 of PR #9. The last writers/readers of changeRegistry are
moved to the SDK ConfigEditor. (One sweep commit drops the
changeRegistry plumbing from the deviceStore.)

ConfigEditor (sdk/features/config/domain/ConfigEditor.ts):
- New owner state: baselineOwner / workingOwner signals, isOwnerDirty,
  setBaselineOwner(user), setOwner(user). The editor doesn't subscribe
  to a SDK signal for the user (owner arrives via NodeInfo, not its own
  packet), so the web seeds baseline from useMyNodeAsProto via setter.
- commit() now also runs setOwner (admin message) when isOwnerDirty,
  inside the same beginEdit/commitEdit window as radio/module/channels.
- isDirty aggregates owner dirty too. reset() reverts working owner.
- Disconnect clears baseline + working owner.

User page (Settings/User.tsx):
- Aligned to Android: single "User Config" card, fields in order:
  Node ID (read-only), Long Name, Short Name, Hardware model
  (read-only enum name), Unmessageable, Licensed amateur radio (Ham).
- onSubmit calls editor.setOwner instead of connection.setOwner —
  edits queue with the rest of the editor's pending changes and ship
  on the global Save.
- Preserves non-edited User fields (id, hwModel, role, publicKey,
  macaddr) by spreading the baseline before applying form deltas.
- isUnmessageable now reads from the proto's isUnmessagable instead of
  defaulting to false (longstanding bug — the existing value was
  ignored).
- shortName min loosened to 1 (was 2) per Android rule.

Channel page (PageComponents/Channels/Channel.tsx):
- Reads working channel from editor.channels via useSignal projection;
  drops getChange / setChange / removeChange / deepCompareConfig.
- onSubmit -> editor.setChannel(payload).

Channels page (PageComponents/Channels/Channels.tsx):
- Reads channel list from useChannels() (SDK), maps each into a real
  proto Channel via create(ChannelSchema, ...) for the per-tab Channel
  component which still expects the proto shape.
- Per-channel dirty indicator now reads editor.dirtyChannels instead
  of hasChannelChange.

ImportDialog (Dialog/ImportDialog.tsx):
- Apply path -> editor.setChannel + editor.setRadioSection("lora",...)
  instead of setChange. Channel reads via SDK.

i18n: config.json user.* gains userConfig (card label), nodeId,
hardwareModel keys; field labels reworded to match Android (e.g.
"Licensed amateur radio (Ham)", "Unmessageable" with "Unmonitored or
Infrastructure" description). UserValidationSchema gains optional
nodeId / hardwareModel display fields.

* feat(sdk,web): delete changeRegistry; ConfigEditor owns all settings dirty state

Phase 3c-2 of PR #9. With every web settings page already migrated, the
deviceStore changeRegistry plumbing has no remaining writers or readers
and is deleted.

ConfigEditor (sdk):
- New queueAdminMessage(message) for one-off side flows. Queue drains
  inside commit() between beginEdit and commitEdit. Used by
  Position.tsx for setFixedPosition; future side flows (e.g. SetTime)
  reuse the same queue.
- Disconnect / commit success now also reset the admin-message queue.
- isDirty includes a queued admin-message check.

Web Settings/index.tsx:
- handleSave is now a one-liner: editor.commit(). All the legacy
  get*Changes / get*ChangeCount / clearAllChanges / connection.setConfig
  loops + the post-commit deviceStore mirror writes are gone.
- handleReset calls editor.reset() instead of clearAllChanges().
- Save-button gating reads editor.isDirty + RHF dirty.
- Section change-count badges read directly from editor.dirtyRadioSections /
  editor.dirtyModuleSections / editor.dirtyChannels lengths.

Tab dirty-dot indicators (RadioConfig.tsx / DeviceConfig.tsx /
ModuleConfig.tsx): rewired from hasConfigChange/hasModuleConfigChange/
hasChannelChange/hasUserChange to editor signals (dirtyRadioSections,
dirtyModuleSections, dirtyChannels, isOwnerDirty).

Position.tsx: queueAdminMessage call now goes through editor — pending
fixed-position coordinates ride along with the rest of the editor's
dirty state and ship under the same beginEdit/commitEdit window.

deviceStore.ts:
- Drops the entire changeRegistry surface from the Device interface and
  factory: setChange / removeChange / hasChange / getChange /
  clearAllChanges / hasConfigChange / hasModuleConfigChange /
  hasChannelChange / hasUserChange / getConfigChangeCount /
  getModuleConfigChangeCount / getChannelChangeCount /
  getAdminMessageChangeCount / getAllConfigChanges /
  getAllModuleConfigChanges / getAllChannelChanges / queueAdminMessage /
  getAllQueuedAdminMessages, plus the changeRegistry field.
- getEffectiveConfig / getEffectiveModuleConfig collapse to plain
  device.config[variant] / device.moduleConfig[variant] passthroughs
  (kept as a thin compatibility shim for residual callers; the
  changeRegistry merge is gone).
- types.ts: ValidConfigType / ValidModuleConfigType derive directly
  from LocalConfig / LocalModuleConfig keys (was imported from the
  deleted changeRegistry.ts).
- The 252-line changeRegistry.ts file is deleted; ~250 lines also drop
  out of the deviceStore factory.
- deviceStore.test.ts loses the change-registry describe block (3
  tests). 237 web tests still passing (was 240; -3 dead tests).

Net: -1066 / +136 lines.

* feat(sdk,sdk-storage-sqlocal,web): TelemetryRepository port + SqlocalTelemetryRepository (PR #10)

Telemetry slice gains the same persistence shape as chat / nodes: a
repository port on the SDK side, an in-memory default, an OPFS-backed
SQLite adapter on the storage package side, and lazy hydration into the
in-memory store.

SDK (@meshtastic/sdk):
- New TelemetryRepository port (loadRecent, loadBefore, append,
  appendBatch, prune, clearNode, clear) + TelemetryRetentionPolicy
  (maxPerNode, olderThanMs).
- New InMemoryTelemetryRepository — default when no adapter is wired.
- TelemetryClient grows TelemetryClientOptions { repository?, retention? }.
  Each incoming onTelemetryPacket appends to both the in-memory store
  and the repository, then the configured retention policy prunes the
  repository.
- latest(nodeNum) and history(nodeNum) lazy-hydrate the in-memory store
  from the repository on first subscribe (HYDRATE_LIMIT = 256). loadBefore
  passes through to the repository for paged reads.
- clearNode / clear methods exposed on the client.
- MeshClient gains options.telemetry which is passed through to
  TelemetryClient.

@meshtastic/sdk-storage-sqlocal:
- New SqlocalTelemetryRepository under ./telemetry subpath. Drizzle-typed
  insert/select/delete against the existing telemetry table; payload is
  stored as base64 of the proto bytes (per-kind schema lookup) so the
  wire shape is the source of truth across schema additions.
- prune({ maxPerNode }) trims with a per-node offset query. prune({
  olderThanMs }) deletes by ts cutoff.
- Six new tests cover round-trip, ascending order, deviceId scoping,
  per-node retention, age-based prune, and proto payload preservation.
- Re-exports added to mod.ts + ./telemetry subpath in package.json.

web:
- useConnections wires SqlocalTelemetryRepository per connection with
  retention { maxPerNode: 500, olderThanMs: 30 days }.

Tests: SDK 57 (was 49 — +8 new), storage 30 (was 24 — +6), web 237.
Build clean.

* feat(sdk,sdk-react,web): unread counts on the SDK ChatClient

ChatClient gains a `chat.unread` namespace mirroring `chat.drafts`:
- byKey: ReadonlySignal<Map<conversation-key-string, number>>
- total: ReadonlySignal<number>
- count(key): ReadonlySignal<number>
- markRead(key): void

Increments happen in the existing onMessagePacket subscriber when
packet.from !== client.myNodeNum (so the outbound echo of our own send
doesn't bump anything). Uses the same ConversationKey shape the rest
of the chat slice already keys by, so direct messages keyed by peer
and broadcasts by channel can never collide.

Counts are in-memory only — persistence will come later if needed
(would require tracking a lastReadAt timestamp per conversation in the
message repository and computing unread on hydrate).

sdk-react: new useTotalUnread / useUnreadCount(key) / useUnreadByKey
hooks. All fall back to safe empty values when no client is active.

Web migration:
- Sidebar reads useTotalUnread instead of summing
  deviceStore.unreadCounts.
- MessagesPage: per-channel SidebarButton counts read from
  useUnreadByKey()'s `channel:N` keys; per-direct-message counts from
  `direct:N` keys. Click handlers call meshClient.chat.unread.markRead
  with the typed ConversationKey instead of resetUnread.
- subscriptions.ts: drops onMessagePacket -> incrementUnread mirror
  (SDK now owns it). myNodeNum local goes away too — nothing else
  consumed it.
- deviceStore: removes unreadCounts field + incrementUnread /
  resetUnread / getUnreadCount / getAllUnreadCount methods. The mock
  + test block in deviceStore.test.ts also drop their unread coverage.
- deviceStore.mock.ts: also strips the dead changeRegistry / setChange
  / hasConfigChange / etc. methods that survived from the earlier
  changeRegistry deletion.

Tests: SDK 61 -> 65 (+4 ChatClient.unread.test), sdk-react 8, web 236.
Build clean.

* refactor(web): split useConnections into focused modules

useConnections went from 661 lines down to 264 by extracting three
single-responsibility helpers under packages/web/src/core/connections/.
The hook is now pure orchestration; transport / heartbeat / SDK-client
/ status-probe concerns live in their own files.

New modules:
- core/connections/heartbeat.ts (45 LOC): startConfigHeartbeat (5s),
  startMaintenanceHeartbeat (5min), stopHeartbeat. Owns the heartbeats
  Map; replaces the inline interval bookkeeping. Both helpers stop the
  prior heartbeat first so callers don't have to.
- core/connections/sdkClient.ts (61 LOC): buildMeshDevice(connId,
  deviceId, transport) opens the OPFS DB, builds the four sqlocal
  repositories (chat / draft / nodes / telemetry), and constructs the
  MeshDevice with the canonical retention defaults (chat 90d / 1k per
  bucket; telemetry 30d / 500 per node). Falls back to in-memory when
  sqlocal is unavailable.
- core/connections/transports.ts (236 LOC): per-transport openTransport
  factory (HTTP reachability check, BT permission re-acquisition with
  optional prompt, Serial port lookup with close-then-reopen),
  probeConnection for refreshStatuses, closeTransport for cleanup.
  Discriminates over conn.type so useConnections doesn't carry the
  switch logic.

useConnections (now 264 LOC):
- Owns the cachedTransports + configSubscriptions maps and the
  Zustand selectors.
- teardown(id, conn) consolidates the heartbeat + config-sub +
  meshDevice.disconnect + transport-close cleanup that used to be
  duplicated across removeConnection / disconnect.
- connect calls openTransport and forwards the resulting transport +
  cached BT/Serial handle into setupMeshDevice. The BT
  gattserverdisconnected listener is wired here (it needs the connId).
- refreshStatuses simplifies to a filter + Promise.all over
  probeConnection.
- syncConnectionStatuses unchanged.

Behavior is unchanged. No new tests — the existing web suite (236)
still passes; build clean.

* chore: move packages/web → apps/web

Web is a deployable SPA, not a library — no @meshtastic scope, no
exports map, no npm/JSR publish target, no other workspace member
depends on it. Conventional pnpm/Turbo/Nx layout puts deployables
under apps/ and libraries under packages/. Doing the move now (after
PR #9 / #10 / unread / useConnections refactor land but before Phase
C ships) so the lib-only packages/* directory remains stable as we
delete packages/core.

Mechanics:
- pnpm-workspace.yaml: add `apps/*` to packages.
- git mv packages/web apps/web (entire directory tree).
- vite.config.ts uses process.cwd(), so no internal path edits needed.
- pnpm filter commands still resolve by package name (`pnpm --filter
  meshtastic-web run build`) — no script changes.

External-path consumers updated:
- README.md table row.
- tsconfig.json reference.
- 7 GH workflows (pr.yml, nightly.yml, release-web.yml, the three
  crowdin-*.yml, release-packages.yml). The
  packages/release-packages.yml `packages/* | grep -v packages/web`
  filter is now redundant since web isn't in packages/* anymore — it
  collapses to plain `ls -d packages/*`.

Verified: web build clean, web 236 / sdk 65 / sdk-react 8 / storage
30 tests all pass.

* feat: PR #12 Phase C — delete packages/core, retarget transports to @meshtastic/sdk, bump majors

The legacy `@meshtastic/core` package is gone. The six transport-*
packages and the web app no longer depend on it; everything routes
through `@meshtastic/sdk`.

Transport packages (transport-deno, transport-http, transport-node,
transport-node-serial, transport-web-bluetooth, transport-web-serial):
- package.json deps swap `@meshtastic/core: workspace:*` for
  `@meshtastic/sdk: workspace:*`.
- src/transport.ts + src/transport.test.ts imports point at
  `@meshtastic/sdk` (the `Types` and `Utils` namespaces are still
  exported from the SDK so source code is otherwise unchanged).
- README.md examples updated to import from `@meshtastic/sdk`.

apps/web:
- Drops the leftover `@meshtastic/core` workspace dep; nothing in
  apps/web/src imports from it.

@meshtastic/sdk:
- README description loses the "Replaces @meshtastic/core" suffix —
  there's nothing left to replace.
- Three legacy shim files keep their re-exports but their docstrings
  drop the "Phase-A shim, removed in Phase C" framing. The MeshDevice
  facade survives because the web app's `connection.factoryResetDevice()`
  / `connection.reboot()` / etc. callsites still go through it; new
  consumers should reach into `client.config` / `client.chat` / etc.
- New scripts/rename-dts.mjs is a postbuild step that renames tsdown's
  hashed entry-point dts outputs (`mod-<hash>.d.ts` etc.) back to their
  canonical names so package.json `types` and downstream dts-bundlers
  can find them. Internal chunk dts files (e.g. `Transport-<hash>.d.ts`)
  are intentionally NOT renamed because mod.d.ts imports them by path.
- build:npm runs tsdown then the rename script.

Version bumps (signal: now require @meshtastic/sdk):
- @meshtastic/sdk             0.1.0 -> 1.0.0
- @meshtastic/sdk-react       0.1.0 -> 1.0.0
- @meshtastic/sdk-storage-sqlocal 0.1.0 -> 1.0.0
- @meshtastic/transport-http       0.2.5 -> 1.0.0
- @meshtastic/transport-web-serial 0.2.5 -> 1.0.0
- @meshtastic/transport-web-bluetooth 0.1.5 -> 1.0.0
- @meshtastic/transport-deno       0.1.1 -> 1.0.0
- @meshtastic/transport-node       0.0.2 -> 1.0.0
- @meshtastic/transport-node-serial 0.0.2 -> 1.0.0

Workflows: nothing referenced packages/core directly (only the
release-packages.yml glob which already collapsed in the apps/web
move). README packages table loses the legacy `packages/core` row.

Verified: web build clean, all four package suites green
(web 236, sdk 65, sdk-react 8, storage 30).

The transport packages' dist build is currently blocked by a tsdown
cross-chunk dts resolution glitch where the `Types` namespace import
can't follow `mod.d.ts`'s reference to the internal `Transport-<hash>`
chunk. Runtime is fine — only the published-types path is affected,
and transport packages publish via their own release flow. Logged as
follow-up.

* fix(web/connections): probe = "online" not "configured"; flip status to "configuring" before DB open; await transport disconnect

Three reconnect-flow bugs:

1. probeConnection returned "configured" for serial / bluetooth when
   the browser had stored permission for the device — but permission
   ≠ a configured Meshtastic device. The card showed "connected"
   and a Disconnect button before the user had ever clicked Connect.
   Probe now returns "online" (= "available, click to connect"),
   matching the HTTP path. "configured" is reserved for the
   onConfigComplete callback.

2. setupMeshDevice flipped status from "connecting" → "configuring"
   AFTER awaiting buildMeshDevice, which opens the OPFS DB. If the
   DB open stalled (multi-tab contention, slow first-time init), the
   card sat at "connecting" indefinitely. Move the status flip ahead
   of the persistence await — UI shows "configuring" while
   persistence is spinning up.

3. teardown's `device?.connection?.disconnect()` returned a Promise
   that was never awaited, so the underlying transport's port.close()
   could race the next port.open() on a fast disconnect → reconnect.
   Make teardown async, await disconnect, propagate via async
   removeConnection / disconnect callers.

Plus: connect() catch block logs the underlying error before turning
it into a status update, so the actual failure shows up in console
even when the toast text is generic.

* feat(web): Position "Use browser location" button + Telemetry firmware capability gate

Two backlog UX nits.

DynamicForm:
- FormGroup gains an optional `footer?: ReactNode` slot that renders
  after the field list. Lets pages drop arbitrary JSX (action buttons,
  notes, etc.) into a card without subclassing the form.

Position:
- New `UseBrowserLocationButton` component lives inside the Device GPS
  card via the new `footer` slot. Calls navigator.geolocation, writes
  lat/lng/altitude into the form via `useFormContext` (the
  PositionValidation form is wrapped in FormProvider by DynamicForm).
- Truncates lat/lng to 7 decimals to match the proto's max precision.
- Gracefully no-ops when navigator.geolocation is unavailable
  (insecure context).
- Failed reads surface as a toast carrying the GeolocationPositionError
  message; busy state disables the button + flips the label.
- New i18n keys: position.useBrowserLocation.{label,busy,failed}.

Telemetry:
- `device_telemetry_enabled` is only writable on firmware ≥ v2.7.12
  (mirrors Android's `Capabilities.canToggleTelemetryEnabled`). Adds a
  small `firmwareAtLeast` semver helper and reads
  `device.metadata.get(0)?.firmwareVersion`. The toggle is hidden on
  older firmware so we don't push a value the device will silently
  drop.
- Unparseable / unknown firmware versions default to "show the toggle"
  (rather than hide), so we don't accidentally hide the control on
  devices we can't classify.

Build clean, 236 web tests still pass.

* fix(sdk): build clean dts for npm consumers; transports drop Types/Utils namespace

Previously transport-* package dts builds failed with "Missing export" because
rolldown's dts bundler couldn't follow tsdown's cross-chunk re-exports out of
@meshtastic/sdk. Three things land here:

1. mod.ts now re-exports `fromDeviceStream`, `toDeviceStream`, `Queue`, and
   `Xmodem` directly. Transport packages were importing these via the legacy
   `Utils` namespace; namespace re-exports are exactly what rolldown chokes
   on. Transport packages (http, deno, node, node-serial, web-bluetooth,
   web-serial) and shared transportContract.ts now use direct imports —
   `import { Transport, DeviceOutput, ... } from "@meshtastic/sdk"`.

2. package.json `exports` split: `types` points at `./dist/<entry>.d.ts`
   (built dts) so tsdown's downstream rolldown reads a self-contained file;
   `default` keeps source paths so vitest + workspace-internal imports still
   resolve to .ts source.

3. Postbuild `rename-dts.mjs` now (a) inlines internal chunk dts files
   (Transport-<hash>.d.ts) into each entry's dts, rewriting the letter
   aliases tsdown produces; (b) strips `type` modifiers from re-exports
   so rolldown accepts the bindings as both value- and type-shape;
   (c) declares the synthetic `Types`/`Utils` namespaces explicitly,
   replacing the broken `<wrapper>_d_exports as Types` aliases tsdown
   emits for `export * as` patterns.

vitest.config.ts gains `apps/*` so the workspace move keeps test discovery
working for the apps/web project.

* chore(build): tighten tsdown perf flags across SDK + transport packages

- Drop bogus `dts.isolatedDeclarations` field from SDK (not a real tsdown
  option; tsdown was silently ignoring it).
- Make every package explicit about the perf-relevant flags rather than
  relying on defaults that drift between tsdown versions: target=esnext
  (no syntax downleveling), sourcemap=false, minify=false, treeshake=true,
  report=false, splitting=false.
- Modest wall-clock wins: SDK 1020→752ms, transports ~720→~600ms.

`isolatedDeclarations: true` in tsconfig would unlock the bigger oxc-dts
fast path but the codebase isn't ID-clean yet — left as future work.

* fix(web): clear pre-existing typecheck errors (36 → 0)

Sweep covering several unrelated cohorts:

- Delete dead `NewDeviceDialog.tsx` (commented-out in App.tsx, imports point at
  non-existent `@components/PageComponents/Connect/*`).
- Add `better-result` to sdk-react deps so `useChat`/`useDirectChat`/
  `useFavoriteNode`/`useIgnoreNode` resolve.
- Fix `test-utils.tsx`: route at `routeTree.gen.ts` was never generated;
  re-export the existing `routeTree` constant from `routes.tsx` and pass
  the missing router context + DeviceWrapper deviceId.
- Pre-existing `noUncheckedIndexedAccess` violations in `pskSchema.test.ts`,
  `x25519.ts`, `Table/index.tsx` + test, `useCopyToClipboard` (Timeout vs
  number) — non-null asserts where the index is guaranteed by the
  surrounding code, plus a defensive `if (!cell) return 0` in the table sort.
- Immer `WritableDraft<T>` mismatches against SDK's `MeshDevice`/`Device`
  classes — cast through `Draft<X>` where the inferred recursive draft type
  can't represent SDK class internals.
- `deviceStore.mock` updated for the `connectionPhase`/`connectionId` +
  setters added when the connection lifecycle was extracted.
- `HeatmapLayer` accepts the `isVisible` prop everyone else's layer accepts.
- `SNRTooltipProps.to` widened to `string | undefined` (single-node hover
  has no `to`).
- Zod resolver returns `Record<string, never>` for the error-path values
  shape that react-hook-form expects.
- Mock `NodeInfo` in `useFilterNode.test.ts` gains the `isMuted` proto
  field that landed upstream.

* fix(web/connections): retry-once + clearer error on Bluetooth GATT connect failure

`NetworkError: Connection attempt failed` from `device.gatt.connect()` is the
most common transient when reconnecting BT — OS stack hiccup, device just
woke from sleep, etc. Adding one retry with a 750ms delay clears most of
those. Persistent failures get a wrapped error message naming the actual
likely causes (out of range, powered off, paired with phone or another
tab) instead of leaving the raw DOMException for the user to interpret.

* refactor(transport-web-bluetooth): own GATT connect-retry semantics + typed error

Per the DDD layering — transport-level concerns belong in the transport
package, not the web app's connection orchestrator. Moved the GATT
`NetworkError: Connection attempt failed` retry-once + the user-facing
error wrapping out of `apps/web/src/core/connections/transports.ts` and
into `TransportWebBluetooth.prepareConnection`.

New `BluetoothConnectError` carries:
- `kind: "transient" | "unavailable" | "missing-service"` so callers can
  decide whether to suggest retry vs re-pair vs firmware upgrade.
- `userMessage` — human-readable, actionable string ready for UI.

The web app's `transports.ts` is back to a thin wrapper that just calls
`TransportWebBluetooth.createFromDevice` and surfaces whatever error it
throws. `BluetoothConnectError` is re-exported through the connections
module so the Connections page can `instanceof`-check without depending
on the transport package directly.

* feat(sdk,web): detect newly-flashed device + prompt region setup

Mirrors Meshtastic-Android's `regionUnset` flow. A freshly-flashed device
boots with `Config.LoRa.region == UNSET` and won't transmit at all until
the user picks one. Web now surfaces this:

- `ConfigClient.isRegionUnset: ReadonlySignal<boolean>` — computed from
  the radio config signal, false until the first LoRa packet arrives so
  consumers don't flash the prompt during the connect handshake.
- `useIsRegionUnset()` hook in sdk-react, re-exported from the package's
  public surface.
- `RegionSetupReminder` mounts inside the connected-device branch of
  App.tsx. While the SDK reports `isRegionUnset == true`, a persistent
  toast offers a "Set region" CTA that deep-links into the LoRa tab
  (`/settings/radio`). Toast auto-dismisses the moment a real region is
  committed.

Predicate matches Android exactly (single check, no owner/name/setupComplete
heuristics). Lives in the SDK config slice — UI is a thin consumer.

3 new SDK tests; SDK 64 / sdk-react 8 / web 236.

* refactor(transport-web-serial): own port-state hygiene + Result-typed connect errors

Pre-flight close + open-with-backoff lived in apps/web's transport
orchestrator — wrong layer per DDD. Lifted into TransportWebSerial
itself.

Changes:
- `TransportWebSerial.createFromPort` (and `create`) now return
  `Result<TransportWebSerial, SerialConnectError>`. No throwing on
  expected failures; callers branch on the Result.
- New `preparePort` private static that:
  * force-closes the port if `readable` / `writable` are non-null
  * opens with up to 4 attempts (250 / 500 / 750 ms backoff) on
    `InvalidStateError` — common during USB re-enumeration
  * tags persistent failures `kind: "in-use"` (other tab / app
    holding the port) vs `"busy"` (transient / unknown) vs
    `"unavailable"` (no streams after open)
- `SerialConnectError` carries `kind` + `userMessage` ready for UI.
- `apps/web/src/core/connections/transports.ts` drops its old
  conditional `port.close()` + 100ms sleep; just calls
  `createFromPort` and unwraps the Result. `SerialConnectError` is
  re-exported alongside `BluetoothConnectError` so the Connections
  page can pattern-match.
- `AnyTransport` definition simplified — was deriving via
  `Awaited<ReturnType<...>>` which broke once `createFromPort`
  returned a Result.
- Test FakeSerialPort updated to mirror the real spec: `readable`
  /`writable` go null on `close()` and re-create on `open()`.
- 3 new port-hygiene tests cover the close-on-prior-open path,
  the backoff-retry success path, and the persistent-`in-use`
  Err path. Suite: 5 → 8.

Matches the better-result preference for new application/use-case
code. BT transport stays on the throwing `BluetoothConnectError`
shape for now — separate refactor if we want to converge.

* chore(logging): tslog-gated debug logs across the serial connect path

createLogger now reads `localStorage["mesh-debug"]==="1"` (browser) or
`MESH_DEBUG=1` (node) on each invocation. When set, default minLevel
drops to debug; otherwise stays at info. Existing callers
(MeshClient + co.) are unaffected.

Logs added (all `[name]`-prefixed via tslog) covering the connect
lifecycle the user just hit:

- TransportWebSerial.preparePort: enter, close-needed branch,
  close result, each open() attempt, retry decisions, final error.
- TransportWebSerial constructor: pipe wiring, toDevice pipe abort
  vs reject path.
- TransportWebSerial read loop: start, done, throw (with
  closingByUser flag), reader-lock release.
- TransportWebSerial.disconnect: each cleanup step (abort, pipe
  settled, fromDevice cancel, connection.close).
- transports.ts openSerial: cached-port flag, getPorts count,
  picker invocation, resolved-port stream state, createFromPort
  Result outcome (kind + userMessage on Err).
- useConnections.connect / setupMeshDevice / teardown: phase
  transitions, configure() resolve / reject, onConfigComplete fire,
  BT gattserverdisconnected, transport.disconnect rejection.

Flip on:
  localStorage.setItem("mesh-debug", "1"); location.reload();

* chore(web/storage): logs + 5s timeout around sqlocal DB open

The connect path silently hung at `buildMeshDevice` when sqlocal failed
to open. Adding visibility:

- `getStorageDb` logs creation start, success (with elapsed ms), and
  failure (with name + message).
- `buildMeshDevice` races the DB open against a 5s timeout. If sqlocal
  hangs (stale Web Lock from a crashed prior tab, OPFS contention,
  worker hang), the connect path falls through to the SDK's in-memory
  repositories instead of blocking forever — the user gets a working
  session and the warn-level log surfaces the underlying cause.
- `buildMeshDevice` logs entry, DB-ready elapsed, repos-opened, and
  fall-through decisions.

* feat(sdk,web): live connect-progress overlay (terminal-style log)

Surfaces what the connection handshake is doing in real time. Per DDD,
the predicate + counters live in the SDK; the web overlay is a thin
consumer of the signal.

SDK
- New `MeshClient.progress: ReadonlySignal<ConnectionProgress>` with the
  state machine `idle → configuring → configured`. Counters
  (config / modules / channels / nodes + boolean myInfo / metadata)
  tally inbound packets each `configure()` cycle.
- `configure()` resets to `configuring` with empty counters.
  `onConfigComplete` flips to `configured`.
- `ConnectionProgress` + `ConnectionProgressCounters` exported from the
  package surface.
- 6 new tests in `MeshClient.progress.test.ts`.

sdk-react
- `useConnectionProgress()` hook reads the active client's signal,
  returns `{ phase: "idle" }` when there is no active client so the
  caller can render unconditionally.

apps/web
- `ConnectingOverlay` redesigned as a terminal-style streaming log:
  - macOS-window-style header (red/yellow/green dots) with a live
    `phase` indicator pulse.
  - Monospace event lines with `→` (active) / `✓` (done) / `•` (info)
    glyphs and a relative-seconds timestamp column.
  - Auto-scrolls to the latest entry; blinking caret on the trailing
    active line.
  - Lines derive from `device.connectionPhase` transitions and per-
    counter bumps on `MeshClient.progress`. Resets on each fresh
    connect cycle.
- Mounted at the top of the device tree (outside the device-conditional
  branch) so it shows during a first-time connect from the Connections
  screen as well as reconnects from inside the app.
- i18n strings under `connections.overlay.log.*`.

* refactor(web): redesign ConnectingOverlay as hero card + fix early visibility

Two changes:

Visibility fix — overlay now reads `savedConnections` for any entry
whose status is "connecting" or "configuring". The previous code keyed
off `device.connectionPhase` from the active deviceStore entry, but
that entry doesn't exist until partway through `setupMeshDevice` —
the overlay was hidden during transport-open + storage-open (often
the slowest part of the connect flow).

Visual redo (option C — hero card with radial pings):
- Center: transport-type icon (Globe / Bluetooth / Cable) on a
  gradient disc with two concentric ping rings.
- Below: device name + phase label with small spinner.
- 2x2 grid of stat chips (Identity / Metadata / Channels / Nodes)
  that flip from gray (dashed circle) to emerald (check or count)
  as the SDK reports each piece arriving.
- Slate-to-black gradient panel; non-dismissable while active.
- i18n strings under `connections.overlay.*` updated to match.

* fix(web/connecting-overlay): clear stale in-flight statuses + Cancel escape

Two reasons the overlay could "never disappear":

1. Persisted state from a prior session.
   `savedConnections` is Zustand-persisted, so a prior tab that died
   mid-connect (page reload, hot reload, force-quit) leaves a saved
   connection at status "connecting" / "configuring" forever. On cold
   boot the overlay reads that and stays visible. `onRehydrateStorage`
   now sweeps any persisted "connecting" / "configuring" /
   "disconnecting" entries back to "disconnected" — no live JS code
   could complete those, so they're stale by definition.

2. Live attempt that genuinely hangs (firmware in CLI / bootloader,
   framing out of sync, `onConfigComplete` never arrives).
   After STUCK_THRESHOLD_MS (15s) the overlay surfaces a Cancel button
   + a hint. Cancel calls `useConnections().disconnect(id)` which tears
   down the transport and flips status off "configuring". Resets if a
   new attempt starts.

i18n adds `connections.overlay.stuckHint` + `cancel`.

* fix(web/connections): close configured-transition race when configCompleteId is buffered

Reproed on serial reconnect: the device kept emitting from a prior
session, so the new MeshClient's `transport.fromDevice → decodePacket`
pump processed the buffered `configCompleteId` synchronously inside
the `buildMeshDevice` await — before `setupMeshDevice` had a chance to
subscribe to `onConfigComplete`. SimpleEventDispatcher doesn't replay
to late subscribers, so the event was lost. The connect overlay (which
keys off the saved-connection status) stayed visible forever even
though the rest of the app saw nodes / messages flowing.

Fix: wire two parallel paths to a shared idempotent `markConfigured`
handler:

- `events.onConfigComplete` (fast path, fires on the next live event).
- `MeshClient.device.status` signal — `decodePacket` also flips the
  signal to `DeviceConfigured` on the same packet, and signal
  subscribers don't drop the current value if it's already there.

Plus an initial synchronous check in case the status signal had
already settled before either subscribe ran. `configSubscriptions`
unsubscribes both on teardown.

* style(connecting-overlay): drop hardcoded slate/sky for the app's theme tokens

Reuses the same `--color-text-primary`, `--color-text-secondary`,
`--color-background-primary`, and `--color-link` tokens the rest of
the web UI already binds to (light + dark variants resolve via
`[data-theme=...]`), so the overlay now picks up the active theme
instead of fighting it with a hardcoded slate/sky/indigo palette.

- Hero ring + disc → `bg-link` + `bg-link/{20,30}` ping ripples.
  Icon uses `text-background-primary` so it stays legible on both
  themes (white-on-blue light, dark-on-blue dark).
- Title / phase / hint copy → `text-text-primary` / `text-text-secondary`.
- Stat chips use `green-500` (matches `Button.success`) for the done
  state and `text-secondary`-derived neutrals for idle.
- Cancel button reverts to the default `Button` outline variant — was
  carrying its own slate overrides, no need.

* fix(sdk/chat): optimistic-append outbound text so it shows up after send

Reproed in MessagesPage on /messages/broadcast/0: typing a message and
pressing Enter cleared the input, but the message never rendered.

Root cause:
- `ChatClient.send` calls `sendText` → `MeshClient.sendPacket(...,
  echoResponse=true)`. The echo branch dispatches `onMeshPacket` only.
- `ChatClient` subscribes to the per-portnum `onMessagePacket`, not the
  raw `onMeshPacket`. So the outbound message is never appended to its
  conversation bucket.
- The Meshtastic firmware does not loop the user's own outbound text
  back via `fromradio`, so there's no inbound echo to fall back on.

Fix:
- `ChatClient.send` now optimistically appends the outbound message
  (state=Pending) to the matching channel/direct bucket and persists
  it via the configured repository as soon as `sendText` resolves Ok.
- The existing `onRoutingPacket` subscriber flips state Pending→Ack /
  Failed when the routing ack arrives keyed by packet id — unchanged.
- `ChatStore.hasMessage(key, id)` added; the inbound `onMessagePacket`
  subscriber and the `send()` path both consult it so a
  belt-and-suspenders firmware echo doesn't double-append.

Tests: ChatClient.send.test.ts — 4 cases (broadcast append, direct
append, echo dedup, routing-ack flips state). Suite 70 → 74 / web
suite untouched at 236.

* fix(sdk/chat): append outbound message before awaiting send (instant render)

Previously the optimistic append happened after `await sendText(...)`,
which itself awaited `queue.wait(id)` — i.e. the firmware ack. On LoRa
that's 1–3 seconds, so the user saw a noticeable delay between hitting
Enter and the bubble appearing.

Move the append before the await. To do that the chat slice needs to
know the packet id synchronously, so:

- `MeshClient.sendPacket` gains an optional `packetId` parameter
  (defaults to `generatePacketId()`, behaviour unchanged for callers
  that don't pass one).
- `SendTextInput.packetId` plumbs through `SendTextUseCase` to
  `sendPacket`.
- `ChatClient.send` generates the id up-front, appends the message
  with `state=Pending` immediately, persists it, then awaits
  `sendText(..., { packetId })`. On Err the optimistic message stays
  visible but flips to `Failed` so the user sees what happened.
  Routing-ack subscriber still flips `Pending → Ack` keyed by id —
  unchanged.

Tests added (suite 74 → 76):
- "appends the optimistic message before the send promise resolves"
  — asserts the bucket contains the message synchronously after the
  send call returns its pending promise.
- "flips outbound state to Failed when sendText returns Err"
  — exercises the empty-text validation path.

* adding a claude to repo

* handle device reboots

* chore(web): post-rebase fixups — lockfile, dedupe dep, formatting

- Regenerate pnpm-lock.yaml to match the merged package.json set (adds the
  @meshtastic/sdk + transport workspace packages from this PR); the rebase
  had held the lockfile at main's version via a merge driver.
- Drop a duplicate better-result entry in apps/web/package.json.
- Reformat LoRa.tsx / Display.tsx (oxfmt) after merging main's config fields
  into Dan's ConfigEditor field groups.

* test: retire main's nodeDBStore + messageStore tests superseded by SDK migration

Dan's SDK migration removed the Zustand nodeDBStore (node state now lives in
the SDK; useNodesLegacy notes the migration) and the useNodeDB hook. main had
since added nodeDBStore.test.tsx / messageStore.test.ts and kept evolving the
store; the rebase carried those over, so they tested an API this PR removes
(useNodeDB is not a function). Dan's branch contains none of these files.

Remove the dead nodeDBStore store dir and the two orphaned main tests to match
the migrated architecture. The live messageStore (barrel-exported) is kept; only
main's standalone test for it is dropped.

---------

Co-authored-by: Ben Meadors <benmmeadors@gmail.com>
This commit is contained in:
Dan Ditomaso
2026-06-15 16:55:49 -05:00
committed by GitHub
co-authored by Ben Meadors
parent ccc02ad438
commit dc9749c042
386 changed files with 13841 additions and 7155 deletions
@@ -0,0 +1,45 @@
import type { ConnectionId } from "@core/stores/deviceStore/types";
import type { MeshDevice } from "@meshtastic/sdk";
const HEARTBEAT_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes (post-config)
const CONFIG_HEARTBEAT_INTERVAL_MS = 5_000; // 5s (during initial config)
const heartbeats = new Map<ConnectionId, ReturnType<typeof setInterval>>();
/**
* Stops + clears any active heartbeat for the connection. Safe to call when
* no heartbeat is running.
*/
export function stopHeartbeat(id: ConnectionId): void {
const h = heartbeats.get(id);
if (!h) return;
clearInterval(h);
heartbeats.delete(id);
}
/**
* Fast-cadence heartbeat used while the device is in `configuring`. Replaced
* by the maintenance heartbeat once the device fires onConfigComplete.
*/
export function startConfigHeartbeat(id: ConnectionId, meshDevice: MeshDevice): void {
stopHeartbeat(id);
const intervalId = setInterval(() => {
meshDevice.heartbeat().catch((error) => {
console.warn("[heartbeat] config heartbeat failed:", error);
});
}, CONFIG_HEARTBEAT_INTERVAL_MS);
heartbeats.set(id, intervalId);
}
/**
* Slow-cadence keep-alive used after configuration completes.
*/
export function startMaintenanceHeartbeat(id: ConnectionId, meshDevice: MeshDevice): void {
stopHeartbeat(id);
const intervalId = setInterval(() => {
meshDevice.heartbeat().catch((error) => {
console.warn("[heartbeat] maintenance heartbeat failed:", error);
});
}, HEARTBEAT_INTERVAL_MS);
heartbeats.set(id, intervalId);
}
@@ -0,0 +1,82 @@
import { coordinator, getStorageDb } from "@core/sdkStorage.ts";
import type { ConnectionId } from "@core/stores/deviceStore/types";
import { createLogger, MeshDevice } 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 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 } as const;
const TELEMETRY_RETENTION = { maxPerNode: 500, olderThanMs: 1000 * 60 * 60 * 24 * 30 } as const;
const STORAGE_OPEN_TIMEOUT_MS = 5000;
/**
* Builds a MeshDevice wired with persistence repositories opened against the
* shared OPFS-backed SQLite DB. 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.
*/
export async function buildMeshDevice(
connectionId: ConnectionId,
deviceId: number,
transport: AnyTransport,
): Promise<MeshDevice> {
log.debug("buildMeshDevice: enter", { connectionId, deviceId });
let chatRepository: SqlocalMessageRepository | undefined;
let draftRepository: SqlocalDraftRepository | undefined;
let nodesRepository: SqlocalNodesRepository | undefined;
let telemetryRepository: SqlocalTelemetryRepository | undefined;
try {
const t0 = Date.now();
const db = await Promise.race([
getStorageDb(),
new Promise<never>((_, reject) =>
setTimeout(
() =>
reject(
new Error(`sqlocal DB open did not resolve within ${STORAGE_OPEN_TIMEOUT_MS}ms`),
),
STORAGE_OPEN_TIMEOUT_MS,
),
),
]);
log.debug("buildMeshDevice: storage DB ready", { ms: Date.now() - t0 });
chatRepository = new SqlocalMessageRepository(db, { deviceId: connectionId, coordinator });
draftRepository = new SqlocalDraftRepository(db, { deviceId: connectionId });
nodesRepository = new SqlocalNodesRepository(db, { deviceId: connectionId });
telemetryRepository = new SqlocalTelemetryRepository(db, { deviceId: connectionId });
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,
});
}
return new MeshDevice(transport, {
configId: deviceId,
chat:
chatRepository || draftRepository
? {
repository: chatRepository,
draftRepository,
retention: CHAT_RETENTION,
}
: undefined,
nodes: nodesRepository ? { repository: nodesRepository } : undefined,
telemetry: telemetryRepository
? { repository: telemetryRepository, retention: TELEMETRY_RETENTION }
: undefined,
});
}
+263
View File
@@ -0,0 +1,263 @@
import type { Connection } from "@core/stores/deviceStore/types";
import { testHttpReachable } from "@pages/Connections/utils";
import { createLogger } from "@meshtastic/sdk";
import { TransportHTTP } from "@meshtastic/transport-http";
import { BluetoothConnectError, TransportWebBluetooth } from "@meshtastic/transport-web-bluetooth";
import { SerialConnectError, TransportWebSerial } from "@meshtastic/transport-web-serial";
import { Result } from "better-result";
import type { AnyTransport } from "./sdkClient.ts";
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;
}
export interface OpenTransportResult {
transport: AnyTransport;
/** 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: Connection,
opts: OpenTransportOptions = {},
): Promise<OpenTransportResult> {
switch (conn.type) {
case "http":
return openHttp(conn);
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 openHttp(
conn: Connection & { type: "http"; url: string },
): Promise<OpenTransportResult> {
const ok = await testHttpReachable(conn.url);
if (!ok) {
const url = new URL(conn.url);
const isHTTPS = url.protocol === "https:";
throw new Error(
isHTTPS
? `Cannot reach HTTPS endpoint. If using a self-signed certificate, open ${conn.url} in a new tab, accept the certificate warning, then try connecting again.`
: "HTTP endpoint not reachable (may be blocked by CORS)",
);
}
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";
deviceId?: string;
gattServiceUUID?: string;
},
opts: OpenTransportOptions,
): Promise<OpenTransportResult> {
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<BluetoothDevice[]>;
};
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<OpenTransportResult> {
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<SerialPort[]>;
requestPort: (options: Record<string, unknown>) => Promise<SerialPort>;
};
}
).serial;
let port = opts.cachedSerialPort;
if (!port) {
const ports = await serial.getPorts();
log.debug("openSerial: getPorts", { count: ports.length });
if (ports && conn.usbVendorId && conn.usbProductId) {
port = ports.find((p: SerialPort) => {
const info =
(
p as SerialPort & {
getInfo?: () => { usbVendorId?: number; usbProductId?: number };
}
).getInfo?.() ?? {};
return info.usbVendorId === conn.usbVendorId && info.usbProductId === conn.usbProductId;
});
}
}
if (!port && opts.allowPrompt) {
log.debug("openSerial: requesting port via picker");
port = await serial.requestPort({});
}
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 };
}
/**
* 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<"online" | "configured" | "disconnected" | "error"> {
switch (conn.type) {
case "http": {
const ok = await testHttpReachable(conn.url);
return ok ? "online" : "error";
}
case "bluetooth": {
if (!("bluetooth" in navigator)) return "disconnected";
try {
const known = await (
navigator.bluetooth as Navigator["bluetooth"] & {
getDevices?: () => Promise<BluetoothDevice[]>;
}
).getDevices?.();
const hasPermission = known?.some((d: BluetoothDevice) => d.id === conn.deviceId);
// Permission granted ≠ device configured. The card surfaces "online"
// (i.e. "available, click to connect") so the user explicitly opts
// into the configure handshake. "configured" is reserved for when
// the firmware has actually replied with config-complete.
return hasPermission ? "online" : "disconnected";
} catch {
return "disconnected";
}
}
case "serial": {
if (!("serial" in navigator)) return "disconnected";
try {
const ports: SerialPort[] = await (
navigator as Navigator & {
serial: { getPorts: () => Promise<SerialPort[]> };
}
).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 hasPermission ? "online" : "disconnected";
} catch {
return "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<void> };
if (port.close) {
try {
port.close();
} catch {}
}
}
@@ -1,5 +1,5 @@
import { create } from "@bufbuild/protobuf";
import { Protobuf } from "@meshtastic/core";
import { Protobuf } from "@meshtastic/sdk";
function createDefaultUser(num: number): Protobuf.Mesh.User {
const userIdHex = num.toString(16).toUpperCase().padStart(2, "0");
+1 -1
View File
@@ -1,6 +1,6 @@
import { MessageState, MessageType } from "@core/stores";
import type { Message } from "@core/stores/messageStore/types.ts";
import type { Types } from "@meshtastic/core";
import type { Types } from "@meshtastic/sdk";
class PacketToMessageDTO {
channel: Types.ChannelNumber;
@@ -0,0 +1,66 @@
import {
type Message as LegacyMessage,
MessageState as LegacyMessageState,
MessageType,
} from "@core/stores/messageStore";
import type { Message as SdkMessage } from "@meshtastic/sdk";
import { MessageState as SdkMessageState, type Types } from "@meshtastic/sdk";
import { useChat, useDirectChat } from "@meshtastic/sdk-react";
import { useMemo } from "react";
/**
* 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]);
}
function toLegacy(message: SdkMessage, params: UseChatAsLegacyMessagesParams): LegacyMessage {
return {
type: params.type,
channel: message.channel,
to: message.to,
from: message.from,
date: message.rxTime.getTime(),
messageId: message.id,
state: mapState(message.state),
message: message.text,
} as LegacyMessage;
}
function mapState(state: SdkMessageState): LegacyMessageState {
switch (state) {
case SdkMessageState.Ack:
return LegacyMessageState.Ack;
case SdkMessageState.Failed:
return LegacyMessageState.Failed;
case SdkMessageState.Pending:
default:
return LegacyMessageState.Waiting;
}
}
+66
View File
@@ -0,0 +1,66 @@
import {
type Message as LegacyMessage,
MessageState as LegacyMessageState,
MessageType,
} from "@core/stores/messageStore";
import type { Message as SdkMessage } from "@meshtastic/sdk";
import { MessageState as SdkMessageState, type Types } from "@meshtastic/sdk";
import { useChat, useDirectChat } from "@meshtastic/sdk-react";
import { useMemo } from "react";
/**
* 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]);
}
function toLegacy(message: SdkMessage, params: UseChatAsLegacyMessagesParams): LegacyMessage {
return {
type: params.type,
channel: message.channel,
to: message.to,
from: message.from,
date: message.rxTime.getTime(),
messageId: message.id,
state: mapState(message.state),
message: message.text,
} as LegacyMessage;
}
function mapState(state: SdkMessageState): LegacyMessageState {
switch (state) {
case SdkMessageState.Ack:
return LegacyMessageState.Ack;
case SdkMessageState.Failed:
return LegacyMessageState.Failed;
case SdkMessageState.Pending:
default:
return LegacyMessageState.Waiting;
}
}
@@ -6,7 +6,7 @@ interface UseCopyToClipboardProps {
export function useCopyToClipboard({ timeout = 2000 }: UseCopyToClipboardProps = {}) {
const [isCopied, setIsCopied] = useState<boolean>(false);
const timeoutRef = useRef<number | null>(null);
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
return () => {
+28 -35
View File
@@ -1,32 +1,17 @@
import type { Protobuf } from "@meshtastic/core";
import { act, renderHook } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { useFavoriteNode } from "./useFavoriteNode.ts";
const mockNode = {
num: 1234,
user: {
longName: "Test Node",
},
isFavorite: true,
} as unknown | Protobuf.Mesh.NodeInfo;
const mockUpdateFavorite = vi.fn();
const mockGetNode = vi.fn(() => mockNode);
const mockToast = vi.fn();
const mockSendAdminMessage = vi.fn();
const mockSdkFavorite = vi.fn();
const mockSdkUnfavorite = vi.fn();
const mockByNum = vi.fn();
const { mockUseActiveClient } = vi.hoisted(() => ({
mockUseActiveClient: vi.fn(),
}));
vi.mock("@core/stores", () => ({
CurrentDeviceContext: {
_currentValue: { deviceId: 1234 },
},
useNodeDB: () => ({
updateFavorite: mockUpdateFavorite,
getNode: mockGetNode,
}),
useDevice: () => ({
sendAdminMessage: mockSendAdminMessage,
}),
vi.mock("@meshtastic/sdk-react", () => ({
useActiveClient: mockUseActiveClient,
}));
vi.mock("@core/hooks/useToast.ts", () => ({
@@ -38,17 +23,28 @@ vi.mock("@core/hooks/useToast.ts", () => ({
describe("useFavoriteNode hook", () => {
beforeEach(() => {
vi.clearAllMocks();
mockByNum.mockReturnValue({
num: 1234,
user: { longName: "Test Node" },
isFavorite: true,
});
mockUseActiveClient.mockReturnValue({
nodes: {
byNum: mockByNum,
favorite: mockSdkFavorite,
unfavorite: mockSdkUnfavorite,
},
});
});
it("calls updateFavorite and shows correct toast", () => {
it("calls SDK favorite and shows correct toast", () => {
const { result } = renderHook(() => useFavoriteNode());
act(() => {
result.current.updateFavorite({ nodeNum: 1234, isFavorite: true });
});
expect(mockUpdateFavorite).toHaveBeenCalledWith(1234, true);
expect(mockGetNode).toHaveBeenCalledWith(1234);
expect(mockSdkFavorite).toHaveBeenCalledWith(1234);
expect(mockToast).toHaveBeenCalledWith({
title: "Added Test Node to favorites.",
});
@@ -61,18 +57,14 @@ describe("useFavoriteNode hook", () => {
result.current.updateFavorite({ nodeNum: 1234, isFavorite: false });
});
expect(mockUpdateFavorite).toHaveBeenCalledWith(1234, false);
expect(mockGetNode).toHaveBeenCalledWith(1234);
expect(mockSdkUnfavorite).toHaveBeenCalledWith(1234);
expect(mockToast).toHaveBeenCalledWith({
title: "Removed Test Node from favorites.",
});
});
it("falls back to 'node' if longName is missing", () => {
mockGetNode.mockReturnValueOnce({
num: 5678,
user: {},
}); // no longName
mockByNum.mockReturnValueOnce({ num: 5678, user: {} });
const { result } = renderHook(() => useFavoriteNode());
@@ -85,8 +77,8 @@ describe("useFavoriteNode hook", () => {
});
});
it("falls back to 'node' if getNode returns undefined", () => {
mockGetNode.mockReturnValueOnce(undefined);
it("no-ops if node is not in the SDK store", () => {
mockByNum.mockReturnValueOnce(undefined);
const { result } = renderHook(() => useFavoriteNode());
@@ -94,7 +86,8 @@ describe("useFavoriteNode hook", () => {
result.current.updateFavorite({ nodeNum: 9999, isFavorite: false });
});
expect(mockUpdateFavorite).not.toHaveBeenCalled();
expect(mockSdkFavorite).not.toHaveBeenCalled();
expect(mockSdkUnfavorite).not.toHaveBeenCalled();
expect(mockToast).not.toHaveBeenCalled();
});
});
+12 -22
View File
@@ -1,7 +1,5 @@
import { create } from "@bufbuild/protobuf";
import { useToast } from "@core/hooks/useToast.ts";
import { useDevice, useNodeDB } from "@core/stores";
import { Protobuf } from "@meshtastic/core";
import { useActiveClient } from "@meshtastic/sdk-react";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
@@ -10,44 +8,36 @@ interface FavoriteNodeOptions {
isFavorite: boolean;
}
/**
* Toggles the favorite flag on a node. Drives the SDK NodesClient which
* sends the matching admin message and flips the local flag on success.
*/
export function useFavoriteNode() {
const { sendAdminMessage } = useDevice();
const { getNode, updateFavorite } = useNodeDB();
const meshClient = useActiveClient();
const { t } = useTranslation();
const { toast } = useToast();
const updateFavoriteCB = useCallback(
({ nodeNum, isFavorite }: FavoriteNodeOptions) => {
const node = getNode(nodeNum);
if (!node) {
return;
}
if (!meshClient) return;
const node = meshClient.nodes.byNum(nodeNum);
if (!node) return;
sendAdminMessage(
create(Protobuf.Admin.AdminMessageSchema, {
payloadVariant: {
case: isFavorite ? "setFavoriteNode" : "removeFavoriteNode",
value: nodeNum,
},
}),
);
// TODO: Wait for response before changing the store
updateFavorite(nodeNum, isFavorite);
void (isFavorite ? meshClient.nodes.favorite(nodeNum) : meshClient.nodes.unfavorite(nodeNum));
toast({
title: t("toast.favoriteNode.title", {
action: isFavorite
? t("toast.favoriteNode.action.added")
: t("toast.favoriteNode.action.removed"),
nodeName: node?.user?.longName ?? t("node"),
nodeName: node.user?.longName ?? t("node"),
direction: isFavorite
? t("toast.favoriteNode.action.to")
: t("toast.favoriteNode.action.from"),
}),
});
},
[updateFavorite, sendAdminMessage, getNode, t, toast],
[meshClient, t, toast],
);
return { updateFavorite: updateFavoriteCB };
+29 -39
View File
@@ -1,32 +1,17 @@
import type { Protobuf } from "@meshtastic/core";
import { act, renderHook } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { useIgnoreNode } from "./useIgnoreNode.ts";
const mockNode = {
num: 1234,
user: {
longName: "Test Node",
},
isIgnored: true,
} as unknown | Protobuf.Mesh.NodeInfo;
const mockUpdateIgnore = vi.fn();
const mockGetNode = vi.fn(() => mockNode);
const mockToast = vi.fn();
const mockSendAdminMessage = vi.fn();
const mockSdkIgnore = vi.fn();
const mockSdkUnignore = vi.fn();
const mockByNum = vi.fn();
const { mockUseActiveClient } = vi.hoisted(() => ({
mockUseActiveClient: vi.fn(),
}));
vi.mock("@core/stores", () => ({
CurrentDeviceContext: {
_currentValue: { deviceId: 1234 },
},
useNodeDB: () => ({
updateIgnore: mockUpdateIgnore,
getNode: mockGetNode,
}),
useDevice: () => ({
sendAdminMessage: mockSendAdminMessage,
}),
vi.mock("@meshtastic/sdk-react", () => ({
useActiveClient: mockUseActiveClient,
}));
vi.mock("@core/hooks/useToast.ts", () => ({
@@ -38,17 +23,28 @@ vi.mock("@core/hooks/useToast.ts", () => ({
describe("useIgnoreNode hook", () => {
beforeEach(() => {
vi.clearAllMocks();
mockByNum.mockReturnValue({
num: 1234,
user: { longName: "Test Node" },
isIgnored: true,
});
mockUseActiveClient.mockReturnValue({
nodes: {
byNum: mockByNum,
ignore: mockSdkIgnore,
unignore: mockSdkUnignore,
},
});
});
it("calls updateIgnored and shows correct toast", () => {
it("calls SDK ignore and shows correct toast", () => {
const { result } = renderHook(() => useIgnoreNode());
act(() => {
result.current.updateIgnored({ nodeNum: 1234, isIgnored: true });
});
expect(mockUpdateIgnore).toHaveBeenCalledWith(1234, true);
expect(mockGetNode).toHaveBeenCalledWith(1234);
expect(mockSdkIgnore).toHaveBeenCalledWith(1234);
expect(mockToast).toHaveBeenCalledWith({
title: "Added Test Node to ignore list",
});
@@ -58,24 +54,17 @@ describe("useIgnoreNode hook", () => {
const { result } = renderHook(() => useIgnoreNode());
act(() => {
result.current.updateIgnored({
nodeNum: 1234,
isIgnored: false,
});
result.current.updateIgnored({ nodeNum: 1234, isIgnored: false });
});
expect(mockUpdateIgnore).toHaveBeenCalledWith(1234, false);
expect(mockGetNode).toHaveBeenCalledWith(1234);
expect(mockSdkUnignore).toHaveBeenCalledWith(1234);
expect(mockToast).toHaveBeenCalledWith({
title: "Removed Test Node from ignore list",
});
});
it("falls back to 'node' if longName is missing", () => {
mockGetNode.mockReturnValueOnce({
num: 5678,
user: {},
}); // no longName
mockByNum.mockReturnValueOnce({ num: 5678, user: {} });
const { result } = renderHook(() => useIgnoreNode());
@@ -88,8 +77,8 @@ describe("useIgnoreNode hook", () => {
});
});
it("falls back to 'node' if getNode returns undefined", () => {
mockGetNode.mockReturnValueOnce(undefined);
it("no-ops if node is not in the SDK store", () => {
mockByNum.mockReturnValueOnce(undefined);
const { result } = renderHook(() => useIgnoreNode());
@@ -97,7 +86,8 @@ describe("useIgnoreNode hook", () => {
result.current.updateIgnored({ nodeNum: 9999, isIgnored: false });
});
expect(mockUpdateIgnore).not.toHaveBeenCalled();
expect(mockSdkIgnore).not.toHaveBeenCalled();
expect(mockSdkUnignore).not.toHaveBeenCalled();
expect(mockToast).not.toHaveBeenCalled();
});
});
+12 -24
View File
@@ -1,7 +1,5 @@
import { create } from "@bufbuild/protobuf";
import { useToast } from "@core/hooks/useToast.ts";
import { useDevice, useNodeDB } from "@core/stores";
import { Protobuf } from "@meshtastic/core";
import { useActiveClient } from "@meshtastic/sdk-react";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
@@ -10,36 +8,26 @@ interface IgnoreNodeOptions {
isIgnored: boolean;
}
/**
* Toggles the ignored flag on a node. Drives the SDK NodesClient which
* sends the matching admin message and flips the local flag on success.
*/
export function useIgnoreNode() {
const { sendAdminMessage } = useDevice();
const { getNode, updateIgnore } = useNodeDB();
const meshClient = useActiveClient();
const { t } = useTranslation();
const { toast } = useToast();
const updateIgnoredCB = useCallback(
({ nodeNum, isIgnored }: IgnoreNodeOptions) => {
const node = getNode(nodeNum);
if (!node) {
return;
}
if (!meshClient) return;
const node = meshClient.nodes.byNum(nodeNum);
if (!node) return;
sendAdminMessage(
create(Protobuf.Admin.AdminMessageSchema, {
payloadVariant: {
case: isIgnored ? "setIgnoredNode" : "removeIgnoredNode",
value: nodeNum,
},
}),
);
// TODO: Wait for response before changing the store
updateIgnore(nodeNum, isIgnored);
void (isIgnored ? meshClient.nodes.ignore(nodeNum) : meshClient.nodes.unignore(nodeNum));
toast({
title: t("toast.ignoreNode.title", {
nodeName: node?.user?.longName ?? "node",
nodeName: node.user?.longName ?? "node",
action: isIgnored
? t("toast.ignoreNode.action.added")
: t("toast.ignoreNode.action.removed"),
@@ -49,7 +37,7 @@ export function useIgnoreNode() {
}),
});
},
[sendAdminMessage, updateIgnore, getNode, t, toast],
[meshClient, t, toast],
);
return { updateIgnored: updateIgnoredCB };
+1 -1
View File
@@ -1,5 +1,5 @@
import { boundsFromLngLat, type LngLat, toLngLat } from "@core/utils/geo";
import type { Protobuf } from "@meshtastic/core";
import type { Protobuf } from "@meshtastic/sdk";
import { useCallback } from "react";
import type { MapRef } from "react-map-gl/maplibre";
+2 -4
View File
@@ -1,8 +1,6 @@
import { useDeviceStore, useMessageStore, useNodeDBStore } from "@core/stores";
import type { Protobuf } from "@meshtastic/core";
import { useDeviceStore } from "@core/stores";
import type { Protobuf } from "@meshtastic/sdk";
export function useNewNodeNum(id: number, nodeInfo: Protobuf.Mesh.MyNodeInfo): void {
useDeviceStore.getState().getDevice(id)?.setHardware(nodeInfo);
useNodeDBStore.getState().getNodeDB(id)?.setNodeNum(nodeInfo.myNodeNum);
useMessageStore.getState().getMessageStore(id)?.setNodeNum(nodeInfo.myNodeNum);
}
@@ -0,0 +1,89 @@
import { create } from "@bufbuild/protobuf";
import type { Node as SdkNode } from "@meshtastic/sdk";
import { Protobuf } from "@meshtastic/sdk";
import { useActiveClient, useSignal } from "@meshtastic/sdk-react";
import { useMemo } from "react";
/**
* Adapter hooks that surface SDK-managed nodes in the
* `Protobuf.Mesh.NodeInfo` shape consumed by web components today.
*
* Wraps the SDK Node into the legacy proto shape so the existing
* components keep working without rewrites. Removed once every consumer
* reads `Node` from the SDK directly.
*
* Reads through `useActiveClient()` so that, when no client is active
* (e.g. inside isolated component tests or before any device connects),
* the hooks return safe empty values instead of throwing.
*/
const EMPTY_NODES: ReadonlyArray<SdkNode> = [];
function useSdkNodesSafe(): ReadonlyArray<SdkNode> {
const client = useActiveClient();
// Always pass *something* to useSignal so the hook count stays stable
// across the with-client / without-client branches.
return useSignal(
client?.nodes.list ?? {
value: EMPTY_NODES,
peek: () => EMPTY_NODES,
subscribe: () => () => {},
},
);
}
function useMyNodeNumSafe(): number | undefined {
const client = useActiveClient();
return useSignal(
client?.device.myNodeNum ?? {
value: undefined,
peek: () => undefined,
subscribe: () => () => {},
},
);
}
export function useNodesAsProto(): Protobuf.Mesh.NodeInfo[] {
const nodes = useSdkNodesSafe();
return useMemo(() => nodes.map(toNodeInfo), [nodes]);
}
export function useNodeAsProto(nodeNum: number): Protobuf.Mesh.NodeInfo | undefined {
const nodes = useSdkNodesSafe();
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 or there is no active client.
*/
export function useMyNodeAsProto(): Protobuf.Mesh.NodeInfo | undefined {
const myNodeNum = useMyNodeNumSafe();
const nodes = useSdkNodesSafe();
return useMemo(() => {
if (myNodeNum === undefined) return undefined;
const found = nodes.find((n) => n.num === myNodeNum);
return found ? toNodeInfo(found) : undefined;
}, [myNodeNum, nodes]);
}
function toNodeInfo(node: SdkNode): Protobuf.Mesh.NodeInfo {
return create(Protobuf.Mesh.NodeInfoSchema, {
num: node.num,
user: node.user,
position: node.position,
deviceMetrics: node.deviceMetrics,
snr: node.snr ?? 0,
lastHeard: node.lastHeard ?? 0,
channel: node.channel ?? 0,
viaMqtt: node.viaMqtt ?? false,
hopsAway: node.hopsAway,
isFavorite: node.isFavorite,
isIgnored: node.isIgnored,
isKeyManuallyVerified: node.isKeyManuallyVerified ?? false,
});
}
+59
View File
@@ -0,0 +1,59 @@
import { create } from "@bufbuild/protobuf";
import type { Node as SdkNode } from "@meshtastic/sdk";
import { Protobuf } from "@meshtastic/sdk";
import { useMeshDevice, useNodes } from "@meshtastic/sdk-react";
import { useMemo } from "react";
/**
* 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]);
}
function toNodeInfo(node: SdkNode): Protobuf.Mesh.NodeInfo {
return create(Protobuf.Mesh.NodeInfoSchema, {
num: node.num,
user: node.user,
position: node.position,
deviceMetrics: node.deviceMetrics,
snr: node.snr ?? 0,
lastHeard: node.lastHeard ?? 0,
channel: node.channel ?? 0,
viaMqtt: node.viaMqtt ?? false,
hopsAway: node.hopsAway,
isFavorite: node.isFavorite,
isIgnored: node.isIgnored,
isKeyManuallyVerified: node.isKeyManuallyVerified ?? false,
});
}
+14
View File
@@ -0,0 +1,14 @@
import { MeshRegistry } from "@meshtastic/sdk";
/**
* App-wide MeshRegistry singleton.
*
* Holds one `MeshClient` per active connection. Wrapped at the root by
* `<MeshRegistryProvider registry={meshRegistry}>` 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();
+45
View File
@@ -0,0 +1,45 @@
import { createLogger } from "@meshtastic/sdk";
import {
createSqlocalDb,
MultiTabCoordinator,
type SqlocalDb,
} from "@meshtastic/sdk-storage-sqlocal";
const log = createLogger("sdkStorage");
/**
* Lazy singletons for the chat (and future nodes/telemetry) persistence layer.
*
* `getStorageDb()` opens the OPFS-backed SQLite database on first call and
* returns the same Drizzle client on subsequent calls. `coordinator` is a
* shared `MultiTabCoordinator` for cross-tab change broadcasts.
*
* The database is opened only when a feature actually needs it; importing
* this module is side-effect-free so unit tests that don't touch storage
* stay fast and headless-safe.
*/
let dbPromise: Promise<SqlocalDb> | undefined;
export function getStorageDb(): Promise<SqlocalDb> {
if (!dbPromise) {
log.debug("getStorageDb: creating sqlocal DB", { path: "meshtastic.db" });
const t0 = Date.now();
dbPromise = createSqlocalDb({ databasePath: "meshtastic.db" })
.then((db) => {
log.info("getStorageDb: sqlocal DB ready", { ms: Date.now() - t0 });
return db;
})
.catch((err) => {
const e = err as Error;
log.error("getStorageDb: sqlocal DB open failed", {
ms: Date.now() - t0,
name: e?.name,
message: e?.message,
});
throw err;
});
}
return dbPromise;
}
export const coordinator = new MultiTabCoordinator();
@@ -5,7 +5,6 @@ console.log(`Dev mode: ${isDev}`);
if (isDev) {
featureFlags.setOverrides({
persistNodeDB: true,
persistMessages: true,
persistApp: true,
});
@@ -2,7 +2,6 @@ import { z } from "zod";
/** Map feature keys -> env var names (Vite exposes only VITE_*). */
export const FLAG_ENV = {
persistNodeDB: "VITE_PERSIST_NODE_DB",
persistMessages: "VITE_PERSIST_MESSAGES",
persistDevices: "VITE_PERSIST_DEVICES",
persistApp: "VITE_PERSIST_APP",
@@ -1,256 +0,0 @@
import type { Types } from "@meshtastic/core";
// Config type discriminators
export type ValidConfigType =
| "device"
| "position"
| "power"
| "network"
| "display"
| "lora"
| "bluetooth"
| "security";
export type ValidModuleConfigType =
| "mqtt"
| "serial"
| "externalNotification"
| "storeForward"
| "rangeTest"
| "telemetry"
| "cannedMessage"
| "audio"
| "neighborInfo"
| "ambientLighting"
| "detectionSensor"
| "paxcounter"
| "remoteHardware"
| "statusmessage"
| "trafficManagement"
| "tak";
// Admin message types that can be queued
export type ValidAdminMessageType = "setFixedPosition" | "other";
// Unified config change key type
export type ConfigChangeKey =
| { type: "config"; variant: ValidConfigType }
| { type: "moduleConfig"; variant: ValidModuleConfigType }
| { type: "channel"; index: Types.ChannelNumber }
| { type: "user" }
| { type: "adminMessage"; variant: ValidAdminMessageType; id: string };
// Serialized key for Map storage
export type ConfigChangeKeyString = string;
// Registry entry
export interface ChangeEntry {
key: ConfigChangeKey;
value: unknown;
timestamp: number;
originalValue?: unknown;
}
// The unified registry
export interface ChangeRegistry {
changes: Map<ConfigChangeKeyString, ChangeEntry>;
}
/**
* Convert structured key to string for Map lookup
*/
export function serializeKey(key: ConfigChangeKey): ConfigChangeKeyString {
switch (key.type) {
case "config":
return `config:${key.variant}`;
case "moduleConfig":
return `moduleConfig:${key.variant}`;
case "channel":
return `channel:${key.index}`;
case "user":
return "user";
case "adminMessage":
return `adminMessage:${key.variant}:${key.id}`;
}
}
/**
* Reverse operation for type-safe retrieval
*/
export function deserializeKey(keyStr: ConfigChangeKeyString): ConfigChangeKey {
const parts = keyStr.split(":");
const type = parts[0];
switch (type) {
case "config":
return { type: "config", variant: parts[1] as ValidConfigType };
case "moduleConfig":
return {
type: "moduleConfig",
variant: parts[1] as ValidModuleConfigType,
};
case "channel":
return {
type: "channel",
index: Number(parts[1]) as Types.ChannelNumber,
};
case "user":
return { type: "user" };
case "adminMessage":
return {
type: "adminMessage",
variant: parts[1] as ValidAdminMessageType,
id: parts[2] ?? "",
};
default:
throw new Error(`Unknown key type: ${type}`);
}
}
/**
* Create an empty change registry
*/
export function createChangeRegistry(): ChangeRegistry {
return {
changes: new Map(),
};
}
/**
* Check if a config variant has changes
*/
export function hasConfigChange(registry: ChangeRegistry, variant: ValidConfigType): boolean {
return registry.changes.has(serializeKey({ type: "config", variant }));
}
/**
* Check if a module config variant has changes
*/
export function hasModuleConfigChange(
registry: ChangeRegistry,
variant: ValidModuleConfigType,
): boolean {
return registry.changes.has(serializeKey({ type: "moduleConfig", variant }));
}
/**
* Check if a channel has changes
*/
export function hasChannelChange(registry: ChangeRegistry, index: Types.ChannelNumber): boolean {
return registry.changes.has(serializeKey({ type: "channel", index }));
}
/**
* Check if user config has changes
*/
export function hasUserChange(registry: ChangeRegistry): boolean {
return registry.changes.has(serializeKey({ type: "user" }));
}
/**
* Get count of config changes
*/
export function getConfigChangeCount(registry: ChangeRegistry): number {
let count = 0;
for (const keyStr of registry.changes.keys()) {
const key = deserializeKey(keyStr);
if (key.type === "config") {
count++;
}
}
return count;
}
/**
* Get count of module config changes
*/
export function getModuleConfigChangeCount(registry: ChangeRegistry): number {
let count = 0;
for (const keyStr of registry.changes.keys()) {
const key = deserializeKey(keyStr);
if (key.type === "moduleConfig") {
count++;
}
}
return count;
}
/**
* Get count of channel changes
*/
export function getChannelChangeCount(registry: ChangeRegistry): number {
let count = 0;
for (const keyStr of registry.changes.keys()) {
const key = deserializeKey(keyStr);
if (key.type === "channel") {
count++;
}
}
return count;
}
/**
* Get all config changes as an array
*/
export function getAllConfigChanges(registry: ChangeRegistry): ChangeEntry[] {
const changes: ChangeEntry[] = [];
for (const entry of registry.changes.values()) {
if (entry.key.type === "config") {
changes.push(entry);
}
}
return changes;
}
/**
* Get all module config changes as an array
*/
export function getAllModuleConfigChanges(registry: ChangeRegistry): ChangeEntry[] {
const changes: ChangeEntry[] = [];
for (const entry of registry.changes.values()) {
if (entry.key.type === "moduleConfig") {
changes.push(entry);
}
}
return changes;
}
/**
* Get all channel changes as an array
*/
export function getAllChannelChanges(registry: ChangeRegistry): ChangeEntry[] {
const changes: ChangeEntry[] = [];
for (const entry of registry.changes.values()) {
if (entry.key.type === "channel") {
changes.push(entry);
}
}
return changes;
}
/**
* Get all admin message changes as an array
*/
export function getAllAdminMessages(registry: ChangeRegistry): ChangeEntry[] {
const changes: ChangeEntry[] = [];
for (const entry of registry.changes.values()) {
if (entry.key.type === "adminMessage") {
changes.push(entry);
}
}
return changes;
}
/**
* Get count of admin message changes
*/
export function getAdminMessageChangeCount(registry: ChangeRegistry): number {
let count = 0;
for (const keyStr of registry.changes.keys()) {
const key = deserializeKey(keyStr);
if (key.type === "adminMessage") {
count++;
}
}
return count;
}
@@ -1,4 +1,4 @@
import type { Protobuf } from "@meshtastic/core";
import type { Protobuf } from "@meshtastic/sdk";
import { vi } from "vitest";
import type { Device } from "./index.ts";
@@ -16,10 +16,11 @@ export const mockDeviceStore: Device = {
id: 0,
myNodeNum: 123456,
status: 5 as const,
connectionPhase: "disconnected",
connectionId: null,
channels: new Map(),
config: {} as Protobuf.LocalOnly.LocalConfig,
moduleConfig: {} as Protobuf.LocalOnly.LocalModuleConfig,
changeRegistry: { changes: new Map() },
hardware: {} as Protobuf.Mesh.MyNodeInfo,
metadata: new Map(),
traceroutes: new Map(),
@@ -28,7 +29,6 @@ export const mockDeviceStore: Device = {
waypoints: [],
pendingSettingsChanges: false,
messageDraft: "",
unreadCounts: new Map(),
dialog: {
import: false,
QR: false,
@@ -52,6 +52,8 @@ export const mockDeviceStore: Device = {
neighborInfo: new Map(),
setStatus: vi.fn(),
setConnectionPhase: vi.fn(),
setConnectionId: vi.fn(),
setConfig: vi.fn(),
setModuleConfig: vi.fn(),
getEffectiveConfig: vi.fn(),
@@ -69,31 +71,10 @@ export const mockDeviceStore: Device = {
setDialogOpen: vi.fn(),
getDialogOpen: vi.fn().mockReturnValue(false),
setMessageDraft: vi.fn(),
incrementUnread: vi.fn(),
resetUnread: vi.fn(),
sendAdminMessage: vi.fn(),
addClientNotification: vi.fn(),
removeClientNotification: vi.fn(),
getClientNotification: vi.fn(),
getAllUnreadCount: vi.fn().mockReturnValue(0),
getUnreadCount: vi.fn().mockReturnValue(0),
getNeighborInfo: vi.fn(),
addNeighborInfo: vi.fn(),
// New unified change tracking methods
setChange: vi.fn(),
removeChange: vi.fn(),
hasChange: vi.fn().mockReturnValue(false),
getChange: vi.fn(),
clearAllChanges: vi.fn(),
hasConfigChange: vi.fn().mockReturnValue(false),
hasModuleConfigChange: vi.fn().mockReturnValue(false),
hasChannelChange: vi.fn().mockReturnValue(false),
hasUserChange: vi.fn().mockReturnValue(false),
getConfigChangeCount: vi.fn().mockReturnValue(0),
getModuleConfigChangeCount: vi.fn().mockReturnValue(0),
getChannelChangeCount: vi.fn().mockReturnValue(0),
getAllConfigChanges: vi.fn().mockReturnValue([]),
getAllModuleConfigChanges: vi.fn().mockReturnValue([]),
getAllChannelChanges: vi.fn().mockReturnValue([]),
};
@@ -1,5 +1,5 @@
import { create, toBinary } from "@bufbuild/protobuf";
import { Protobuf, type Types } from "@meshtastic/core";
import { Protobuf, type Types } from "@meshtastic/sdk";
import { beforeEach, describe, expect, it, vi } from "vitest";
const idbMem = new Map<string, string>();
@@ -31,8 +31,7 @@ async function freshStore(persist = false) {
}));
const storeMod = await import("./index.ts");
const { useNodeDB } = await import("../index.ts");
return { ...storeMod, useNodeDB };
return storeMod;
}
function makeHardware(myNodeNum: number) {
@@ -46,9 +45,6 @@ function makeRoute(from: number, time = Date.now() / 1000) {
data: create(Protobuf.Mesh.RouteDiscoverySchema, {}),
} as unknown as Types.PacketMetadata<Protobuf.Mesh.RouteDiscovery>;
}
function makeChannel(index: number) {
return create(Protobuf.Channel.ChannelSchema, { index });
}
function makeWaypoint(id: number, expire?: number) {
return create(Protobuf.Mesh.WaypointSchema, { id, expire });
}
@@ -96,194 +92,6 @@ describe("DeviceStore – basic map ops & retention", () => {
});
});
describe("DeviceStore – change registry API", () => {
beforeEach(() => {
idbMem.clear();
vi.clearAllMocks();
});
it("setChange/hasChange/getChange for config and getEffectiveConfig merges base + working", async () => {
const { useDeviceStore } = await freshStore(false);
const state = useDeviceStore.getState();
const device = state.addDevice(42);
// config deviceConfig.role = CLIENT
device.setConfig(
create(Protobuf.Config.ConfigSchema, {
payloadVariant: {
case: "device",
value: create(Protobuf.Config.Config_DeviceConfigSchema, {
role: Protobuf.Config.Config_DeviceConfig_Role.CLIENT,
}),
},
}),
);
// working deviceConfig.role = ROUTER
const routerConfig = create(Protobuf.Config.Config_DeviceConfigSchema, {
role: Protobuf.Config.Config_DeviceConfig_Role.ROUTER,
});
device.setChange({ type: "config", variant: "device" }, routerConfig);
// expect change is tracked
expect(device.hasConfigChange("device")).toBe(true);
const working = device.getChange({
type: "config",
variant: "device",
}) as Protobuf.Config.Config_DeviceConfig;
expect(working?.role).toBe(Protobuf.Config.Config_DeviceConfig_Role.ROUTER);
// expect effective deviceConfig.role = ROUTER
const effective = device.getEffectiveConfig("device");
expect(effective?.role).toBe(Protobuf.Config.Config_DeviceConfig_Role.ROUTER);
// remove change, effective should equal base
device.removeChange({ type: "config", variant: "device" });
expect(device.hasConfigChange("device")).toBe(false);
expect(device.getEffectiveConfig("device")?.role).toBe(
Protobuf.Config.Config_DeviceConfig_Role.CLIENT,
);
// add multiple, then clear all
device.setChange({ type: "config", variant: "device" }, routerConfig);
device.setChange({ type: "config", variant: "position" }, {});
device.clearAllChanges();
expect(device.hasConfigChange("device")).toBe(false);
expect(device.hasConfigChange("position")).toBe(false);
});
it("setChange/hasChange for moduleConfig and getEffectiveModuleConfig", async () => {
const { useDeviceStore } = await freshStore(false);
const state = useDeviceStore.getState();
const device = state.addDevice(7);
// base moduleConfig.mqtt with base address
device.setModuleConfig(
create(Protobuf.ModuleConfig.ModuleConfigSchema, {
payloadVariant: {
case: "mqtt",
value: create(Protobuf.ModuleConfig.ModuleConfig_MQTTConfigSchema, {
address: "mqtt://base",
}),
},
}),
);
// working mqtt config
const workingMqtt = create(Protobuf.ModuleConfig.ModuleConfig_MQTTConfigSchema, {
address: "mqtt://working",
});
device.setChange({ type: "moduleConfig", variant: "mqtt" }, workingMqtt);
expect(device.hasModuleConfigChange("mqtt")).toBe(true);
const mqtt = device.getChange({
type: "moduleConfig",
variant: "mqtt",
}) as Protobuf.ModuleConfig.ModuleConfig_MQTTConfig;
expect(mqtt?.address).toBe("mqtt://working");
// effective should return working value
expect(device.getEffectiveModuleConfig("mqtt")?.address).toBe("mqtt://working");
// remove change
device.removeChange({ type: "moduleConfig", variant: "mqtt" });
expect(device.hasModuleConfigChange("mqtt")).toBe(false);
expect(device.getEffectiveModuleConfig("mqtt")?.address).toBe("mqtt://base");
// Clear all
device.setChange({ type: "moduleConfig", variant: "mqtt" }, workingMqtt);
device.clearAllChanges();
expect(device.hasModuleConfigChange("mqtt")).toBe(false);
});
it("setModuleConfig stores the firmware-current module variants", async () => {
const { useDeviceStore } = await freshStore(false);
const device = useDeviceStore.getState().addDevice(11);
device.setModuleConfig(
create(Protobuf.ModuleConfig.ModuleConfigSchema, {
payloadVariant: {
case: "trafficManagement",
value: create(Protobuf.ModuleConfig.ModuleConfig_TrafficManagementConfigSchema, {
enabled: true,
rateLimitMaxPackets: 5,
}),
},
}),
);
device.setModuleConfig(
create(Protobuf.ModuleConfig.ModuleConfigSchema, {
payloadVariant: {
case: "statusmessage",
value: create(Protobuf.ModuleConfig.ModuleConfig_StatusMessageConfigSchema, {
nodeStatus: "online",
}),
},
}),
);
device.setModuleConfig(
create(Protobuf.ModuleConfig.ModuleConfigSchema, {
payloadVariant: {
case: "remoteHardware",
value: create(Protobuf.ModuleConfig.ModuleConfig_RemoteHardwareConfigSchema, {
enabled: true,
}),
},
}),
);
expect(device.getEffectiveModuleConfig("trafficManagement")?.enabled).toBe(true);
expect(device.getEffectiveModuleConfig("trafficManagement")?.rateLimitMaxPackets).toBe(5);
expect(device.getEffectiveModuleConfig("statusmessage")?.nodeStatus).toBe("online");
expect(device.getEffectiveModuleConfig("remoteHardware")?.enabled).toBe(true);
});
it("channel change tracking add/update/remove/get", async () => {
const { useDeviceStore } = await freshStore(false);
const state = useDeviceStore.getState();
const device = state.addDevice(9);
const channel0 = makeChannel(0);
const channel1 = create(Protobuf.Channel.ChannelSchema, {
index: 1,
settings: { name: "one" },
});
device.setChange({ type: "channel", index: 0 }, channel0);
device.setChange({ type: "channel", index: 1 }, channel1);
expect(device.hasChannelChange(0)).toBe(true);
expect(device.hasChannelChange(1)).toBe(true);
const ch0 = device.getChange({ type: "channel", index: 0 }) as
| Protobuf.Channel.Channel
| undefined;
expect(ch0?.index).toBe(0);
const ch1 = device.getChange({ type: "channel", index: 1 }) as
| Protobuf.Channel.Channel
| undefined;
expect(ch1?.settings?.name).toBe("one");
// update channel 1
const channel1Updated = create(Protobuf.Channel.ChannelSchema, {
index: 1,
settings: { name: "uno" },
});
device.setChange({ type: "channel", index: 1 }, channel1Updated);
const ch1Updated = device.getChange({ type: "channel", index: 1 }) as
| Protobuf.Channel.Channel
| undefined;
expect(ch1Updated?.settings?.name).toBe("uno");
// remove specific
device.removeChange({ type: "channel", index: 1 });
expect(device.hasChannelChange(1)).toBe(false);
// remove all
device.clearAllChanges();
expect(device.hasChannelChange(0)).toBe(false);
});
});
describe("DeviceStore – metadata, dialogs, unread counts, message draft", () => {
beforeEach(() => {
idbMem.clear();
@@ -318,24 +126,6 @@ describe("DeviceStore – metadata, dialogs, unread counts, message draft", () =
expect(() => device.getDialogOpen("reboot")).toThrow(/Device 5 not found/);
});
it("unread counts: increment/get/getAll/reset", async () => {
const { useDeviceStore } = await freshStore(false);
const state = useDeviceStore.getState();
const device = state.addDevice(2);
expect(device.getUnreadCount(10)).toBe(0);
device.incrementUnread(10);
device.incrementUnread(10);
device.incrementUnread(11);
expect(device.getUnreadCount(10)).toBe(2);
expect(device.getUnreadCount(11)).toBe(1);
expect(device.getAllUnreadCount()).toBe(3);
device.resetUnread(10);
expect(device.getUnreadCount(10)).toBe(0);
expect(device.getAllUnreadCount()).toBe(1);
});
it("setMessageDraft stores the text", async () => {
const { useDeviceStore } = await freshStore(false);
const device = useDeviceStore.getState().addDevice(3);
+23 -355
View File
@@ -1,27 +1,10 @@
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/core";
import { produce } from "immer";
import { type MeshDevice, Protobuf, Types } from "@meshtastic/sdk";
import { type Draft, produce } from "immer";
import { create as createStore, type StateCreator } from "zustand";
import { type PersistOptions, persist, subscribeWithSelector } from "zustand/middleware";
import type { ChangeRegistry, ConfigChangeKey } from "./changeRegistry.ts";
import {
createChangeRegistry,
getAdminMessageChangeCount,
getAllAdminMessages,
getAllChannelChanges,
getAllConfigChanges,
getAllModuleConfigChanges,
getChannelChangeCount,
getConfigChangeCount,
getModuleConfigChangeCount,
hasChannelChange,
hasConfigChange,
hasModuleConfigChange,
hasUserChange,
serializeKey,
} from "./changeRegistry.ts";
import type {
Connection,
ConnectionId,
@@ -57,14 +40,12 @@ export interface Device extends DeviceData {
channels: Map<Types.ChannelNumber, Protobuf.Channel.Channel>;
config: Protobuf.LocalOnly.LocalConfig;
moduleConfig: Protobuf.LocalOnly.LocalModuleConfig;
changeRegistry: ChangeRegistry; // Unified change tracking
hardware: Protobuf.Mesh.MyNodeInfo;
metadata: Map<number, Protobuf.Mesh.DeviceMetadata>;
connection?: MeshDevice;
activeNode: number;
pendingSettingsChanges: boolean;
messageDraft: string;
unreadCounts: Map<number, number>;
dialog: Dialogs;
clientNotifications: Protobuf.Mesh.ClientNotification[];
@@ -97,36 +78,12 @@ export interface Device extends DeviceData {
setDialogOpen: (dialog: DialogVariant, open: boolean) => void;
getDialogOpen: (dialog: DialogVariant) => boolean;
setMessageDraft: (message: string) => void;
incrementUnread: (nodeNum: number) => void;
resetUnread: (nodeNum: number) => void;
getUnreadCount: (nodeNum: number) => number;
getAllUnreadCount: () => number;
sendAdminMessage: (message: Protobuf.Admin.AdminMessage) => void;
addClientNotification: (clientNotificationPacket: Protobuf.Mesh.ClientNotification) => void;
removeClientNotification: (index: number) => void;
getClientNotification: (index: number) => Protobuf.Mesh.ClientNotification | undefined;
addNeighborInfo: (nodeNum: number, neighborInfo: Protobuf.Mesh.NeighborInfo) => void;
getNeighborInfo: (nodeNum: number) => Protobuf.Mesh.NeighborInfo | undefined;
// New unified change tracking methods
setChange: (key: ConfigChangeKey, value: unknown, originalValue?: unknown) => void;
removeChange: (key: ConfigChangeKey) => void;
hasChange: (key: ConfigChangeKey) => boolean;
getChange: (key: ConfigChangeKey) => unknown | undefined;
clearAllChanges: () => void;
hasConfigChange: (variant: ValidConfigType) => boolean;
hasModuleConfigChange: (variant: ValidModuleConfigType) => boolean;
hasChannelChange: (index: Types.ChannelNumber) => boolean;
hasUserChange: () => boolean;
getConfigChangeCount: () => number;
getModuleConfigChangeCount: () => number;
getChannelChangeCount: () => number;
getAllConfigChanges: () => Protobuf.Config.Config[];
getAllModuleConfigChanges: () => Protobuf.ModuleConfig.ModuleConfig[];
getAllChannelChanges: () => Protobuf.Channel.Channel[];
queueAdminMessage: (message: Protobuf.Admin.AdminMessage) => void;
getAllQueuedAdminMessages: () => Protobuf.Admin.AdminMessage[];
getAdminMessageChangeCount: () => number;
}
export interface deviceState {
@@ -186,7 +143,6 @@ function deviceFactory(
channels: new Map(),
config: create(Protobuf.LocalOnly.LocalConfigSchema),
moduleConfig: create(Protobuf.LocalOnly.LocalModuleConfigSchema),
changeRegistry: createChangeRegistry(),
hardware: create(Protobuf.Mesh.MyNodeInfoSchema),
metadata: new Map(),
connection: undefined,
@@ -212,7 +168,6 @@ function deviceFactory(
},
pendingSettingsChanges: false,
messageDraft: "",
unreadCounts: new Map(),
clientNotifications: [],
setStatus: (status: Types.DeviceStatusEnum) => {
@@ -369,35 +324,13 @@ function deviceFactory(
return;
}
const device = get().devices.get(id);
if (!device) {
return;
}
const workingValue = device.changeRegistry.changes.get(
serializeKey({ type: "config", variant: payloadVariant }),
)?.value as Protobuf.LocalOnly.LocalConfig[K] | undefined;
return {
...device.config[payloadVariant],
...workingValue,
};
return device?.config[payloadVariant];
},
getEffectiveModuleConfig<K extends ValidModuleConfigType>(
payloadVariant: K,
): Protobuf.LocalOnly.LocalModuleConfig[K] | undefined {
const device = get().devices.get(id);
if (!device) {
return;
}
const workingValue = device.changeRegistry.changes.get(
serializeKey({ type: "moduleConfig", variant: payloadVariant }),
)?.value as Protobuf.LocalOnly.LocalModuleConfig[K] | undefined;
return {
...device.moduleConfig[payloadVariant],
...workingValue,
};
return device?.moduleConfig[payloadVariant];
},
setHardware: (hardware: Protobuf.Mesh.MyNodeInfo) => {
@@ -559,7 +492,7 @@ function deviceFactory(
produce<PrivateDeviceState>((draft) => {
const device = draft.devices.get(id);
if (device) {
device.connection = connection;
device.connection = connection as unknown as Draft<MeshDevice>;
}
}),
);
@@ -619,51 +552,6 @@ function deviceFactory(
}),
);
},
incrementUnread: (nodeNum: number) => {
set(
produce<PrivateDeviceState>((draft) => {
const device = draft.devices.get(id);
if (!device) {
return;
}
const currentCount = device.unreadCounts.get(nodeNum) ?? 0;
device.unreadCounts.set(nodeNum, currentCount + 1);
}),
);
},
getUnreadCount: (nodeNum: number): number => {
const device = get().devices.get(id);
if (!device) {
return 0;
}
return device.unreadCounts.get(nodeNum) ?? 0;
},
getAllUnreadCount: (): number => {
const device = get().devices.get(id);
if (!device) {
return 0;
}
let totalUnread = 0;
device.unreadCounts.forEach((count) => {
totalUnread += count;
});
return totalUnread;
},
resetUnread: (nodeNum: number) => {
set(
produce<PrivateDeviceState>((draft) => {
const device = draft.devices.get(id);
if (!device) {
return;
}
device.unreadCounts.set(nodeNum, 0);
if (device.unreadCounts.get(nodeNum) === 0) {
device.unreadCounts.delete(nodeNum);
}
}),
);
},
sendAdminMessage(message: Protobuf.Admin.AdminMessage) {
const device = get().devices.get(id);
if (!device) {
@@ -727,242 +615,6 @@ function deviceFactory(
}
return device.neighborInfo.get(nodeNum);
},
// New unified change tracking methods
setChange: (key: ConfigChangeKey, value: unknown, originalValue?: unknown) => {
set(
produce<PrivateDeviceState>((draft) => {
const device = draft.devices.get(id);
if (!device) {
return;
}
const keyStr = serializeKey(key);
device.changeRegistry.changes.set(keyStr, {
key,
value,
originalValue,
timestamp: Date.now(),
});
}),
);
},
removeChange: (key: ConfigChangeKey) => {
set(
produce<PrivateDeviceState>((draft) => {
const device = draft.devices.get(id);
if (!device) {
return;
}
device.changeRegistry.changes.delete(serializeKey(key));
}),
);
},
hasChange: (key: ConfigChangeKey) => {
const device = get().devices.get(id);
return device?.changeRegistry.changes.has(serializeKey(key)) ?? false;
},
getChange: (key: ConfigChangeKey) => {
const device = get().devices.get(id);
if (!device) {
return;
}
return device.changeRegistry.changes.get(serializeKey(key))?.value;
},
clearAllChanges: () => {
set(
produce<PrivateDeviceState>((draft) => {
const device = draft.devices.get(id);
if (!device) {
return;
}
device.changeRegistry.changes.clear();
}),
);
},
hasConfigChange: (variant: ValidConfigType) => {
const device = get().devices.get(id);
if (!device) {
return false;
}
return hasConfigChange(device.changeRegistry, variant);
},
hasModuleConfigChange: (variant: ValidModuleConfigType) => {
const device = get().devices.get(id);
if (!device) {
return false;
}
return hasModuleConfigChange(device.changeRegistry, variant);
},
hasChannelChange: (index: Types.ChannelNumber) => {
const device = get().devices.get(id);
if (!device) {
return false;
}
return hasChannelChange(device.changeRegistry, index);
},
hasUserChange: () => {
const device = get().devices.get(id);
if (!device) {
return false;
}
return hasUserChange(device.changeRegistry);
},
getConfigChangeCount: () => {
const device = get().devices.get(id);
if (!device) {
return 0;
}
return getConfigChangeCount(device.changeRegistry);
},
getModuleConfigChangeCount: () => {
const device = get().devices.get(id);
if (!device) {
return 0;
}
return getModuleConfigChangeCount(device.changeRegistry);
},
getChannelChangeCount: () => {
const device = get().devices.get(id);
if (!device) {
return 0;
}
return getChannelChangeCount(device.changeRegistry);
},
getAllConfigChanges: () => {
const device = get().devices.get(id);
if (!device) {
return [];
}
const changes = getAllConfigChanges(device.changeRegistry);
return changes
.map((entry) => {
if (entry.key.type !== "config") {
return null;
}
if (!entry.value) {
return null;
}
return create(Protobuf.Config.ConfigSchema, {
payloadVariant: {
case: entry.key.variant,
value: entry.value,
},
});
})
.filter((c): c is Protobuf.Config.Config => c !== null);
},
getAllModuleConfigChanges: () => {
const device = get().devices.get(id);
if (!device) {
return [];
}
const changes = getAllModuleConfigChanges(device.changeRegistry);
return changes
.map((entry) => {
if (entry.key.type !== "moduleConfig") {
return null;
}
if (!entry.value) {
return null;
}
return create(Protobuf.ModuleConfig.ModuleConfigSchema, {
payloadVariant: {
case: entry.key.variant,
value: entry.value,
},
});
})
.filter((c): c is Protobuf.ModuleConfig.ModuleConfig => c !== null);
},
getAllChannelChanges: () => {
const device = get().devices.get(id);
if (!device) {
return [];
}
const changes = getAllChannelChanges(device.changeRegistry);
return changes
.map((entry) => entry.value as Protobuf.Channel.Channel)
.filter((c): c is Protobuf.Channel.Channel => c !== undefined);
},
queueAdminMessage: (message: Protobuf.Admin.AdminMessage) => {
// Generate a unique ID for this admin message
const messageId = `${Date.now()}-${Math.random().toString(36).substring(7)}`;
// Determine the variant type
const variant =
message.payloadVariant.case === "setFixedPosition" ? "setFixedPosition" : "other";
set(
produce<PrivateDeviceState>((draft) => {
const device = draft.devices.get(id);
if (!device) {
return;
}
const keyStr = serializeKey({
type: "adminMessage",
variant,
id: messageId,
});
device.changeRegistry.changes.set(keyStr, {
key: { type: "adminMessage", variant, id: messageId },
value: message,
timestamp: Date.now(),
});
}),
);
},
getAllQueuedAdminMessages: () => {
const device = get().devices.get(id);
if (!device) {
return [];
}
const changes = getAllAdminMessages(device.changeRegistry);
return changes
.map((entry) => entry.value as Protobuf.Admin.AdminMessage)
.filter((m): m is Protobuf.Admin.AdminMessage => m !== undefined);
},
getAdminMessageChangeCount: () => {
const device = get().devices.get(id);
if (!device) {
return 0;
}
return getAdminMessageChangeCount(device.changeRegistry);
},
};
}
@@ -980,7 +632,7 @@ export const deviceStoreInitializer: StateCreator<PrivateDeviceState> = (set, ge
const device = deviceFactory(id, get, set);
set(
produce<PrivateDeviceState>((draft) => {
draft.devices = new Map(draft.devices).set(id, device);
draft.devices = new Map(draft.devices).set(id, device as unknown as Draft<Device>);
// Enforce retention limit
evictOldestEntries(draft.devices, DEVICESTORE_RETENTION_NUM);
@@ -1101,7 +753,23 @@ const persistOptions: PersistOptions<PrivateDeviceState, DevicePersisted> = {
);
}
}
draft.devices = rebuilt;
draft.devices = rebuilt as unknown as Map<number, Draft<Device>>;
// Stale in-flight states can't survive a reload — no JS code is
// running that could complete them. Reset any persisted
// "connecting" / "configuring" / "disconnecting" entries to
// "disconnected" so the connecting overlay (which keys off
// these statuses) doesn't get stuck visible on cold boot.
for (const conn of draft.savedConnections) {
if (
conn.status === "connecting" ||
conn.status === "configuring" ||
conn.status === "disconnecting"
) {
conn.status = "disconnected";
conn.error = undefined;
}
}
}),
);
},
@@ -1,5 +1,10 @@
import type { Protobuf } from "@meshtastic/core";
import type { ValidConfigType, ValidModuleConfigType } from "./changeRegistry.ts";
import type { Protobuf } from "@meshtastic/sdk";
type ValidConfigType = Exclude<keyof Protobuf.LocalOnly.LocalConfig, "version" | "$typeName">;
type ValidModuleConfigType = Exclude<
keyof Protobuf.LocalOnly.LocalModuleConfig,
"version" | "$typeName"
>;
interface Dialogs {
import: boolean;
+1 -24
View File
@@ -1,8 +1,5 @@
import { useDeviceContext } from "@core/hooks/useDeviceContext.ts";
import { type Device, useDeviceStore } from "@core/stores/deviceStore/index.ts";
import { type MessageStore, useMessageStore } from "@core/stores/messageStore/index.ts";
import { type NodeDB, useNodeDBStore } from "@core/stores/nodeDBStore/index.ts";
import { bindStoreToDevice } from "@core/stores/utils/bindStoreToDevice.ts";
export {
CurrentDeviceContext,
@@ -33,14 +30,7 @@ export type {
ValidModuleConfigType,
WaypointWithMetadata,
} from "@core/stores/deviceStore/types.ts";
export {
MessageState,
type MessageStore,
MessageType,
useMessageStore,
} from "@core/stores/messageStore";
export { type NodeDB, useNodeDBStore } from "@core/stores/nodeDBStore/index.ts";
export type { NodeErrorType } from "@core/stores/nodeDBStore/types.ts";
export { MessageState, MessageType } from "@core/stores/messageStore";
export {
SidebarProvider,
useSidebar, // TODO: Bring hook into this file
@@ -49,22 +39,9 @@ export {
// Re-export idb-keyval functions for clearing all stores, expand this if we add more local storage types
export { clear as clearAllStores } from "idb-keyval";
// Define hooks to access the stores
export const useNodeDB = bindStoreToDevice(
useNodeDBStore,
(s, deviceId): NodeDB => s.getNodeDB(deviceId) ?? s.addNodeDB(deviceId),
);
export const useDevice = (): Device => {
const { deviceId } = useDeviceContext();
const device = useDeviceStore((s) => s.getDevice(deviceId) ?? s.addDevice(deviceId));
return device;
};
export const useMessages = (): MessageStore => {
const { deviceId } = useDeviceContext();
const device = useMessageStore((s) => s.getMessageStore(deviceId) ?? s.addMessageStore(deviceId));
return device;
};
+28 -411
View File
@@ -1,26 +1,11 @@
import { featureFlags } from "@core/services/featureFlags";
import type {
ChannelId,
ClearMessageParams,
ConversationId,
GetMessagesParams,
Message,
MessageId,
MessageLogMap,
NodeNum,
SetMessageStateParams,
} from "@core/stores/messageStore/types.ts";
import { evictOldestEntries } from "@core/stores/utils/evictOldestEntries.ts";
import { createStorage } from "@core/stores/utils/indexDB.ts";
import type { Types } from "@meshtastic/core";
import { produce } from "immer";
import { create as createStore, type StateCreator } from "zustand";
import { type PersistOptions, persist } from "zustand/middleware";
/**
* Legacy enums and message-shape types preserved for components that still
* read from the SDK chat slice via the `useChatAsLegacyMessages` adapter. The Zustand
* messageStore that previously lived here has been retired — chat
* persistence is owned by the SDK ChatClient + SqlocalMessageRepository.
*/
const IDB_KEY_NAME = "meshtastic-message-store";
const CURRENT_STORE_VERSION = 0;
const MESSAGESTORE_RETENTION_NUM = 10;
const MESSAGELOG_RETENTION_NUM = 1000; // Max messages per conversation/channel
import type { Types } from "@meshtastic/sdk";
export enum MessageState {
Ack = "ack",
@@ -33,395 +18,27 @@ export enum MessageType {
Broadcast = "broadcast",
}
export type NodeNum = number;
export type MessageId = number;
export type ChannelId = Types.ChannelNumber;
export type ConversationId = string;
interface MessageBase {
channel: Types.ChannelNumber;
to: number;
from: number;
date: number;
messageId: number;
state: MessageState;
message: string;
}
interface GenericMessage<T extends MessageType> extends MessageBase {
type: T;
}
export type Message = GenericMessage<MessageType.Direct> | GenericMessage<MessageType.Broadcast>;
export function getConversationId(node1: NodeNum, node2: NodeNum): ConversationId {
return [node1, node2].sort((a, b) => a - b).join(":");
}
export interface MessageBuckets {
direct: Map<ConversationId, MessageLogMap>;
broadcast: Map<ChannelId, MessageLogMap>;
}
type MessageStoreData = {
// Persisted data
id: number;
myNodeNum: number | undefined;
messages: MessageBuckets;
drafts: Map<Types.Destination, string>;
};
export interface MessageStore extends MessageStoreData {
// Ephemeral state (not persisted)
activeChat: number;
chatType: MessageType;
setNodeNum: (nodeNum: number) => void;
saveMessage: (message: Message) => void;
setMessageState: (params: SetMessageStateParams) => void;
getMessages: (params: GetMessagesParams) => Message[];
getDraft: (key: Types.Destination) => string;
setDraft: (key: Types.Destination, message: string) => void;
clearDraft: (key: Types.Destination) => void;
//clearAllDrafts: (key: Types.Destination) => void;
deleteAllMessages: () => void;
clearMessageByMessageId: (params: ClearMessageParams) => void;
}
export interface MessageStoreState {
addMessageStore: (id: number) => MessageStore;
removeMessageStore: (id: number) => void;
getMessageStore: (id: number) => MessageStore | undefined;
getMessageStores: () => MessageStore[];
}
interface PrivateMessageStoreState extends MessageStoreState {
messageStores: Map<number, MessageStore>;
}
type MessageStorePersisted = {
messageStores: Map<number, MessageStoreData>;
};
function messageStoreFactory(
id: number,
get: () => PrivateMessageStoreState,
set: typeof useMessageStore.setState,
data?: Partial<MessageStoreData>,
): MessageStore {
const messages = data?.messages ?? {
direct: new Map<ConversationId, MessageLogMap>(),
broadcast: new Map<ChannelId, MessageLogMap>(),
};
const drafts = data?.drafts ?? new Map<Types.Destination, string>();
const myNodeNum = data?.myNodeNum;
const activeChat = 0;
const chatType = MessageType.Broadcast;
return {
id,
myNodeNum,
messages,
drafts,
activeChat,
chatType,
setNodeNum: (nodeNum) => {
set(
produce<PrivateMessageStoreState>((draft) => {
const newStore = draft.messageStores.get(id);
if (!newStore) {
throw new Error(`No MessageStore found for id: ${id}`);
}
newStore.myNodeNum = nodeNum;
for (const [otherId, oldStore] of draft.messageStores) {
if (otherId === id || oldStore.myNodeNum !== nodeNum) {
continue;
}
// Adopt broadcast conversations (reuses inner Map references)
for (const [channelId, logMap] of oldStore.messages.broadcast) {
newStore.messages.broadcast.set(channelId, logMap);
}
// Adopt direct conversations
for (const [conversationId, logMap] of oldStore.messages.direct) {
newStore.messages.direct.set(conversationId, logMap);
}
// Adopt drafts
for (const [destination, draftText] of oldStore.drafts) {
newStore.drafts.set(destination, draftText);
}
// Drop old store
draft.messageStores.delete(otherId);
}
}),
);
},
saveMessage: (message: Message) => {
set(
produce<PrivateMessageStoreState>((draft) => {
const state = draft.messageStores.get(id);
if (!state) {
throw new Error(`No MessageStore found for id: ${id}`);
}
let log: MessageLogMap | undefined;
if (message.type === MessageType.Direct) {
const conversationId = getConversationId(message.from, message.to);
if (!state.messages.direct.has(conversationId)) {
state.messages.direct.set(conversationId, new Map<MessageId, Message>());
}
log = state.messages.direct.get(conversationId);
log?.set(message.messageId, message);
} else if (message.type === MessageType.Broadcast) {
const channelId = message.channel as ChannelId;
if (!state.messages.broadcast.has(channelId)) {
state.messages.broadcast.set(channelId, new Map<MessageId, Message>());
}
log = state.messages.broadcast.get(channelId);
log?.set(message.messageId, message);
}
if (log) {
// Enforce retention limit
evictOldestEntries(log, MESSAGELOG_RETENTION_NUM);
}
}),
);
},
setMessageState: (params: SetMessageStateParams) => {
set(
produce<PrivateMessageStoreState>((draft) => {
const state = draft.messageStores.get(id);
if (!state) {
throw new Error(`No MessageStore found for id: ${id}`);
}
let messageLog: MessageLogMap | undefined;
let targetMessage: Message | undefined;
if (params.type === MessageType.Direct) {
const conversationId = getConversationId(params.nodeA, params.nodeB);
messageLog = state.messages.direct.get(conversationId);
if (messageLog) {
targetMessage = messageLog.get(params.messageId);
}
} else {
// Broadcast
messageLog = state.messages.broadcast.get(params.channelId);
if (messageLog) {
targetMessage = messageLog.get(params.messageId);
}
}
if (targetMessage) {
targetMessage.state = params.newState ?? MessageState.Ack;
} else {
console.warn(
`Message or conversation/channel not found for state update. Params: ${JSON.stringify(
params,
)}`,
);
}
}),
);
},
getMessages: (params: GetMessagesParams): Message[] => {
const state = get().messageStores.get(id);
if (!state) {
throw new Error(`No MessageStore found for id: ${id}`);
}
let messageMap: MessageLogMap | undefined;
if (params.type === MessageType.Direct) {
const conversationId = getConversationId(params.nodeA, params.nodeB);
messageMap = state.messages.direct.get(conversationId);
} else {
messageMap = state.messages.broadcast.get(params.channelId);
}
if (messageMap === undefined) {
return [];
}
const messagesArray = Array.from(messageMap.values());
messagesArray.sort((a, b) => a.date - b.date);
return messagesArray;
},
getDraft: (key) => {
const state = get().messageStores.get(id);
if (!state) {
throw new Error(`No MessageStore found for id: ${id}`);
}
return state.drafts.get(key) ?? "";
},
setDraft: (key, message) => {
set(
produce<PrivateMessageStoreState>((draft) => {
const state = draft.messageStores.get(id);
if (!state) {
throw new Error(`No MessageStore found for id: ${id}`);
}
state.drafts.set(key, message);
}),
);
},
clearDraft: (key) => {
set(
produce<PrivateMessageStoreState>((draft) => {
const state = draft.messageStores.get(id);
if (!state) {
throw new Error(`No MessageStore found for id: ${id}`);
}
state.drafts.delete(key);
}),
);
},
deleteAllMessages: () => {
set(
produce<PrivateMessageStoreState>((draft) => {
const state = draft.messageStores.get(id);
if (!state) {
throw new Error(`No MessageStore found for id: ${id}`);
}
state.messages.direct = new Map<ConversationId, MessageLogMap>();
state.messages.broadcast = new Map<ChannelId, MessageLogMap>();
}),
);
},
clearMessageByMessageId: (params: ClearMessageParams) => {
set(
produce<PrivateMessageStoreState>((draft) => {
const state = draft.messageStores.get(id);
if (!state) {
throw new Error(`No MessageStore found for id: ${id}`);
}
let messageLog: MessageLogMap | undefined;
let parentMap: Map<ConversationId | ChannelId, MessageLogMap>;
let parentKey: ConversationId | ChannelId;
if (params.type === MessageType.Direct) {
parentKey = getConversationId(params.nodeA, params.nodeB);
parentMap = state.messages.direct;
messageLog = parentMap.get(parentKey);
} else {
// Broadcast
parentKey = params.channelId;
parentMap = state.messages.broadcast;
messageLog = parentMap.get(parentKey);
}
if (messageLog) {
const deleted = messageLog.delete(params.messageId);
if (deleted) {
console.log(
`Deleted message ${params.messageId} from ${params.type} message ${parentKey}`,
);
// Clean up empty MessageLogMap and its entry in the parent map
if (messageLog.size === 0) {
parentMap.delete(parentKey);
console.log(`Cleaned up empty message entry for ${parentKey}`);
}
} else {
console.warn(
`Message ${params.messageId} not found in ${params.type} chat ${parentKey} for deletion.`,
);
}
} else {
console.warn(`Message entry ${parentKey} not found for message deletion.`);
}
}),
);
},
};
}
export const messageStoreInitializer: StateCreator<PrivateMessageStoreState> = (set, get) => ({
messageStores: new Map(),
addMessageStore: (id) => {
const existing = get().messageStores.get(id);
if (existing) {
return existing;
}
const nodeStore = messageStoreFactory(id, get, set);
set(
produce<PrivateMessageStoreState>((draft) => {
draft.messageStores.set(id, nodeStore);
// Enforce retention limit
evictOldestEntries(draft.messageStores, MESSAGESTORE_RETENTION_NUM);
}),
);
return nodeStore;
},
removeMessageStore: (id) => {
set(
produce<PrivateMessageStoreState>((draft) => {
draft.messageStores.delete(id);
}),
);
},
getMessageStores: () => Array.from(get().messageStores.values()),
getMessageStore: (id) => get().messageStores.get(id),
});
const persistOptions: PersistOptions<PrivateMessageStoreState, MessageStorePersisted> = {
name: IDB_KEY_NAME,
storage: createStorage<MessageStorePersisted>(),
version: CURRENT_STORE_VERSION,
partialize: (s): MessageStorePersisted => ({
messageStores: new Map(
Array.from(s.messageStores.entries()).map(([id, db]) => [
id,
{
id: db.id,
myNodeNum: db.myNodeNum,
messages: db.messages,
drafts: db.drafts,
},
]),
),
}),
onRehydrateStorage: () => (state) => {
if (!state) {
return;
}
console.debug(
"MessageStoreStore: Rehydrating state with ",
state.messageStores.size,
" MessageStores -",
state.messageStores,
);
useMessageStore.setState(
produce<PrivateMessageStoreState>((draft) => {
const rebuilt = new Map<number, MessageStore>();
for (const [id, data] of (
draft.messageStores as unknown as Map<number, MessageStoreData>
).entries()) {
if (data.myNodeNum !== undefined) {
// Only rebuild if there is a nodenum set otherwise orphan dbs will acumulate
rebuilt.set(
id,
messageStoreFactory(id, useMessageStore.getState, useMessageStore.setState, data),
);
}
}
draft.messageStores = rebuilt;
}),
);
},
};
// Add persist middleware on the store if the feature flag is enabled
const persistMessages = featureFlags.get("persistMessages");
console.debug(`MessageStore: Persisting messages is ${persistMessages ? "enabled" : "disabled"}`);
export const useMessageStore = persistMessages
? createStore<PrivateMessageStoreState, [["zustand/persist", MessageStorePersisted]]>(
persist(messageStoreInitializer, persistOptions),
)
: createStore<PrivateMessageStoreState>()(messageStoreInitializer);
@@ -1,727 +0,0 @@
/** biome-ignore-all lint/style/noNonNullAssertion: <tests> */
import { Types } from "@meshtastic/core";
import { setAutoFreeze } from "immer";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getConversationId, MessageState, MessageType } from "./index.ts";
import type { ChannelId, Message } from "./types.ts";
const idbMem = new Map<string, string>();
vi.mock("idb-keyval", () => ({
get: vi.fn((key: string) => Promise.resolve(idbMem.get(key))),
set: vi.fn((key: string, val: string) => {
idbMem.set(key, val);
return Promise.resolve();
}),
del: vi.fn((k: string) => {
idbMem.delete(k);
return Promise.resolve();
}),
}));
async function freshStore(persist = false) {
vi.resetModules();
// suppress console output from the store during tests (for github actions)
vi.spyOn(console, "debug").mockImplementation(() => {});
vi.spyOn(console, "log").mockImplementation(() => {});
vi.spyOn(console, "info").mockImplementation(() => {});
// Mock feature flag for persistence
vi.doMock("@core/services/featureFlags", () => ({
featureFlags: {
get: vi.fn((key: string) => (key === "persistMessages" ? persist : false)),
},
}));
const mod = await import("./index.ts");
return mod;
}
const myNodeNum = 111;
const otherNodeNum1 = 222;
const otherNodeNum2 = 333;
const broadcastChannel: ChannelId = 0;
const directMessageToOther1: Message = {
type: MessageType.Direct,
from: myNodeNum,
to: otherNodeNum1,
channel: 0,
date: Date.now(),
messageId: 101,
state: MessageState.Waiting,
message: "Hello other 1 from me",
};
const directMessageFromOther1: Message = {
type: MessageType.Direct,
from: otherNodeNum1,
to: myNodeNum,
channel: 0,
date: Date.now() + 1000,
messageId: 102,
state: MessageState.Waiting,
message: "Hello me from other 1",
};
const directMessageToOther2: Message = {
type: MessageType.Direct,
from: myNodeNum,
to: otherNodeNum2,
channel: 0,
date: Date.now() + 2000,
messageId: 103,
state: MessageState.Waiting,
message: "Hello other 2 from me",
};
const broadcastMessage1: Message = {
type: MessageType.Broadcast,
from: otherNodeNum1,
to: 0xffffffff,
channel: broadcastChannel,
date: Date.now() + 3000,
messageId: 201,
state: MessageState.Waiting,
message: "Broadcast message 1",
};
const broadcastMessage2: Message = {
type: MessageType.Broadcast,
from: myNodeNum,
to: 0xffffffff,
channel: broadcastChannel,
date: Date.now() + 4000,
messageId: 202,
state: MessageState.Waiting,
message: "Broadcast message 2",
};
describe("MessageStore persistence & rehydrate", () => {
beforeEach(() => {
idbMem.clear();
vi.clearAllMocks();
});
it("should have correct initial state", async () => {
const { useMessageStore } = await freshStore();
const state = useMessageStore.getState();
const store = state.addMessageStore(123);
expect(store.messages.direct).toBeInstanceOf(Map);
expect(store.messages.direct.size).toBe(0);
expect(store.messages.broadcast).toBeInstanceOf(Map);
expect(store.messages.broadcast.size).toBe(0);
expect(store.drafts).toBeInstanceOf(Map);
expect(store.drafts.size).toBe(0);
expect(store.myNodeNum).toBe(undefined);
expect(store.activeChat).toBe(0);
expect(store.chatType).toBe(MessageType.Broadcast);
});
it("should set nodeNum", async () => {
const { useMessageStore } = await freshStore();
const state = useMessageStore.getState();
const db = state.addMessageStore(123);
db.setNodeNum(myNodeNum);
expect(useMessageStore.getState().getMessageStore(123)?.myNodeNum).toBe(myNodeNum);
});
describe("saveMessage", async () => {
const { useMessageStore } = await freshStore();
const state = useMessageStore.getState();
state.addMessageStore(123);
it("should save a direct message with correct Map structure", () => {
state.getMessageStore(123)?.saveMessage(directMessageToOther1);
const conversationId = getConversationId(
directMessageToOther1.from,
directMessageToOther1.to,
);
const store = state.getMessageStore(123)!;
// Check if the conversation Map exists
expect(store.messages.direct.has(conversationId)).toBe(true);
const conversationLog = store.messages.direct.get(conversationId);
// Check if the inner Map (MessageLogMap) exists and is a Map
expect(conversationLog).toBeInstanceOf(Map);
// Check if the message exists within the inner Map
expect(conversationLog?.has(directMessageToOther1.messageId)).toBe(true);
// Check the message content
expect(conversationLog?.get(directMessageToOther1.messageId)).toEqual(directMessageToOther1);
});
it("should save a broadcast message with correct Map structure", () => {
state.getMessageStore(123)?.saveMessage(broadcastMessage1);
const store = state.getMessageStore(123)!;
const channelId = broadcastMessage1.channel;
expect(store.messages.broadcast.has(channelId)).toBe(true);
const channelLog = store.messages.broadcast.get(channelId);
expect(channelLog).toBeInstanceOf(Map);
expect(channelLog?.has(broadcastMessage1.messageId)).toBe(true);
expect(channelLog?.get(broadcastMessage1.messageId)).toEqual(broadcastMessage1);
});
it("should save multiple messages correctly", () => {
state.getMessageStore(123)?.saveMessage(directMessageToOther1);
state.getMessageStore(123)?.saveMessage(directMessageFromOther1);
state.getMessageStore(123)?.saveMessage(broadcastMessage1);
const store = state.getMessageStore(123)!;
const convId1 = getConversationId(myNodeNum, otherNodeNum1);
expect(store.messages.direct.get(convId1)?.get(directMessageToOther1.messageId)).toEqual(
directMessageToOther1,
);
expect(store.messages.direct.get(convId1)?.get(directMessageFromOther1.messageId)).toEqual(
directMessageFromOther1,
);
const channelId = broadcastMessage1.channel;
expect(store.messages.broadcast.get(channelId)?.get(broadcastMessage1.messageId)).toEqual(
broadcastMessage1,
);
});
});
describe("getMessages", async () => {
const { useMessageStore } = await freshStore();
const state = useMessageStore.getState();
state.addMessageStore(123);
beforeEach(() => {
state.getMessageStore(123)?.setNodeNum(myNodeNum);
state.getMessageStore(123)?.saveMessage(directMessageToOther1);
state.getMessageStore(123)?.saveMessage(directMessageFromOther1);
state.getMessageStore(123)?.saveMessage(directMessageToOther2);
state.getMessageStore(123)?.saveMessage(broadcastMessage1);
state.getMessageStore(123)?.saveMessage(broadcastMessage2);
});
it("should return broadcast messages for a channel, sorted by date", () => {
const messages = state.getMessageStore(123)!.getMessages({
type: MessageType.Broadcast,
channelId: broadcastChannel,
});
expect(messages).toHaveLength(2);
expect(messages[0]).toEqual(broadcastMessage1);
expect(messages[1]).toEqual(broadcastMessage2);
});
it("should return empty array for broadcast if channel has no messages", () => {
const messages = state.getMessageStore(123)!.getMessages({
type: MessageType.Broadcast,
channelId: Types.ChannelNumber.Channel1,
});
expect(messages).toEqual([]);
});
it("should return combined direct messages for a specific chat pair, sorted by date", () => {
const messages = state.getMessageStore(123)!.getMessages({
type: MessageType.Direct,
nodeA: myNodeNum,
nodeB: otherNodeNum1,
});
expect(messages).toHaveLength(2);
expect(messages[0]).toEqual(directMessageToOther1);
expect(messages[1]).toEqual(directMessageFromOther1);
});
it("should return only relevant direct messages for a different chat pair", () => {
const messages = state.getMessageStore(123)!.getMessages({
type: MessageType.Direct,
nodeA: myNodeNum,
nodeB: otherNodeNum2,
});
expect(messages).toHaveLength(1);
expect(messages[0]).toEqual(directMessageToOther2);
});
it("should return empty array for direct chat if no messages exist", () => {
const messages = state.getMessageStore(123)!.getMessages({
type: MessageType.Direct,
nodeA: myNodeNum,
nodeB: 999,
});
expect(messages).toEqual([]);
});
});
describe("setMessageState", async () => {
const { useMessageStore } = await freshStore();
const state = useMessageStore.getState();
state.addMessageStore(123);
beforeEach(() => {
state.getMessageStore(123)?.setNodeNum(myNodeNum);
state.getMessageStore(123)?.saveMessage(directMessageToOther1);
state.getMessageStore(123)?.saveMessage(directMessageFromOther1);
state.getMessageStore(123)?.saveMessage(broadcastMessage1);
});
it("should update state for a direct message", () => {
state.getMessageStore(123)!.setMessageState({
type: MessageType.Direct,
nodeA: directMessageToOther1.from,
nodeB: directMessageToOther1.to,
messageId: directMessageToOther1.messageId,
newState: MessageState.Ack,
});
const conversationId = getConversationId(
directMessageToOther1.from,
directMessageToOther1.to,
);
const message = useMessageStore
.getState()
.getMessageStore(123)!
.messages.direct.get(conversationId)
?.get(directMessageToOther1.messageId);
expect(message?.state).toBe(MessageState.Ack);
});
it("should update state for another direct message in the same conversation", () => {
state.getMessageStore(123)!.setMessageState({
type: MessageType.Direct,
nodeA: directMessageFromOther1.from,
nodeB: directMessageFromOther1.to,
messageId: directMessageFromOther1.messageId,
newState: MessageState.Failed,
});
const conversationId = getConversationId(
directMessageFromOther1.from,
directMessageFromOther1.to,
);
const message = useMessageStore
.getState()
.getMessageStore(123)!
.messages.direct.get(conversationId)
?.get(directMessageFromOther1.messageId);
expect(message?.state).toBe(MessageState.Failed);
});
it("should update state for a broadcast message", () => {
state.getMessageStore(123)!.setMessageState({
type: MessageType.Broadcast,
channelId: broadcastChannel,
messageId: broadcastMessage1.messageId,
newState: MessageState.Ack,
});
const message = useMessageStore
.getState()
.getMessageStore(123)!
.messages.broadcast.get(broadcastChannel)
?.get(broadcastMessage1.messageId);
expect(message?.state).toBe(MessageState.Ack);
});
it("should warn if message is not found (direct)", () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
state.getMessageStore(123)!.setMessageState({
type: MessageType.Direct,
nodeA: myNodeNum,
nodeB: otherNodeNum1,
messageId: 999,
newState: MessageState.Ack,
});
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining("Message or conversation/channel not found for state update"),
);
warnSpy.mockRestore();
});
it("should warn if message is not found (broadcast)", () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
state.getMessageStore(123)!.setMessageState({
type: MessageType.Broadcast,
channelId: broadcastChannel,
messageId: 999,
newState: MessageState.Ack,
});
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining("Message or conversation/channel not found for state update"),
);
warnSpy.mockRestore();
});
it("should warn if conversation/channel is not found", () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
state.getMessageStore(123)!.setMessageState({
type: MessageType.Direct,
nodeA: myNodeNum,
nodeB: 998,
messageId: 101,
newState: MessageState.Ack,
});
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining("Message or conversation/channel not found for state update"),
);
warnSpy.mockRestore();
});
});
describe("clearMessageByMessageId", async () => {
const { useMessageStore } = await freshStore();
const state = useMessageStore.getState();
state.addMessageStore(123);
const extraDirectMessageId = 1011;
beforeEach(() => {
state.getMessageStore(123)?.setNodeNum(myNodeNum);
state.getMessageStore(123)?.saveMessage(directMessageToOther1);
state.getMessageStore(123)?.saveMessage(directMessageFromOther1);
state.getMessageStore(123)?.saveMessage(broadcastMessage1);
state.getMessageStore(123)?.saveMessage({
...directMessageToOther1,
messageId: extraDirectMessageId,
date: Date.now() + 50,
});
});
it("should delete a specific direct message", () => {
const messageIdToDelete = directMessageToOther1.messageId;
const nodeA = directMessageToOther1.from;
const nodeB = directMessageToOther1.to;
const conversationId = getConversationId(nodeA, nodeB);
state.getMessageStore(123)?.clearMessageByMessageId({
type: MessageType.Direct,
nodeA: nodeA,
nodeB: nodeB,
messageId: messageIdToDelete,
});
const store = useMessageStore.getState().getMessageStore(123)!;
const conversationLog = store.messages.direct.get(conversationId);
expect(conversationLog?.has(messageIdToDelete)).toBe(false);
expect(conversationLog?.has(extraDirectMessageId)).toBe(true);
expect(conversationLog?.has(directMessageFromOther1.messageId)).toBe(true);
expect(store.messages.direct.has(conversationId)).toBe(true);
});
it("should delete another specific direct message", () => {
const messageIdToDelete = directMessageFromOther1.messageId;
const nodeA = directMessageFromOther1.from;
const nodeB = directMessageFromOther1.to;
const conversationId = getConversationId(nodeA, nodeB);
state.getMessageStore(123)?.clearMessageByMessageId({
type: MessageType.Direct,
nodeA: nodeA,
nodeB: nodeB,
messageId: messageIdToDelete,
});
const store = useMessageStore.getState().getMessageStore(123)!;
const conversationLog = store.messages.direct.get(conversationId);
expect(conversationLog?.has(messageIdToDelete)).toBe(false);
expect(conversationLog?.has(directMessageToOther1.messageId)).toBe(true);
expect(conversationLog?.has(extraDirectMessageId)).toBe(true);
});
it("should delete a specific broadcast message", () => {
const messageIdToDelete = broadcastMessage1.messageId;
const channelId = broadcastMessage1.channel;
state.getMessageStore(123)?.clearMessageByMessageId({
type: MessageType.Broadcast,
channelId: channelId,
messageId: messageIdToDelete,
});
const store = useMessageStore.getState().getMessageStore(123)!;
expect(store.messages.broadcast.get(channelId)?.get(messageIdToDelete)).toBeUndefined();
});
it("should clean up empty conversation/channel Maps", () => {
const directConvId = getConversationId(
directMessageFromOther1.from,
directMessageFromOther1.to,
);
const broadcastChanId = broadcastMessage1.channel;
state.getMessageStore(123)?.clearMessageByMessageId({
type: MessageType.Direct,
nodeA: directMessageToOther1.from,
nodeB: directMessageToOther1.to,
messageId: directMessageToOther1.messageId,
});
state.getMessageStore(123)?.clearMessageByMessageId({
type: MessageType.Direct,
nodeA: directMessageFromOther1.from,
nodeB: directMessageFromOther1.to,
messageId: directMessageFromOther1.messageId,
});
state.getMessageStore(123)?.clearMessageByMessageId({
type: MessageType.Direct,
nodeA: directMessageToOther1.from,
nodeB: directMessageToOther1.to,
messageId: extraDirectMessageId,
});
expect(state.getMessageStore(123)?.messages.direct.has(directConvId)).toBe(false);
state.getMessageStore(123)?.clearMessageByMessageId({
type: MessageType.Broadcast,
channelId: broadcastChanId,
messageId: broadcastMessage1.messageId,
});
expect(state.getMessageStore(123)?.messages.broadcast.has(broadcastChanId)).toBe(false);
});
it("should not error when trying to delete non-existent message", () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const conversationId = getConversationId(myNodeNum, otherNodeNum1);
expect(() => {
state.getMessageStore(123)?.clearMessageByMessageId({
type: MessageType.Direct,
nodeA: myNodeNum,
nodeB: otherNodeNum1,
messageId: 9999,
});
}).not.toThrow();
const store = useMessageStore.getState().getMessageStore(123)!;
const conversationLog = store.messages.direct.get(conversationId);
expect(conversationLog?.size).toBe(3); // 101, 102, 1011
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("not found in direct chat"));
warnSpy.mockRestore();
});
it("should not error when trying to delete from non-existent conversation/channel", () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
expect(() => {
state.getMessageStore(123)?.clearMessageByMessageId({
type: MessageType.Direct,
nodeA: myNodeNum,
nodeB: 9998,
messageId: 101,
});
}).not.toThrow();
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("Message entry"));
expect(warnSpy).toHaveBeenCalledTimes(1);
warnSpy.mockRestore();
});
});
describe("Drafts", async () => {
const { useMessageStore } = await freshStore();
const state = useMessageStore.getState();
state.addMessageStore(123);
const draftKeyDirect = otherNodeNum1;
const draftKeyBroadcast = broadcastChannel;
const draftMessage = "This is a draft";
it("should set and get a draft for direct chat", () => {
state.getMessageStore(123)?.setDraft(draftKeyDirect, draftMessage);
expect(state.getMessageStore(123)?.drafts.get(draftKeyDirect)).toBe(draftMessage);
expect(state.getMessageStore(123)?.getDraft(draftKeyDirect)).toBe(draftMessage);
});
it("should set and get a draft for broadcast chat", () => {
state.getMessageStore(123)?.setDraft(draftKeyBroadcast, draftMessage);
expect(state.getMessageStore(123)?.drafts.get(draftKeyBroadcast)).toBe(draftMessage);
expect(state.getMessageStore(123)?.getDraft(draftKeyBroadcast)).toBe(draftMessage);
});
it("should return empty string for non-existent draft", () => {
expect(state.getMessageStore(123)?.getDraft(999)).toBe("");
});
it("should clear a draft", () => {
state.getMessageStore(123)?.setDraft(draftKeyDirect, draftMessage);
expect(state.getMessageStore(123)?.drafts.has(draftKeyDirect)).toBe(true);
state.getMessageStore(123)?.clearDraft(draftKeyDirect);
expect(state.getMessageStore(123)?.drafts.has(draftKeyDirect)).toBe(false);
expect(state.getMessageStore(123)?.getDraft(draftKeyDirect)).toBe("");
});
});
describe("deleteAllMessages", async () => {
const { useMessageStore } = await freshStore();
const state = useMessageStore.getState();
state.addMessageStore(123);
it("should clear all direct and broadcast messages, leaving empty Maps", () => {
state.getMessageStore(123)?.saveMessage(directMessageToOther1);
state.getMessageStore(123)?.saveMessage(broadcastMessage1);
expect(state.getMessageStore(123)?.messages.direct.size).toBeGreaterThan(0);
expect(state.getMessageStore(123)?.messages.broadcast.size).toBeGreaterThan(0);
state.getMessageStore(123)?.deleteAllMessages();
const store = useMessageStore.getState().getMessageStore(123)!;
expect(store.messages.direct).toBeInstanceOf(Map);
expect(store.messages.direct.size).toBe(0);
expect(store.messages.broadcast).toBeInstanceOf(Map);
expect(store.messages.broadcast.size).toBe(0);
});
});
describe("persistence", () => {
it("partialize persists data; onRehydrateStorage rebuilds methods (messages + drafts survive)", async () => {
{
const { useMessageStore } = await freshStore(true);
const state = useMessageStore.getState();
const store = state.addMessageStore(123);
store.setNodeNum(321);
const convId = getConversationId(myNodeNum, otherNodeNum1);
store.saveMessage(directMessageToOther1);
store.saveMessage(broadcastMessage1);
store.setDraft(otherNodeNum1 as unknown as Types.Destination, "draft-text");
const store2 = state.addMessageStore(123);
expect(store2.messages.direct.has(convId)).toBe(true);
expect(store2.messages.direct.get(convId)?.has(101)).toBe(true);
expect(store2.messages.broadcast.get(broadcastChannel)?.has(201)).toBe(true);
expect(store2.getDraft(otherNodeNum1 as unknown as Types.Destination)).toBe("draft-text");
}
{
const { useMessageStore } = await freshStore(true);
const state = useMessageStore.getState();
const store = state.getMessageStore(123)!; // rebuilt instance
expect(store).toBeTruthy();
// Methods should work after rehydrate
const directMsgs = store.getMessages({
type: MessageType.Direct,
nodeA: myNodeNum,
nodeB: otherNodeNum1,
});
expect(directMsgs.map((m) => m.messageId)).toEqual([101]);
const bMsgs = store.getMessages({
type: MessageType.Broadcast,
channelId: broadcastChannel,
});
expect(bMsgs.map((m) => m.messageId)).toEqual([201]);
expect(store.getDraft(otherNodeNum1 as unknown as Types.Destination)).toBe("draft-text");
store.saveMessage(directMessageFromOther1);
const after = store.getMessages({
type: MessageType.Direct,
nodeA: myNodeNum,
nodeB: otherNodeNum1,
});
expect(after.map((m) => m.messageId)).toEqual([101, 102]);
expect(after[1]?.state).toBe(MessageState.Waiting);
}
});
it("removeMessageStore persists removal across reload", async () => {
{
const { useMessageStore } = await freshStore(true);
const state = useMessageStore.getState();
const store = state.addMessageStore(99);
store.setNodeNum(42);
expect(state.getMessageStore(99)).toBeDefined();
state.removeMessageStore(99);
expect(state.getMessageStore(99)).toBeUndefined();
}
{
const { useMessageStore } = await freshStore(true);
const state = useMessageStore.getState();
expect(state.getMessageStore(99)).toBeUndefined(); // still gone
}
});
it("rehydrate only rebuilds stores with myNodeNum set (orphans dropped)", async () => {
{
const { useMessageStore } = await freshStore(true);
const state = useMessageStore.getState();
// Orphan (no myNodeNum)
const orphan = state.addMessageStore(500);
orphan.saveMessage(broadcastMessage1);
// Proper store
const good = state.addMessageStore(501);
good.setNodeNum(777);
good.saveMessage(broadcastMessage2);
}
{
const { useMessageStore } = await freshStore(true);
const state = useMessageStore.getState();
expect(state.getMessageStore(500)).toBeUndefined(); // orphan dropped
const kept = state.getMessageStore(501);
expect(kept).toBeDefined();
expect(kept?.messages.broadcast.get(broadcastChannel)?.has(202)).toBe(true);
}
});
it("evicts the earliest-added message store when exceeding cap of 10", async () => {
const { useMessageStore } = await freshStore();
const state = useMessageStore.getState();
for (let i = 1; i <= 10; i++) {
state.addMessageStore(i);
}
// Adding the 11th should evict the earliest (id=1)
state.addMessageStore(11);
expect(state.getMessageStore(1)).toBeUndefined(); // evicted
expect(state.getMessageStore(2)).toBeDefined(); // still there
expect(state.getMessageStore(11)).toBeDefined(); // newest kept
});
it("keeps only the latest 1000 messages in a broadcast channel (oldest trimmed)", async () => {
setAutoFreeze(false); // Disable immer auto-freeze for performance in this test
try {
const { useMessageStore, MessageType, MessageState } = await freshStore();
const state = useMessageStore.getState();
const store = state.addMessageStore(123);
const channelId = 0 as number;
const total = 1005;
for (let i = 1; i <= total; i++) {
store.saveMessage({
type: MessageType.Broadcast,
from: 123,
to: 0xffffffff,
channel: channelId,
date: Date.now() + i,
messageId: i,
state: MessageState.Waiting,
message: `m${i}`,
});
}
const fresh = useMessageStore.getState().getMessageStore(123)!;
const log = fresh.messages.broadcast.get(channelId)!;
expect(log.size).toBe(1000); // capped
for (let i = 1; i <= 5; i++) {
expect(log.has(i)).toBe(false); // oldest removed
}
for (let i = 6; i <= 1005; i++) {
expect(log.has(i)).toBe(true); // newest kept
}
} finally {
setAutoFreeze(true); // Restore immer auto-freeze
}
});
});
});
@@ -1,5 +1,5 @@
import type { MessageState, MessageType } from "@core/stores";
import type { Types } from "@meshtastic/core";
import type { Types } from "@meshtastic/sdk";
type NodeNum = number;
type MessageId = number;
@@ -1,589 +0,0 @@
import { create } from "@bufbuild/protobuf";
import { featureFlags } from "@core/services/featureFlags";
import { validateIncomingNode } from "@core/stores/nodeDBStore/nodeValidation";
import { createStorage } from "@core/stores/utils/indexDB.ts";
import { Protobuf, type Types } from "@meshtastic/core";
import { produce } from "immer";
import { create as createStore, type StateCreator } from "zustand";
import { type PersistOptions, persist, subscribeWithSelector } from "zustand/middleware";
import type { NodeError, NodeErrorType, ProcessPacketParams } from "./types.ts";
const IDB_KEY_NAME = "meshtastic-nodedb-store";
const CURRENT_STORE_VERSION = 0;
const NODE_RETENTION_DAYS = 14; // Remove nodes not heard from in 14 days
type NodeDBData = {
// Persisted data
id: number;
myNodeNum: number | undefined;
nodeMap: Map<number, Protobuf.Mesh.NodeInfo>;
nodeErrors: Map<number, NodeError>;
};
export interface NodeDB extends NodeDBData {
// Ephemeral state (not persisted)
addNode: (nodeInfo: Protobuf.Mesh.NodeInfo) => void;
removeNode: (nodeNum: number) => void;
removeAllNodes: (keepMyNode?: boolean) => void;
pruneStaleNodes: () => number;
processPacket: (data: ProcessPacketParams) => void;
addUser: (user: Types.PacketMetadata<Protobuf.Mesh.User>) => void;
addPosition: (position: Types.PacketMetadata<Protobuf.Mesh.Position>) => void;
addDeviceMetrics: (metrics: Types.PacketMetadata<Protobuf.Telemetry.DeviceMetrics>) => void;
updateFavorite: (nodeNum: number, isFavorite: boolean) => void;
updateIgnore: (nodeNum: number, isIgnored: boolean) => void;
setNodeNum: (nodeNum: number) => void;
setNodeError: (nodeNum: number, error: NodeErrorType) => void;
clearNodeError: (nodeNum: number) => void;
removeAllNodeErrors: () => void;
getNodesLength: () => number;
getNode: (nodeNum: number) => Protobuf.Mesh.NodeInfo | undefined;
getNodes: (
filter?: (node: Protobuf.Mesh.NodeInfo) => boolean,
includeSelf?: boolean,
) => Protobuf.Mesh.NodeInfo[];
getMyNode: () => Protobuf.Mesh.NodeInfo | undefined;
getNodeError: (nodeNum: number) => NodeError | undefined;
hasNodeError: (nodeNum: number) => boolean;
}
export interface nodeDBState {
addNodeDB: (id: number) => NodeDB;
removeNodeDB: (id: number) => void;
getNodeDBs: () => NodeDB[];
getNodeDB: (id: number) => NodeDB | undefined;
}
interface PrivateNodeDBState extends nodeDBState {
nodeDBs: Map<number, NodeDB>;
}
type NodeDBPersisted = {
nodeDBs: Map<number, NodeDBData>;
};
function nodeDBFactory(
id: number,
get: () => PrivateNodeDBState,
set: typeof useNodeDBStore.setState,
data?: Partial<NodeDBData>,
): NodeDB {
const nodeMap = data?.nodeMap ?? new Map<number, Protobuf.Mesh.NodeInfo>();
const nodeErrors = data?.nodeErrors ?? new Map<number, NodeError>();
const myNodeNum = data?.myNodeNum;
return {
id,
myNodeNum,
nodeMap,
nodeErrors,
addNode: (node) =>
set(
produce<PrivateNodeDBState>((draft) => {
const nodeDB = draft.nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
// Check if node already exists
const existing = nodeDB.nodeMap.get(node.num);
const isNew = !existing;
// Use validation to check the new node before adding
const next = validateIncomingNode(
node,
(nodeNum: number, err: NodeErrorType) => {
nodeDB.setNodeError(nodeNum, err);
},
(filter?: (node: Protobuf.Mesh.NodeInfo) => boolean) => nodeDB.getNodes(filter, true),
);
if (!next) {
// Validation failed and error has been set inside validateIncomingNode
return;
}
// Merge with existing node data if it exists
const merged = existing
? {
...existing,
...next,
// Preserve existing fields if new node doesn't have them
user: next.user ?? existing.user,
position: next.position ?? existing.position,
deviceMetrics: next.deviceMetrics ?? existing.deviceMetrics,
}
: next;
// Use the validated node's num to ensure consistency
nodeDB.nodeMap = new Map(nodeDB.nodeMap).set(merged.num, merged);
if (isNew) {
console.log(
`[NodeDB] Adding new node from NodeInfo packet: ${merged.num} (${merged.user?.longName || "unknown"})`,
);
} else {
console.log(
`[NodeDB] Updating existing node from NodeInfo packet: ${merged.num} (${merged.user?.longName || "unknown"})`,
);
}
}),
),
removeNode: (nodeNum) =>
set(
produce<PrivateNodeDBState>((draft) => {
const nodeDB = draft.nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
const updated = new Map(nodeDB.nodeMap);
updated.delete(nodeNum);
nodeDB.nodeMap = updated;
}),
),
removeAllNodes: (keepMyNode) =>
set(
produce<PrivateNodeDBState>((draft) => {
const nodeDB = draft.nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
const newNodeMap = new Map<number, Protobuf.Mesh.NodeInfo>();
if (
keepMyNode &&
nodeDB.myNodeNum !== undefined &&
nodeDB.nodeMap.has(nodeDB.myNodeNum)
) {
newNodeMap.set(
nodeDB.myNodeNum,
nodeDB.nodeMap.get(nodeDB.myNodeNum) ?? create(Protobuf.Mesh.NodeInfoSchema),
);
}
nodeDB.nodeMap = newNodeMap;
}),
),
pruneStaleNodes: () => {
const nodeDB = get().nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
const nowSec = Math.floor(Date.now() / 1000);
const cutoffSec = nowSec - NODE_RETENTION_DAYS * 24 * 60 * 60;
let prunedCount = 0;
set(
produce<PrivateNodeDBState>((draft) => {
const nodeDB = draft.nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
const newNodeMap = new Map<number, Protobuf.Mesh.NodeInfo>();
for (const [nodeNum, node] of nodeDB.nodeMap) {
// Keep myNode regardless of lastHeard
// Keep nodes that have been heard recently
// Keep nodes without lastHeard (just in case)
if (nodeNum === nodeDB.myNodeNum || !node.lastHeard || node.lastHeard >= cutoffSec) {
newNodeMap.set(nodeNum, node);
} else {
prunedCount++;
console.log(
`[NodeDB] Pruning stale node ${nodeNum} (last heard ${Math.floor((nowSec - node.lastHeard) / 86400)} days ago)`,
);
}
}
nodeDB.nodeMap = newNodeMap;
}),
);
if (prunedCount > 0) {
console.log(
`[NodeDB] Pruned ${prunedCount} stale node(s) older than ${NODE_RETENTION_DAYS} days`,
);
}
return prunedCount;
},
setNodeError: (nodeNum, error) =>
set(
produce<PrivateNodeDBState>((draft) => {
const nodeDB = draft.nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
nodeDB.nodeErrors = new Map(nodeDB.nodeErrors).set(nodeNum, {
node: nodeNum,
error,
});
}),
),
clearNodeError: (nodeNum) =>
set(
produce<PrivateNodeDBState>((draft) => {
const nodeDB = draft.nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
const updated = new Map(nodeDB.nodeErrors);
updated.delete(nodeNum);
nodeDB.nodeErrors = updated;
}),
),
removeAllNodeErrors: () =>
set(
produce<PrivateNodeDBState>((draft) => {
const nodeDB = draft.nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
nodeDB.nodeErrors = new Map<number, NodeError>();
}),
),
processPacket: (data) =>
set(
produce<PrivateNodeDBState>((draft) => {
const nodeDB = draft.nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
const node = nodeDB.nodeMap.get(data.from);
const nowSec = Math.floor(Date.now() / 1000); // lastHeard is in seconds(!)
if (node) {
const updated = {
...node,
lastHeard: data.time > 0 ? data.time : nowSec,
snr: data.snr,
};
nodeDB.nodeMap = new Map(nodeDB.nodeMap).set(data.from, updated);
} else {
nodeDB.nodeMap = new Map(nodeDB.nodeMap).set(
data.from,
create(Protobuf.Mesh.NodeInfoSchema, {
num: data.from,
lastHeard: data.time > 0 ? data.time : nowSec, // fallback to now if time is 0 or negative,
snr: data.snr,
}),
);
}
}),
),
addUser: (user) =>
set(
produce<PrivateNodeDBState>((draft) => {
const nodeDB = draft.nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
const current = nodeDB.nodeMap.get(user.from);
const isNew = !current;
const updated = {
...(current ?? create(Protobuf.Mesh.NodeInfoSchema)),
user: user.data,
num: user.from,
};
nodeDB.nodeMap = new Map(nodeDB.nodeMap).set(user.from, updated);
if (isNew) {
console.log(
`[NodeDB] Adding new node from user packet: ${user.from} (${user.data.longName || "unknown"})`,
);
}
}),
),
addPosition: (position) =>
set(
produce<PrivateNodeDBState>((draft) => {
const nodeDB = draft.nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
const current = nodeDB.nodeMap.get(position.from);
const isNew = !current;
const updated = {
...(current ?? create(Protobuf.Mesh.NodeInfoSchema)),
position: position.data,
num: position.from,
};
nodeDB.nodeMap = new Map(nodeDB.nodeMap).set(position.from, updated);
if (isNew) {
console.log(`[NodeDB] Adding new node from position packet: ${position.from}`);
}
}),
),
addDeviceMetrics: (metrics) =>
set(
produce<PrivateNodeDBState>((draft) => {
const nodeDB = draft.nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
const current = nodeDB.nodeMap.get(metrics.from);
// Only fold live device metrics into nodes we already know about, to
// avoid creating identity-less phantom nodes from a stray telemetry packet.
if (!current) {
return;
}
const updated = {
...current,
deviceMetrics: metrics.data,
num: metrics.from,
};
nodeDB.nodeMap = new Map(nodeDB.nodeMap).set(metrics.from, updated);
}),
),
setNodeNum: (nodeNum) =>
set(
produce<PrivateNodeDBState>((draft) => {
const newDB = draft.nodeDBs.get(id);
if (!newDB) {
throw new Error(`No nodeDB found for id: ${id}`);
}
newDB.myNodeNum = nodeNum;
for (const [key, oldDB] of draft.nodeDBs) {
if (key === id) {
// short-circuit self
continue;
}
if (oldDB.myNodeNum === nodeNum) {
// We found the oldDB (same myNodeNum). Merge node-by-node as if the new nodes are added with addNode
const mergedNodes = new Map(oldDB.nodeMap);
const mergedErrors = new Map(oldDB.nodeErrors);
const getNodesProxy = (
filter?: (node: Protobuf.Mesh.NodeInfo) => boolean,
): Protobuf.Mesh.NodeInfo[] => {
const arr = Array.from(mergedNodes.values());
return filter ? arr.filter(filter) : arr;
};
const setErrorProxy = (nodeNum: number, err: NodeErrorType) => {
mergedErrors.set(nodeNum, {
node: nodeNum,
error: err,
});
};
for (const [num, newNode] of newDB.nodeMap) {
const next = validateIncomingNode(newNode, setErrorProxy, getNodesProxy);
if (next) {
mergedNodes.set(num, next);
}
const err = newDB.getNodeError(num);
if (err && !oldDB.hasNodeError(num)) {
mergedErrors.set(num, err);
}
}
// finalize: move maps into newDB and drop oldDB entry
newDB.nodeMap = mergedNodes;
newDB.nodeErrors = mergedErrors;
draft.nodeDBs.delete(oldDB.id);
}
}
}),
),
updateFavorite: (nodeNum, isFavorite) =>
set(
produce<PrivateNodeDBState>((draft) => {
const nodeDB = draft.nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
const node = nodeDB.nodeMap.get(nodeNum);
if (node) {
nodeDB.nodeMap = new Map(nodeDB.nodeMap).set(nodeNum, {
...node,
isFavorite: isFavorite,
});
}
}),
),
updateIgnore: (nodeNum, isIgnored) =>
set(
produce<PrivateNodeDBState>((draft) => {
const nodeDB = draft.nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
const node = nodeDB.nodeMap.get(nodeNum);
if (node) {
nodeDB.nodeMap = new Map(nodeDB.nodeMap).set(nodeNum, {
...node,
isIgnored: isIgnored,
});
}
}),
),
getNodesLength: () => {
const nodeDB = get().nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
return nodeDB.nodeMap.size;
},
getNode: (nodeNum) => {
const nodeDB = get().nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
return nodeDB.nodeMap.get(nodeNum);
},
getNodes: (filter, includeSelf) => {
const nodeDB = get().nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
const all = Array.from(nodeDB.nodeMap.values()).filter((n) =>
includeSelf ? true : n.num !== nodeDB.myNodeNum,
);
return filter ? all.filter(filter) : all;
},
getMyNode: () => {
const nodeDB = get().nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
if (nodeDB.myNodeNum) {
return nodeDB.nodeMap.get(nodeDB.myNodeNum) ?? create(Protobuf.Mesh.NodeInfoSchema);
}
},
getNodeError: (nodeNum) => {
const nodeDB = get().nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
return nodeDB.nodeErrors.get(nodeNum);
},
hasNodeError: (nodeNum) => {
const nodeDB = get().nodeDBs.get(id);
if (!nodeDB) {
throw new Error(`No nodeDB found (id: ${id})`);
}
return nodeDB.nodeErrors.has(nodeNum);
},
};
}
export const nodeDBInitializer: StateCreator<PrivateNodeDBState> = (set, get) => ({
nodeDBs: new Map(),
addNodeDB: (id) => {
const existing = get().nodeDBs.get(id);
if (existing) {
// Prune stale nodes when accessing existing nodeDB
existing.pruneStaleNodes();
return existing;
}
const nodeDB = nodeDBFactory(id, get, set);
set(
produce<PrivateNodeDBState>((draft) => {
draft.nodeDBs = new Map(draft.nodeDBs).set(id, nodeDB);
}),
);
// Prune stale nodes on creation (useful when rehydrating from storage)
nodeDB.pruneStaleNodes();
return nodeDB;
},
removeNodeDB: (id) => {
set(
produce<PrivateNodeDBState>((draft) => {
const updated = new Map(draft.nodeDBs);
updated.delete(id);
draft.nodeDBs = updated;
}),
);
},
getNodeDBs: () => Array.from(get().nodeDBs.values()),
getNodeDB: (id) => get().nodeDBs.get(id),
});
const persistOptions: PersistOptions<PrivateNodeDBState, NodeDBPersisted> = {
name: IDB_KEY_NAME,
storage: createStorage<NodeDBPersisted>(),
version: CURRENT_STORE_VERSION,
partialize: (s): NodeDBPersisted => ({
nodeDBs: new Map(
Array.from(s.nodeDBs.entries()).map(([id, db]) => [
id,
{
id: db.id,
myNodeNum: db.myNodeNum,
nodeMap: db.nodeMap,
nodeErrors: db.nodeErrors,
},
]),
),
}),
onRehydrateStorage: () => (state) => {
if (!state) {
return;
}
console.debug(
"NodeDBStore: Rehydrating state with ",
state.nodeDBs.size,
" nodeDBs -",
state.nodeDBs,
);
useNodeDBStore.setState(
produce<PrivateNodeDBState>((draft) => {
const rebuilt = new Map<number, NodeDB>();
for (const [id, data] of (draft.nodeDBs as unknown as Map<number, NodeDBData>).entries()) {
if (data.myNodeNum !== undefined) {
// Only rebuild if there is a nodenum set otherwise orphan dbs will acumulate
rebuilt.set(
id,
nodeDBFactory(id, useNodeDBStore.getState, useNodeDBStore.setState, data),
);
}
}
draft.nodeDBs = rebuilt;
}),
);
},
};
// Add persist middleware on the store if the feature flag is enabled
const persistNodes = featureFlags.get("persistNodeDB");
console.debug(`NodeDBStore: Persisting nodes is ${persistNodes ? "enabled" : "disabled"}`);
export const useNodeDBStore = persistNodes
? createStore(subscribeWithSelector(persist(nodeDBInitializer, persistOptions)))
: createStore(subscribeWithSelector(nodeDBInitializer));
@@ -1,34 +0,0 @@
import { vi } from "vitest";
import type { NodeDB } from "./index.ts";
/**
* You can spread this base mock in your tests and override only the
* properties relevant to a specific test case.
*/
export const mockNodeDBStore: NodeDB = {
id: 0,
myNodeNum: 0,
nodeErrors: new Map(),
nodeMap: new Map(),
addNode: vi.fn(),
addUser: vi.fn(),
addPosition: vi.fn(),
addDeviceMetrics: vi.fn(),
removeNode: vi.fn(),
removeAllNodes: vi.fn(),
pruneStaleNodes: vi.fn().mockReturnValue(0),
processPacket: vi.fn(),
setNodeError: vi.fn(),
clearNodeError: vi.fn(),
removeAllNodeErrors: vi.fn(),
getNodeError: vi.fn().mockReturnValue(undefined),
hasNodeError: vi.fn().mockReturnValue(false),
getNodes: vi.fn().mockReturnValue([]),
getNodesLength: vi.fn().mockReturnValue(0),
getNode: vi.fn().mockReturnValue(undefined),
getMyNode: vi.fn(),
updateFavorite: vi.fn(),
updateIgnore: vi.fn(),
setNodeNum: vi.fn(),
};
@@ -1,68 +0,0 @@
import { create } from "@bufbuild/protobuf";
import { Protobuf, type Types } from "@meshtastic/core";
import { describe, expect, it, vi } from "vitest";
const idbMem = new Map<string, string>();
vi.mock("idb-keyval", () => ({
get: vi.fn((key: string) => Promise.resolve(idbMem.get(key))),
set: vi.fn((key: string, val: string) => {
idbMem.set(key, val);
return Promise.resolve();
}),
del: vi.fn((k: string) => {
idbMem.delete(k);
return Promise.resolve();
}),
}));
// Load a fresh, non-persisting copy of the nodeDB store.
async function freshNodeDB() {
vi.resetModules();
vi.spyOn(console, "debug").mockImplementation(() => {});
vi.spyOn(console, "log").mockImplementation(() => {});
vi.spyOn(console, "info").mockImplementation(() => {});
vi.doMock("@core/services/featureFlags", () => ({
featureFlags: { get: vi.fn(() => false) },
}));
const { useNodeDBStore } = await import("./index.ts");
return useNodeDBStore;
}
function metricsPacket(
from: number,
data: Protobuf.Telemetry.DeviceMetrics,
): Types.PacketMetadata<Protobuf.Telemetry.DeviceMetrics> {
return { id: 1, rxTime: new Date(), type: "broadcast", from, to: 0, channel: 0, data };
}
describe("nodeDBStore – addDeviceMetrics", () => {
it("folds live device metrics into an existing node", async () => {
const useNodeDBStore = await freshNodeDB();
const db = useNodeDBStore.getState().addNodeDB(1);
db.addNode(create(Protobuf.Mesh.NodeInfoSchema, { num: 5 }));
db.addDeviceMetrics(
metricsPacket(
5,
create(Protobuf.Telemetry.DeviceMetricsSchema, { batteryLevel: 80, voltage: 4.1 }),
),
);
expect(db.getNode(5)?.deviceMetrics?.batteryLevel).toBe(80);
expect(db.getNode(5)?.deviceMetrics?.voltage).toBeCloseTo(4.1);
});
it("ignores metrics for an unknown node (no phantom node is created)", async () => {
const useNodeDBStore = await freshNodeDB();
const db = useNodeDBStore.getState().addNodeDB(1);
db.addDeviceMetrics(
metricsPacket(999, create(Protobuf.Telemetry.DeviceMetricsSchema, { batteryLevel: 50 })),
);
expect(db.getNode(999)).toBeUndefined();
expect(db.getNodesLength()).toBe(0);
});
});
@@ -1,549 +0,0 @@
import { create } from "@bufbuild/protobuf";
import { Protobuf } from "@meshtastic/core";
import { act, render, screen } from "@testing-library/react";
import { toByteArray } from "base64-js";
import { beforeEach, describe, expect, it, vi } from "vitest";
const idbMem = new Map<string, string>();
vi.mock("idb-keyval", () => ({
get: vi.fn((key: string) => Promise.resolve(idbMem.get(key))),
set: vi.fn((key: string, val: string) => {
idbMem.set(key, val);
return Promise.resolve();
}),
del: vi.fn((k: string) => {
idbMem.delete(k);
return Promise.resolve();
}),
}));
let deviceIdForTests = 1;
vi.mock("@core/hooks/useDeviceContext", () => ({
useDeviceContext: () => ({ deviceId: deviceIdForTests }),
__setDeviceId: (id: number) => {
deviceIdForTests = id;
},
}));
// import a fresh copy of the store module (because the store is created at import time)
async function freshStore(persist = false) {
vi.resetModules();
// suppress console output from the store during tests (for github actions)
vi.spyOn(console, "debug").mockImplementation(() => {});
vi.spyOn(console, "log").mockImplementation(() => {});
vi.spyOn(console, "info").mockImplementation(() => {});
vi.doMock("@core/services/featureFlags", () => ({
featureFlags: {
get: vi.fn((key: string) => (key === "persistNodeDB" ? persist : false)),
},
}));
const storeMod = await import("./index.ts");
const { useNodeDB } = await import("../index.ts");
return { ...storeMod, useNodeDB };
}
function makeNode(num: number, extras: Record<string, any> = {}) {
return create(Protobuf.Mesh.NodeInfoSchema, { num, ...extras });
}
function makeUser(fields: Record<string, any>) {
return create(Protobuf.Mesh.UserSchema, fields);
}
function makePosition(fields: Record<string, any>) {
return create(Protobuf.Mesh.PositionSchema, fields);
}
describe("NodeDB store", () => {
beforeEach(() => {
idbMem.clear();
vi.clearAllMocks();
});
it("addNodeDB returns same instance on repeated calls; getNodeDB works", async () => {
const { useNodeDBStore } = await freshStore();
const db1 = useNodeDBStore.getState().addNodeDB(123);
const db2 = useNodeDBStore.getState().addNodeDB(123);
expect(db1).toStrictEqual(db2);
const got = useNodeDBStore.getState().getNodeDB(123);
expect(got).toStrictEqual(db1);
expect(useNodeDBStore.getState().getNodeDBs().length).toBe(1);
});
it("addNode, getNode(s), getNodesLength, removeNode", async () => {
const { useNodeDBStore } = await freshStore();
const db = useNodeDBStore.getState().addNodeDB(1);
db.addNode(makeNode(10));
db.addNode(makeNode(11));
expect(db.getNodesLength()).toBe(2);
expect(db.getNode(10)?.num).toBe(10);
const all = db.getNodes();
expect(all.map((n) => n.num).sort()).toEqual([10, 11]);
db.removeNode(10);
expect(db.getNodesLength()).toBe(1);
expect(db.getNode(10)).toBeUndefined();
});
it("processPacket creates or updates a node", async () => {
const { useNodeDBStore } = await freshStore();
const db = useNodeDBStore.getState().addNodeDB(1);
db.processPacket({ from: 50, time: 1111, snr: 7 } as any);
expect(db.getNode(50)).toBeTruthy();
expect(db.getNode(50)?.lastHeard).toBe(1111);
expect(db.getNode(50)?.snr).toBe(7);
db.processPacket({ from: 50, time: 2222, snr: 9 } as any);
expect(db.getNode(50)?.lastHeard).toBe(2222);
expect(db.getNode(50)?.snr).toBe(9);
db.processPacket({ from: 50, time: 0, snr: 9 } as any);
expect(db.getNode(50)?.lastHeard).toBeCloseTo(Date.now() / 1000, -1); // within 1s, note lastHeard is in seconds
expect(db.getNode(50)?.snr).toBe(9);
});
it("addUser and addPosition updates existing or creates new nodes", async () => {
const { useNodeDBStore } = await freshStore();
const db = useNodeDBStore.getState().addNodeDB(1);
// addUser creates node if missing
db.addUser({ from: 77, data: { id: "u" } } as any);
expect(db.getNode(77)?.user).toEqual({ id: "u" });
// addPosition updates same node
db.addPosition({ from: 77, data: { lat: 1, lon: 2 } } as any);
expect(db.getNode(77)?.position).toEqual({ lat: 1, lon: 2 });
expect(db.getNode(77)?.num).toBe(77);
});
it("errors map: setNodeError, getNodeError, hasNodeError, clearNodeError", async () => {
const { useNodeDBStore } = await freshStore();
const db = useNodeDBStore.getState().addNodeDB(1);
db.setNodeError(10, "BadFoo" as any);
expect(db.hasNodeError(10)).toBe(true);
expect(db.getNodeError(10)).toEqual({ node: 10, error: "BadFoo" });
db.clearNodeError(10);
expect(db.hasNodeError(10)).toBe(false);
expect(db.getNodeError(10)).toBeUndefined();
});
it("getMyNode returns undefined before setNodeNum; works after", async () => {
const { useNodeDBStore } = await freshStore();
const db = useNodeDBStore.getState().addNodeDB(1);
db.addNode(makeNode(123));
expect(db.getMyNode()).toBeUndefined();
db.setNodeNum(123);
const me = db.getMyNode();
expect(me?.num).toBe(123);
});
it("setNodeNum merges with existing DB with same myNodeNum", async () => {
const { useNodeDBStore } = await freshStore();
const st = useNodeDBStore.getState();
const oldDB = st.addNodeDB(10);
oldDB.setNodeNum(999);
oldDB.addNode(makeNode(200));
oldDB.setNodeError(200, "ERROR" as any);
const newDB = st.addNodeDB(11);
// newDB currently empty; setting same myNodeNum should copy maps from oldDB and delete old
newDB.setNodeNum(999);
expect(st.getNodeDB(10)).toBeUndefined();
expect(st.getNodeDB(11)).toBeDefined();
expect(newDB.getNode(200)).toBeTruthy();
expect(newDB.getNodeError(200)).toEqual({ node: 200, error: "ERROR" });
});
it("partialize persists only data, and onRehydrateStorage rebuilds methods", async () => {
{
const { useNodeDBStore } = await freshStore(true); // with persistence
const st = useNodeDBStore.getState();
const db = st.addNodeDB(123);
db.setNodeNum(321);
db.addNode(makeNode(50));
db.setNodeError(50, "ERROR" as any);
}
{
const { useNodeDBStore } = await freshStore(true); // with persistence
const st = useNodeDBStore.getState();
const db = st.getNodeDB(123)!;
// methods should work after rehydrate
expect(db.getNode(50)?.num).toBe(50);
expect(db.getNodeError(50)).toEqual({ node: 50, error: "ERROR" });
db.addNode(makeNode(51));
expect(db.getNode(51)).toBeTruthy();
}
});
it("getNodes applies filter and excludes myNodeNum", async () => {
const { useNodeDBStore } = await freshStore();
const db = useNodeDBStore.getState().addNodeDB(1);
db.setNodeNum(11);
db.addNode(makeNode(10));
db.addNode(makeNode(11));
db.addNode(makeNode(12));
const all = db.getNodes();
expect(all.map((n) => n.num).sort()).toEqual([10, 12]); // excludes my (11)
const filtered = db.getNodes((n) => n.num > 10);
expect(filtered.map((n) => n.num).sort()).toEqual([12]); // still excludes 11
});
it("will prune nodes after 14 days of inactivitiy", async () => {
const { useNodeDBStore } = await freshStore();
const st = useNodeDBStore.getState();
st.addNodeDB(1).addNode(makeNode(1, { lastHeard: Date.now() / 1000 - 15 * 24 * 3600 })); // 15 days ago
st.addNodeDB(1).addNode(makeNode(2, { lastHeard: Date.now() / 1000 - 7 * 24 * 3600 })); // 7 days ago
st.getNodeDB(1)!.pruneStaleNodes();
expect(st.getNodeDB(1)?.getNode(2)).toBeDefined();
});
it("removeNodeDB persists removal across reload", async () => {
{
const { useNodeDBStore } = await freshStore(true); // with persistence
const st = useNodeDBStore.getState();
st.addNodeDB(99);
expect(st.getNodeDB(99)).toBeDefined();
st.removeNodeDB(99);
expect(st.getNodeDB(99)).toBeUndefined();
}
{
const { useNodeDBStore } = await freshStore(true); // with persistence
const st = useNodeDBStore.getState();
expect(st.getNodeDB(99)).toBeUndefined(); // still gone
}
});
it("on rehydrate only rebuilds DBs with myNodeNum set (orphans dropped)", async () => {
{
const { useNodeDBStore } = await freshStore(true); // with persistence
const st = useNodeDBStore.getState();
const orphan = st.addNodeDB(500); // no setNodeNum
orphan.addNode(makeNode(1));
const good = st.addNodeDB(501);
good.setNodeNum(42);
good.addNode(makeNode(2));
}
{
const { useNodeDBStore } = await freshStore(true); // with persistence
const st = useNodeDBStore.getState();
expect(st.getNodeDB(500)).toBeUndefined(); // orphan dropped
expect(st.getNodeDB(501)).toBeDefined(); // kept
expect(st.getNodeDB(501)!.getNode(2)).toBeTruthy();
}
});
it("methods throw after their DB is removed from the map", async () => {
const { useNodeDBStore } = await freshStore();
const st = useNodeDBStore.getState();
const db = st.addNodeDB(800);
st.removeNodeDB(800);
expect(() => db.getNodesLength()).toThrow(/No nodeDB found/);
expect(() => db.addNode(makeNode(1))).toThrow(/No nodeDB found/);
});
});
describe("NodeDB – merge semantics, PKI checks & extras", () => {
const keyOld = toByteArray("40g5tLC6A+tXE92EyhwVwdiKsXwa1QUjZjkzEi0pCy4=");
const keyNew = toByteArray("osxYoEP43oDeWZyjyKx1wz/5cvwEOthHB6AhO2fXEQg=");
it("upserts node", async () => {
const { useNodeDBStore } = await freshStore();
const st = useNodeDBStore.getState();
const oldDB = st.addNodeDB(10);
oldDB.setNodeNum(999);
oldDB.addNode(makeNode(200, { position: { altitude: 100 } }));
const newDB = st.addNodeDB(11);
newDB.addNode(makeNode(300));
newDB.addNode(makeNode(200, { position: { altitude: 120 } }));
newDB.setNodeNum(999);
expect(st.getNodeDB(10)).toBeUndefined(); // old db removed
expect(newDB.getNode(300)).toBeTruthy(); // node kept
const n200 = newDB.getNode(200)!;
expect(n200.position?.altitude).toBe(120); // replace existing
});
it("key conflict: keep old node, flag error", async () => {
const { useNodeDBStore } = await freshStore();
const st = useNodeDBStore.getState();
const oldDB = st.addNodeDB(20);
oldDB.setNodeNum(42);
oldDB.addNode(
makeNode(7, {
user: makeUser({ publicKey: keyOld, longName: "old-7" }),
position: makePosition({ latitudeI: 11, longitudeI: 22 }),
}),
);
const newDB = st.addNodeDB(21);
newDB.addNode(
makeNode(7, {
user: makeUser({ publicKey: keyNew, longName: "new-7" }),
position: makePosition({ latitudeI: 33 }),
}),
);
newDB.setNodeNum(42);
const n7 = newDB.getNode(7)!;
// node from old
expect(n7.user?.longName).toBe("old-7");
expect(n7.user?.publicKey).toEqual(keyOld);
expect(n7.position?.latitudeI).toBe(11);
expect(n7.position?.longitudeI).toBe(22);
// error flagged
const err = newDB.getNodeError(7);
expect(err).toBeTruthy();
expect(String(err!.error)).toMatch(/MISMATCH|PK/i);
});
it("empty new key; drop new node", async () => {
const { useNodeDBStore } = await freshStore();
const st = useNodeDBStore.getState();
const oldDB = st.addNodeDB(30);
oldDB.setNodeNum(77);
oldDB.addNode(makeNode(5, { user: { publicKey: keyOld, longName: "old-5" } }));
const newDB = st.addNodeDB(31);
newDB.addNode(makeNode(5, { user: { publicKey: new Uint8Array(), longName: "new-5" } }));
newDB.setNodeNum(77);
// node from old
const n5 = newDB.getNode(5)!;
expect(n5.user?.publicKey).toEqual(keyOld); // keep old PK
expect(n5.user?.longName).toBe("old-5");
// error not flagged; dropped silently
const err = newDB!.getNodeError(5);
expect(err).toBeUndefined();
});
it("old key empty, new key present, store new node", async () => {
const { useNodeDBStore } = await freshStore();
const st = useNodeDBStore.getState();
const oldDB = st.addNodeDB(40);
oldDB.setNodeNum(1001);
oldDB.addNode(makeNode(8, { user: { longName: "old-8" } })); // no key
const newDB = st.addNodeDB(41);
newDB.addNode(
makeNode(8, {
user: { publicKey: keyNew, longName: "new-8" },
position: { altitude: 555 },
}),
);
newDB.setNodeNum(1001);
// node from new
const n8 = newDB.getNode(8)!;
expect(n8.user?.longName).toBe("new-8");
expect(n8.user?.publicKey).toEqual(keyNew);
expect(n8.position?.altitude).toBe(555);
// no error
const err = newDB.getNodeError(8);
expect(err).toBeFalsy();
});
it("unions nodeErrors: preserves old and new, respects existing-on-conflict", async () => {
const { useNodeDBStore } = await freshStore();
const st = useNodeDBStore.getState();
const oldDB = st.addNodeDB(50);
oldDB.setNodeNum(2020);
oldDB.addNode(makeNode(1, { user: { longName: "old-1" } }));
oldDB.setNodeError(1, "OLD_ERR" as any);
const newDB = st.addNodeDB(51);
newDB.addNode(makeNode(1, { user: { longName: "new-1" } }));
newDB.addNode(makeNode(2, { user: { longName: "new-2" } }));
newDB.setNodeError(2, "NEW_ERR" as any);
// also set overlapping error
newDB.setNodeError(1, "SHOULD_NOT_OVERWRITE" as any);
newDB.setNodeNum(2020);
expect(newDB.getNodeError(1)!.error).toBe("OLD_ERR"); // old kept
expect(newDB.getNodeError(2)!.error).toBe("NEW_ERR"); // new added
});
it("removeAllNodes (optionally keeping my node) and removeAllNodeErrors persist across reload", async () => {
{
const { useNodeDBStore } = await freshStore(true); // with persistence
const st = useNodeDBStore.getState();
const db = st.addNodeDB(1000);
db.setNodeNum(55);
db.addNode(makeNode(55, { user: { longName: "me" } }));
db.addNode(makeNode(56));
db.setNodeError(56, "ERR" as any);
db.removeAllNodes(true);
db.removeAllNodeErrors();
}
{
const { useNodeDBStore } = await freshStore(true); // with persistence
const st = useNodeDBStore.getState();
const db = st.getNodeDB(1000)!;
expect(db.getNode(55)).toBeTruthy(); // kept me
expect(db.getNode(56)).toBeUndefined(); // cleared others
expect(db.getNodeError(56)).toBeUndefined(); // cleared errors
}
});
it("getMyNode works after merge establishes myNodeNum", async () => {
const { useNodeDBStore } = await freshStore();
const st = useNodeDBStore.getState();
const oldDB = st.addNodeDB(1100);
oldDB.setNodeNum(4242);
oldDB.addNode(makeNode(4242));
const newDB = st.addNodeDB(1101);
newDB.setNodeNum(4242);
expect(newDB.getMyNode()?.num).toBe(4242);
});
});
describe("NodeDB deviceContext & debounce", () => {
beforeEach(() => {
idbMem.clear();
vi.clearAllMocks();
});
it("useNodeDB resolves per-device DB and switches with deviceId", async () => {
const { useNodeDBStore, useNodeDB } = await freshStore();
// device 1
deviceIdForTests = 1;
const st = useNodeDBStore.getState();
const db1 = st.addNodeDB(1);
db1.addNode({ num: 10 } as any);
function Comp() {
const len = useNodeDB((db) => db.getNodesLength(), {
debounce: 0,
equality: (a, b) => a === b,
});
return <div data-testid="len">{len}</div>;
}
const { rerender } = render(<Comp />);
expect(screen.getByTestId("len").textContent).toBe("1");
// switch to device 2 and add nodes
deviceIdForTests = 2;
const db2 = st.addNodeDB(2);
db2.addNode({ num: 20 } as any);
db2.addNode({ num: 21 } as any);
db2.addNode({ num: 22 } as any);
// re-render so the hook re-subscribes with the new deviceId
await act(async () => {
rerender(<Comp />);
});
expect(screen.getByTestId("len").textContent).toBe("3");
});
it("useNodeDB selector re-renders only when the selected slice changes", async () => {
const { useNodeDBStore, useNodeDB } = await freshStore();
deviceIdForTests = 1;
const st = useNodeDBStore.getState();
const db = st.addNodeDB(1);
let renders = 0;
function Comp() {
const len = useNodeDB((d) => d.getNodesLength(), {
debounce: 0,
equality: (a, b) => a === b,
});
renders++;
return <div data-testid="len">{len}</div>;
}
render(<Comp />);
expect(screen.getByTestId("len").textContent).toBe("0");
expect(renders).toBe(1);
// mutate something unrelated to length
db.setNodeError(999, "X" as any);
await act(() => Promise.resolve());
expect(screen.getByTestId("len").textContent).toBe("0");
expect(renders).toBe(1); // no re-render
// now actually change the slice
db.addNode({ num: 1 } as any);
await act(() => Promise.resolve());
expect(screen.getByTestId("len").textContent).toBe("1");
expect(renders).toBe(2);
});
it("useNodeDB debounce coalesces rapid updates", async () => {
vi.useFakeTimers();
const { useNodeDBStore, useNodeDB } = await freshStore();
deviceIdForTests = 1;
const st = useNodeDBStore.getState();
const db = st.addNodeDB(1);
let renders = 0;
function Comp() {
const len = useNodeDB((d) => d.getNodesLength(), {
debounce: 50,
equality: (a, b) => a === b,
});
renders++;
return <div data-testid="len">{len}</div>;
}
render(<Comp />);
// burst of updates within the debounce window
db.addNode({ num: 1 } as any);
db.addNode({ num: 2 } as any);
db.addNode({ num: 3 } as any);
await act(() => {
vi.advanceTimersByTime(49);
});
expect(renders).toBe(1); // not yet
await act(() => {
vi.advanceTimersByTime(2);
});
expect(screen.getByTestId("len").textContent).toBe("3");
expect(renders).toBe(2); // single coalesced re-render
vi.useRealTimers();
});
});
@@ -1,95 +0,0 @@
import type { NodeErrorType } from "@core/stores";
import type { Protobuf } from "@meshtastic/core";
import { fromByteArray } from "base64-js";
export function equalKey(a?: Uint8Array | null, b?: Uint8Array | null): boolean {
if (!a || !b) {
return false;
}
if (a === b) {
return true;
}
const len = a.byteLength;
if (len !== b.byteLength) {
return false;
}
for (let i = 0; i < len; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
// Validates a new incoming node against existing nodes.
// If valid, returns a node to store, else returns undefined.
export function validateIncomingNode(
newNode: Protobuf.Mesh.NodeInfo,
setNodeError: (nodeNum: number, error: NodeErrorType) => void,
getNodes: (filter?: (node: Protobuf.Mesh.NodeInfo) => boolean) => Protobuf.Mesh.NodeInfo[],
): Protobuf.Mesh.NodeInfo | undefined {
const num = newNode.num;
const existingNodes = getNodes((node) => node.num === num);
if (existingNodes.length === 0) {
// No existing node with this node number.
// Check if the new node's public key (if present and not empty)
// is already claimed by another existing node.
if (newNode.user?.publicKey !== undefined && newNode.user?.publicKey.length > 0) {
const nodesWithSameKey = getNodes((node) => node.user?.publicKey === newNode.user?.publicKey);
if (nodesWithSameKey.length > 0) {
// This is a potential impersonation attempt.
console.warn(
`Node ${num} rejected: Public key already claimed by another node. Key:`,
fromByteArray(newNode.user?.publicKey ?? new Uint8Array()),
);
setNodeError(num, "DUPLICATE_PKI");
return undefined; // drop newNode entirely
}
}
return newNode; // No conflicts, accept newNode
} else if (existingNodes.length === 1) {
// One existing node with this node number.
const oldNode = existingNodes[0];
if (!oldNode) {
return undefined;
}
// A public key is considered matching if the incoming key equals
// the existing key, OR if the existing key is empty.
const isKeyMatchingOrExistingEmpty =
equalKey(oldNode.user?.publicKey, newNode.user?.publicKey) ||
oldNode.user?.publicKey === undefined ||
oldNode.user?.publicKey.length === 0;
if (isKeyMatchingOrExistingEmpty) {
// Keys match or existing key was empty: trust the incoming node data completely.
// This allows for legitimate updates to user info and other fields.
return newNode;
} else if (newNode.user?.publicKey !== undefined && newNode.user?.publicKey.length > 0) {
console.warn(
`Node ${num} rejected: existing key does not match incoming key. Old key:`,
fromByteArray(oldNode.user?.publicKey ?? new Uint8Array()),
"New key:",
fromByteArray(newNode.user?.publicKey ?? new Uint8Array()),
);
// Keys do not match and existing key was not empty: potential impersonation attempt.
setNodeError(num, "MISMATCH_PKI");
return oldNode; // drop newNode fields and return old
} else {
// Incoming node has no public key: ignore the new node entirely.
console.warn(`Node ${num} rejected: incoming node has no public key, but existing does.`);
return oldNode; // drop newNode fields and return old
}
} else {
// Multiple existing nodes with the same node number
// This should never happen, but if it does, we drop the new node entirely.
console.warn(`Node ${num} rejected: Multiple existing nodes with this node number.`);
setNodeError(num, "DUPLICATE_PKI");
return undefined; // drop newNode entirely
}
}
@@ -1,16 +0,0 @@
import type { Protobuf } from "@meshtastic/core";
type NodeErrorType = Protobuf.Mesh.Routing_Error | "MISMATCH_PKI" | "DUPLICATE_PKI";
type NodeError = {
node: number;
error: NodeErrorType;
};
type ProcessPacketParams = {
from: number;
snr: number;
time: number;
};
export type { NodeError, ProcessPacketParams, NodeErrorType };
+23 -55
View File
@@ -1,15 +1,18 @@
import PacketToMessageDTO from "@core/dto/PacketToMessageDTO.ts";
import { useNewNodeNum } from "@core/hooks/useNewNodeNum";
import { type Device, type MessageStore, MessageType, type NodeDB } from "@core/stores";
import { type MeshDevice, Protobuf } from "@meshtastic/core";
export const subscribeAll = (
device: Device,
connection: MeshDevice,
messageStore: MessageStore,
nodeDB: NodeDB,
) => {
let myNodeNum = 0;
import { type Device } from "@core/stores";
import { type MeshDevice, Protobuf } from "@meshtastic/sdk";
/**
* 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).
*/
export const subscribeAll = (device: Device, connection: MeshDevice) => {
connection.events.onDeviceMetadataPacket.subscribe((metadataPacket) => {
device.addMetadata(metadataPacket.from, metadataPacket.data);
});
@@ -56,23 +59,10 @@ export const subscribeAll = (
connection.events.onMyNodeInfo.subscribe((nodeInfo) => {
useNewNodeNum(device.id, nodeInfo);
myNodeNum = nodeInfo.myNodeNum;
});
connection.events.onUserPacket.subscribe((user) => {
nodeDB.addUser(user);
});
connection.events.onPositionPacket.subscribe((position) => {
nodeDB.addPosition(position);
});
// NOTE: Node handling is managed by the nodeDB
// Nodes are added via subscriptions.ts and stored in nodeDB
// Configuration is handled directly by meshDevice.configure() in useConnections
connection.events.onNodeInfoPacket.subscribe((nodeInfo) => {
nodeDB.addNode(nodeInfo);
});
// onUserPacket / onPositionPacket / onNodeInfoPacket are handled by the
// SDK NodesClient (see packages/sdk/src/features/nodes/NodesClient.ts).
connection.events.onChannelPacket.subscribe((channel) => {
device.addChannel(channel);
@@ -84,22 +74,8 @@ export const subscribeAll = (
device.setModuleConfig(moduleConfig);
});
connection.events.onMessagePacket.subscribe((messagePacket) => {
// incoming and outgoing messages are handled by this event listener
const dto = new PacketToMessageDTO(messagePacket, myNodeNum);
const message = dto.toMessage();
messageStore.saveMessage(message);
if (message.type === MessageType.Direct) {
if (message.to === myNodeNum) {
device.incrementUnread(messagePacket.from);
}
} else if (message.type === MessageType.Broadcast) {
if (message.from !== myNodeNum) {
device.incrementUnread(message.channel);
}
}
});
// Inbound message handling (persistence, unread counts) lives entirely on
// the SDK ChatClient now — see ChatClient + chat.unread.
connection.events.onTraceRoutePacket.subscribe((traceRoutePacket) => {
device.addTraceRoute({
@@ -111,13 +87,8 @@ export const subscribeAll = (
device.setPendingSettingsChanges(state);
});
connection.events.onMeshPacket.subscribe((meshPacket) => {
nodeDB.processPacket({
from: meshPacket.from,
snr: meshPacket.rxSnr,
time: meshPacket.rxTime,
});
});
// onMeshPacket → lastHeard / snr per-node updates are handled by the SDK
// NodesClient.
connection.events.onClientNotificationPacket.subscribe((clientNotificationPacket) => {
device.addClientNotification(clientNotificationPacket);
@@ -135,18 +106,15 @@ export const subscribeAll = (
console.error(`Routing Error: ${routingPacket.data.variant.value}`);
break;
case Protobuf.Mesh.Routing_Error.NO_CHANNEL:
console.error(`Routing Error: ${routingPacket.data.variant.value}`);
nodeDB.setNodeError(routingPacket.from, routingPacket?.data?.variant?.value);
device.setDialogOpen("refreshKeys", true);
break;
case Protobuf.Mesh.Routing_Error.PKI_UNKNOWN_PUBKEY:
console.error(`Routing Error: ${routingPacket.data.variant.value}`);
nodeDB.setNodeError(routingPacket.from, 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.
device.setDialogOpen("refreshKeys", true);
break;
default: {
default:
break;
}
}
}
});
+3 -3
View File
@@ -5,9 +5,9 @@ export function getX25519PrivateKey(): Uint8Array {
// scalar clamping for curve25519, according to
// https://www.rfc-editor.org/rfc/rfc7748#section-5
key[0] &= 248;
key[31] &= 127;
key[31] |= 64;
key[0]! &= 248;
key[31]! &= 127;
key[31]! |= 64;
return key;
}