Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
"@tanstack/router-cli": "^1.167.18",
"@tanstack/router-devtools": "^1.167.0",
"@turf/turf": "^7.3.5",
"@types/d3": "^7.4.3",
"@types/node": "^26.1.0",
"@types/web-bluetooth": "^0.0.21",
"base64-js": "^1.5.1",
Expand All @@ -73,6 +74,7 @@
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"crypto-random-string": "^5.0.0",
"d3": "^7.9.0",
"i18next": "^26.3.4",
"i18next-browser-languagedetector": "^8.2.0",
"i18next-http-backend": "^4.0.0",
Expand Down
87 changes: 87 additions & 0 deletions apps/web/src/components/PageComponents/Telemetry/Battery.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { useWaitForConfig } from "@app/core/hooks/useWaitForConfig";
import {
type BluetoothValidation,
BluetoothValidationSchema,
} from "@app/validation/config/bluetooth.ts";
import {
DynamicForm,
type DynamicFormFormInit,
} from "@components/Form/DynamicForm.tsx";
import { useDevice } from "@core/stores";
import { Protobuf } from "@meshtastic/sdk";
import { useConfigEditor, useSignal } from "@meshtastic/sdk-react";
import { useTranslation } from "react-i18next";

interface BluetoothConfigProps {
onFormInit: DynamicFormFormInit<BluetoothValidation>;
}

const EMPTY_RADIO_SIGNAL = {
value: {} as { bluetooth?: Protobuf.Config.Config_BluetoothConfig },
peek: () => ({}) as { bluetooth?: Protobuf.Config.Config_BluetoothConfig },
subscribe: () => () => {},
} as const;

export const Bluetooth = ({ onFormInit }: BluetoothConfigProps) => {
useWaitForConfig({ configCase: "bluetooth" });

const { config, getEffectiveConfig } = useDevice();
const editor = useConfigEditor();
const radio = useSignal(editor?.radio ?? EMPTY_RADIO_SIGNAL);
const effective =
radio.bluetooth ??
(getEffectiveConfig("bluetooth") as
| Protobuf.Config.Config_BluetoothConfig
| undefined);

const { t } = useTranslation("config");

const onSubmit = (data: BluetoothValidation) => {
if (!editor) return;
editor.setRadioSection(
"bluetooth",
data as unknown as Protobuf.Config.Config_BluetoothConfig,
);
};

return (
<DynamicForm<BluetoothValidation>
onSubmit={onSubmit}
onFormInit={onFormInit}
validationSchema={BluetoothValidationSchema}
defaultValues={config.bluetooth}
values={effective}
fieldGroups={[
{
label: t("bluetooth.bluetoothConfig.label"),
description: t("bluetooth.bluetoothConfig.description"),
notes: t("bluetooth.note"),
fields: [
{
type: "toggle",
name: "enabled",
label: t("bluetooth.enabled.label"),
description: t("bluetooth.enabled.description"),
},
{
type: "select",
name: "mode",
label: t("bluetooth.pairingMode.label"),
description: t("bluetooth.pairingMode.description"),
properties: {
enumValue: Protobuf.Config.Config_BluetoothConfig_PairingMode,
formatEnumName: true,
},
},
{
type: "number",
name: "fixedPin",
label: t("bluetooth.pin.label"),
description: t("bluetooth.pin.description"),
},
Comment on lines +51 to +81

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Files matching Battery.tsx/config Bluetooth:"
fd -a 'Battery\.tsx|config\.proto|Bluetooth' . | sed 's#^\./##' | head -200

echo
echo "Battery outline:"
file=$(fd 'Battery\.tsx' . | head -1)
if [ -n "${file:-}" ]; then
  echo "FILE=$file"
  ast-grep outline "$file" --view expanded || true
  echo
  wc -l "$file"
  sed -n '1,140p' "$file" | cat -n
fi

echo
echo "Search BluetoothValidationSchema and pairing mode usages:"
rg -n "BluetoothValidationSchema|fixedPin|pairingMode|PairingMode|NO_PIN|RANDOM_PIN|FIXED_PIN" .

Repository: meshtastic/web

Length of output: 9816


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Bluetooth validation source:"
sed -n '1,80p' apps/web/src/validation/config/bluetooth.ts | cat -n
echo

echo "Bluetooth component source:"
sed -n '45,85p' apps/web/src/components/PageComponents/Telemetry/Battery.tsx | cat -n
echo

echo "Protobuf BluetoothConfig section:"
sed -n '1250,1290p' packages/protobufs/meshtastic/config.proto | cat -n
echo

echo "DynamicForm field handling:"
fd 'DynamicForm\.(ts|tsx)$' . -x sh -c 'echo "FILE=$1"; sed -n "1,220p" "$1" | cat -n' sh {}

Repository: meshtastic/web

Length of output: 10314


🌐 Web query:

Zod conditional required field requiredIf exact match mode conditional optional based on another field value

💡 Result:

Zod does not have a native "requiredIf" method [1][2]. To enforce that a field is required based on the value of another field, you should use either superRefine (or .check in newer versions) for cross-field validation, or a discriminatedUnion for stronger type inference [3][4][5]. 1. Using superRefine/check (Recommended for general conditional logic) This approach allows you to inspect the entire object and add custom issues to specific fields when conditions are not met [4][6]. const schema = z.object({ conditionField: z.boolean, dependentField: z.string.optional, }).superRefine((data, ctx) => { if (data.conditionField &&!data.dependentField) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: "dependentField is required when conditionField is true", path: ["dependentField"], }); } }); 2. Using Discriminated Union (Recommended for stronger types) If your conditional logic relies on literal values, a discriminated union is preferred because it creates distinct types based on the discriminator field [3][5]. const schema = z.discriminatedUnion("type", [ z.object({ type: z.literal("A"), field: z.string }), z.object({ type: z.literal("B"), field: z.string.optional }), ]); 3. Controlling when validation runs By default, refinements may only run if the base schema is valid [2][7]. If you need your custom validation to run even when base fields fail (e.g., to report all errors at once), you can use the when parameter in superRefine or .refine, which accepts a callback to determine if the refinement should execute [8][7].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "read-only Zod v4 behavioral probe:"
python3 - <<'PY'
from pathlib import Path
p = Path("apps/web/src/validation/config/bluetooth.ts").read_text()
print("fixedPin base requirement present:", "fixedPin: z.coerce.number().int().min(100000).max(999999)" in p)
print("fixedPin conditional refs:", any(s in p for s in ("FIXED_PIN", "fixed_pin", "superRefine", "refine", "discriminatedUnion", ".when(")))
print("mode enum values:", "'RANDOM_PIN'" in p, "'FIXED_PIN'" in p, "'NO_PIN'" in p)
PY

echo
echo "check same Bluetooth form in Settings:"
sed -n '1,90p' apps/web/src/components/PageComponents/Settings/Bluetooth.tsx | cat -n

Repository: meshtastic/web

Length of output: 3656


Require fixedPin only for FIXED_PIN.

BluetoothValidationSchema requires a six-digit PIN for every Bluetooth mode, but the protobuf reserves fixedPin for FIXED_PIN; RANDOM_PIN/NO_PIN cannot be submitted without an ignored value. Make the PIN optional except when mode === FIXED_PIN, and apply the same schema UI behavior in the Bluetooth Settings form.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/src/components/PageComponents/Telemetry/Battery.tsx` around lines 51
- 81, Update BluetoothValidationSchema so fixedPin is optional for RANDOM_PIN
and NO_PIN but required as a six-digit PIN when mode is FIXED_PIN, while
preserving the existing Bluetooth validation rules. Apply the same conditional
schema and UI behavior to the Bluetooth Settings form, using the mode field and
fixedPin configuration symbols already shared by the Bluetooth forms.

],
},
]}
/>
);
};
18 changes: 14 additions & 4 deletions apps/web/src/components/Sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
MessageSquareIcon,
SettingsIcon,
UsersIcon,
ChartNoAxesCombinedIcon,
} from "lucide-react";
import type React from "react";
import { useEffect, useState, useTransition } from "react";
Expand Down Expand Up @@ -121,17 +122,26 @@ export const Sidebar = ({ children }: SidebarProps) => {
page: "messages",
count: numUnread ? numUnread : undefined,
},
{ name: t("navigation.map"), icon: MapIcon, page: "map" },
{
name: t("navigation.settings"),
icon: SettingsIcon,
page: "settings",
name: t("navigation.map"),
icon: MapIcon,
page: "map",
},
{
name: `${t("navigation.nodes")} (${displayedNodeCount})`,
icon: UsersIcon,
page: "nodes",
},
{
name: "Telemetry",
icon: ChartNoAxesCombinedIcon,
page: "telemetry",
},
{
name: t("navigation.settings"),
icon: SettingsIcon,
page: "settings",
},
];

return (
Expand Down
95 changes: 95 additions & 0 deletions apps/web/src/core/connections/nodeMetricsRecorder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { createLogger, type MeshClient } from "@meshtastic/sdk";
import type {
NodeMetricSample,
NodeMetricsRetentionPolicy,
SqlocalNodeMetricsRepository,
} from "@meshtastic/sdk-storage-sqlocal/nodeMetrics";

const log = createLogger("nodeMetricsRecorder");

export interface NodeMetricsRecorderOptions {
retention?: NodeMetricsRetentionPolicy;
/** Run a prune pass after roughly this many appended samples. */
pruneEvery?: number;
}

/**
* Records per-node metrics (SNR, hops away, last heard) — the node-level
* values shown on the Nodes page that Telemetry packets don't carry — into the
* given repository, so the Telemetry page can chart them for every node.
*
* SNR is sampled from every inbound mesh packet (dense signal history); hops
* away / last heard come from NodeInfo broadcasts. Returns a teardown that
* detaches the subscriptions.
*/
export function attachNodeMetricsRecorder(
client: MeshClient,
repo: SqlocalNodeMetricsRepository,
options: NodeMetricsRecorderOptions = {},
): () => void {
const retention = options.retention;
const pruneEvery = options.pruneEvery ?? 128;
let sincePrune = 0;

const record = (samples: NodeMetricSample[]): void => {
if (samples.length === 0) return;
repo
.appendBatch(samples)
.then(() => {
sincePrune += samples.length;
if (retention && sincePrune >= pruneEvery) {
sincePrune = 0;
return repo.prune(retention);
}
})
.catch((e: unknown) => {
log.warn("node metric persist failed", {
error: (e as Error)?.message,
});
});
};

const unsubMesh = client.events.onMeshPacket.subscribe((packet) => {
if (!packet.from) return;
const time =
packet.rxTime > 0 ? new Date(packet.rxTime * 1000) : new Date();
if (Number.isFinite(packet.rxSnr)) {
record([
{ nodeNum: packet.from, metric: "snr", time, value: packet.rxSnr },
]);
}
});

const unsubNodeInfo = client.events.onNodeInfoPacket.subscribe((info) => {
if (!info.num) return;
const time =
info.lastHeard > 0 ? new Date(info.lastHeard * 1000) : new Date();
const samples: NodeMetricSample[] = [];
// NodeInfo.snr is 0 when unset; only record a genuine measurement.
if (Number.isFinite(info.snr) && info.snr !== 0) {
samples.push({ nodeNum: info.num, metric: "snr", time, value: info.snr });
}
if (typeof info.hopsAway === "number") {
samples.push({
nodeNum: info.num,
metric: "hopsAway",
time,
value: info.hopsAway,
});
}
if (info.lastHeard > 0) {
samples.push({
nodeNum: info.num,
metric: "lastHeard",
time,
value: info.lastHeard,
});
}
record(samples);
});

return () => {
unsubMesh();
unsubNodeInfo();
};
}
29 changes: 27 additions & 2 deletions apps/web/src/core/connections/sdkClient.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { coordinator, getStorageDb } from "@core/sdkStorage.ts";
import type { ConnectionId } from "@core/stores/deviceStore/types";
import { createLogger, MeshDevice } from "@meshtastic/sdk";
import { createLogger, DeviceStatusEnum, 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 { SqlocalNodeMetricsRepository } from "@meshtastic/sdk-storage-sqlocal/nodeMetrics";
import { attachNodeMetricsRecorder } from "./nodeMetricsRecorder.ts";
import type { TransportHTTP } from "@meshtastic/transport-http";
import type { TransportWebBluetooth } from "@meshtastic/transport-web-bluetooth";
import type { TransportWebSerial } from "@meshtastic/transport-web-serial";
Expand All @@ -26,6 +28,10 @@ const TELEMETRY_RETENTION = {
maxPerNode: 500,
olderThanMs: 1000 * 60 * 60 * 24 * 30,
} as const;
const NODE_METRICS_RETENTION = {
maxPerMetric: 1000,
olderThanMs: 1000 * 60 * 60 * 24 * 30,
} as const;
const STORAGE_OPEN_TIMEOUT_MS = 5000;

/**
Expand All @@ -45,6 +51,7 @@ export async function buildMeshDevice(
let draftRepository: SqlocalDraftRepository | undefined;
let nodesRepository: SqlocalNodesRepository | undefined;
let telemetryRepository: SqlocalTelemetryRepository | undefined;
let nodeMetricsRepository: SqlocalNodeMetricsRepository | undefined;
try {
const t0 = Date.now();
const db = await Promise.race([
Expand Down Expand Up @@ -75,6 +82,9 @@ export async function buildMeshDevice(
telemetryRepository = new SqlocalTelemetryRepository(db, {
deviceId: connectionId,
});
nodeMetricsRepository = new SqlocalNodeMetricsRepository(db, {
deviceId: connectionId,
});
log.debug("buildMeshDevice: repositories opened");
} catch (err) {
const e = err as Error;
Expand All @@ -87,7 +97,7 @@ export async function buildMeshDevice(
);
}

return new MeshDevice(transport, {
const meshDevice = new MeshDevice(transport, {
configId: deviceId,
chat:
chatRepository || draftRepository
Expand All @@ -102,4 +112,19 @@ export async function buildMeshDevice(
? { repository: telemetryRepository, retention: TELEMETRY_RETENTION }
: undefined,
});

// The node-metrics recorder has no SDK client of its own — it subscribes to
// the mesh client's event bus and persists directly. Detached on disconnect.
if (nodeMetricsRepository) {
const detach = attachNodeMetricsRecorder(
meshDevice.meshClient,
nodeMetricsRepository,
{ retention: NODE_METRICS_RETENTION },
);
meshDevice.meshClient.events.onDeviceStatus.subscribe((status) => {
if (status === DeviceStatusEnum.DeviceDisconnected) detach();
});
}

return meshDevice;
}
8 changes: 7 additions & 1 deletion apps/web/src/core/stores/deviceStore/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,13 @@ interface Dialogs {

type DialogVariant = keyof Dialogs;

type Page = "messages" | "map" | "settings" | "channels" | "nodes";
type Page =
| "messages"
| "map"
| "settings"
| "channels"
| "nodes"
| "telemetry";

export type ConnectionId = number;
export type ConnectionType = "http" | "bluetooth" | "serial";
Expand Down
Loading