Skip to content

feat: add abstract local peer communication - #561

Merged
meganetaaan merged 10 commits into
developfrom
codex/local-peer-p2p
Jul 19, 2026
Merged

feat: add abstract local peer communication#561
meganetaaan merged 10 commits into
developfrom
codex/local-peer-p2p

Conversation

@meganetaaan

@meganetaaan meganetaaan commented Jul 18, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Add a transport-agnostic local peer communication capability for stack-chan modules.
  • Keep the ESP32 radio implementation hidden behind the abstract LocalPeerCapability API.
  • Support discovery, broadcast and reliable direct messages, fragmentation, retries, deduplication, and optional shared-key encryption.
  • Integrate offline startup and Wi-Fi credential clearing into the device and web settings flows.
  • Add Japanese documentation and a single-manifest example MOD whose P2P drawer selects stopped, sender, or receiver (hello world N with bounded and sanitized receiver balloons), plus architecture checks, unit tests, and Moddable runtime tests.
  • Prevent timeout-triggered XS restarts by making LocalPeerError preload-safe and queueing acknowledgements before subscriber replies.

Why

Modules need a local P2P communication surface without depending on ESP-NOW or another transport-specific API. This change exposes only logical peers, sessions, messages, and delivery receipts, so the underlying transport can be replaced without changing module code.

Validation

  • npm run test:unit: 179 tests passed
  • npm run lint
  • npm run format
  • npm run check:architecture: 60 checks passed
  • Manifest validation across 6 targets
  • All 30 Moddable test manifests passed
  • Debug builds passed for esp32/m5stackchan_cores3 and esp32/m5stack_cores3
  • Two-device hardware test passed with encrypted 1024-byte fragmented messages in both directions
  • Five-minute instrument soak showed no restart, abort, or monotonic memory growth

Summary by CodeRabbit

  • New Features

    • Added local peer-to-peer messaging for supported ESP32 devices, including peer discovery, direct messages, broadcasts, subscriptions, optional encryption, and delivery status.
    • Added a “Local Peer Hello” example with sender and receiver modes.
    • Added offline launch confirmation and role selection for local peer communication.
    • Added a Wi‑Fi settings action to clear saved credentials.
  • Documentation

    • Added Japanese guides for local peer communication and the Local Peer Hello example.
  • Bug Fixes

    • Improved setup-screen updates and handling when switching between online and offline modes.

@meganetaaan

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds ESP32 local peer messaging with discovery, reliable sends, broadcasts, subscriptions, framing, encryption, runtime lifecycle handling, and a role-based example. It also adds offline Wi-Fi setup and preference clearing flows, documentation, tests, manifest wiring, and smoke-test tooling updates.

Changes

Local peer communication

Layer / File(s) Summary
Protocol and transport
firmware/host/modules/connectivity/local-peer-*, firmware/host/modules/connectivity/esp32/*
Adds public contracts, UTF-8/framing utilities, ESP-NOW transport, peer authentication, queued sends, and native lifecycle management.
Session service and runtime integration
firmware/host/modules/connectivity/local-peer-service.ts, firmware/host/app/*, firmware/host/modules/connectivity/manifest*
Adds discovery, reliable and broadcast messaging, acknowledgements, retries, subscriptions, deduplication, capability exposure, platform mappings, and automatic session cleanup.
Example and documentation
firmware/mods/examples/local_peer_hello/*, firmware/docs/local-peer-communication_ja.md, firmware/mods/README_ja.md
Adds sender/receiver role control, payload sanitization, example manifests and tests, Japanese usage documentation, and MOD catalog documentation.

Offline Wi-Fi setup and preferences

Layer / File(s) Summary
Firmware setup flow
firmware/host/app/setup-mode.ts, firmware/host/modules/ui/views/settings/*, firmware/host/modules/connectivity/stored-wifi.ts
Adds guarded settings updates, offline confirmation, credential clearing, password-view navigation, and related tests.
Web preference flow
web/preference/*, web/web-ui.test.mjs
Extracts preference-page logic into an ES module and adds confirmed BLE-based Wi-Fi credential clearing with success and failure tests.

Smoke tooling

Layer / File(s) Summary
Runtime and smoke execution
firmware/scripts/*
Narrows fatal simulator log detection and makes Linux smoke execution discover the dynamically assigned XSBUG port.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.46% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: introducing abstract local peer communication.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/local-peer-p2p

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai

coderabbitai Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 8

🧹 Nitpick comments (1)
firmware/host/app/runtime-context.ts (1)

489-495: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Preserve future capability extensions by avoiding hardcoded destructuring.

If new fields (e.g., bluetooth) are added to ConnectivityCapability in the future, the current implementation will silently drop them by only copying network. Returning the object directly when localPeer is missing, and spreading ...connectivity when wrapping it, makes the factory resilient to future extensions.

♻️ Proposed refactor
   private createConnectivityCapability(connectivity: ConnectivityCapability): ConnectivityCapability {
     const localPeer = connectivity.localPeer
-    if (!localPeer) return { network: connectivity.network }
+    if (!localPeer) return connectivity
     const context = this
     return {
-      network: connectivity.network,
+      ...connectivity,
       localPeer: {
🤖 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 `@firmware/host/app/runtime-context.ts` around lines 489 - 495, Update
createConnectivityCapability to preserve all existing ConnectivityCapability
fields: return connectivity directly when localPeer is absent, and spread
...connectivity when constructing the wrapped result before overriding
localPeer. Keep the current localPeer wrapping behavior unchanged.
🤖 Prompt for all review comments with 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.

Inline comments:
In `@firmware/host/modules/connectivity/__tests__/local-peer-frame.test.ts`:
- Around line 20-24: Update the hash assertion in the “local peer UTF-8 codec
round-trips ASCII, Japanese, and supplementary characters” test to compare
fnv1a32(value) against a precomputed known FNV-1a expected value, rather than
invoking fnv1a32 on the same input on both sides. Keep the existing UTF-8
round-trip assertion unchanged.

In `@firmware/host/modules/connectivity/__tests__/local-peer-service.test.ts`:
- Around line 6-261: Move the runtime-focused tests in
firmware/host/modules/connectivity/__tests__/local-peer-service.test.ts (lines
6-261), including FakeRadioNetwork, FakeRadio, openPair, and the
LocalPeerService lifecycle/retry cases, into XS-driven Moddable coverage while
preserving their behaviors. Replace the source/manifest rescanning assertions in
firmware/host/modules/connectivity/__tests__/local-peer.architecture.ts (lines
1-35) with runtime checks, or document the architectural rationale with
source-level why-comments instead.

In `@firmware/host/modules/connectivity/__tests__/stored-wifi.test.ts`:
- Around line 121-137: Move the clearStoredWiFiCredentials behavior test from
the Node suite into the XS-driven Moddable harness, preserving its setup and
network-stop assertions. In the migrated test, directly verify that both stored
preference keys, wifi.ssid and wifi.password, are empty after clearing; do not
rely solely on connectStoredWiFi() returning false.

In `@firmware/host/modules/connectivity/esp32/local-peer-radio.c`:
- Around line 144-155: The callbacks around the shown send-status handler and
the callback covering lines 164–207 must synchronize access to gLocalPeerRadio
with localPeerNativeClose. Hold the same close/lookup lock while reading the
global, checking radio->closed, and incrementing useCount, then release it
before posting or other callback work; ensure no radio fields are dereferenced
before the reference is acquired.

In `@firmware/host/modules/connectivity/esp32/local-peer-radio.js`:
- Around line 23-32: Update the construction error path in the local peer radio
initialization to roll back the native radio after nativeConstruct succeeds but
nativeGetID fails. In the catch block surrounding nativeConstruct and
nativeGetID, release or reset the native object and clear the occupied
gLocalPeerRadio state before closing Wi-Fi and rethrowing the original error.

In `@firmware/host/modules/connectivity/local-peer-service.ts`:
- Around line 542-552: In the reliable-message handling flow around `#deliver` and
`#sendAcknowledgement`, queue and complete the acknowledgement before invoking
subscribers via `#deliver`, while preserving duplicate suppression and existing
acknowledgement behavior. Ensure a synchronous close() from a subscriber cannot
interrupt ACK completion, and add a regression test covering close() from the
message handler without causing a sender timeout.

In `@web/preference/index.html`:
- Around line 88-90: Update the catch block handling the save-status failure so
null or undefined rejection values do not cause a second exception when reading
error.message. Safely derive the displayed error detail before calling
setStatus, while preserving the existing message and error status for ordinary
Error objects.

In `@web/web-ui.test.mjs`:
- Around line 41-50: Replace the source-text regex assertions in the preference
test with a runtime interaction test that loads the preference page, stubs
confirmation and client.send, and clicks the wifi-clear-button. Assert the
resulting _batch payload, cleared SSID/password fields, success status, and
recovery of the button’s disabled state; retain only assertions that verify
actual rendered behavior.

---

Nitpick comments:
In `@firmware/host/app/runtime-context.ts`:
- Around line 489-495: Update createConnectivityCapability to preserve all
existing ConnectivityCapability fields: return connectivity directly when
localPeer is absent, and spread ...connectivity when constructing the wrapped
result before overriding localPeer. Keep the current localPeer wrapping behavior
unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 15a03c36-4abb-4299-8d76-1f9d481484fb

📥 Commits

Reviewing files that changed from the base of the PR and between f29a226 and 89c018b.

📒 Files selected for processing (31)
  • firmware/docs/local-peer-communication_ja.md
  • firmware/host/app/boot-services.ts
  • firmware/host/app/capabilities.ts
  • firmware/host/app/runtime-context.ts
  • firmware/host/app/setup-mode.ts
  • firmware/host/modules/connectivity/__tests__/local-peer-frame.test.ts
  • firmware/host/modules/connectivity/__tests__/local-peer-service.test.ts
  • firmware/host/modules/connectivity/__tests__/local-peer.architecture.ts
  • firmware/host/modules/connectivity/__tests__/stored-wifi.test.ts
  • firmware/host/modules/connectivity/esp32/local-peer-radio.c
  • firmware/host/modules/connectivity/esp32/local-peer-radio.js
  • firmware/host/modules/connectivity/local-peer-capability.ts
  • firmware/host/modules/connectivity/local-peer-codec.ts
  • firmware/host/modules/connectivity/local-peer-frame.ts
  • firmware/host/modules/connectivity/local-peer-radio-types.ts
  • firmware/host/modules/connectivity/local-peer-service.ts
  • firmware/host/modules/connectivity/local-peer-types.ts
  • firmware/host/modules/connectivity/manifest.json
  • firmware/host/modules/connectivity/manifest_wasm.json
  • firmware/host/modules/connectivity/sim/local-peer-capability.ts
  • firmware/host/modules/connectivity/stored-wifi.ts
  • firmware/host/modules/ui/views/settings/__tests__/settings-view/settings-view.test.ts
  • firmware/host/modules/ui/views/settings/settings-view.ts
  • firmware/mods/README_ja.md
  • firmware/mods/examples/local_peer_hello/README_ja.md
  • firmware/mods/examples/local_peer_hello/manifest.json
  • firmware/mods/examples/local_peer_hello/mod.js
  • firmware/tsconfig.test.json
  • web/preference/index.html
  • web/preference/preference.css
  • web/web-ui.test.mjs

Comment thread firmware/host/modules/connectivity/__tests__/local-peer-service.test.ts Outdated
Comment thread firmware/host/modules/connectivity/__tests__/stored-wifi.test.ts Outdated
Comment thread firmware/host/modules/connectivity/esp32/local-peer-radio.c Outdated
Comment thread firmware/host/modules/connectivity/esp32/local-peer-radio.js
Comment thread firmware/host/modules/connectivity/local-peer-service.ts Outdated
Comment thread web/preference/index.html Outdated
Comment thread web/web-ui.test.mjs Outdated
@meganetaaan
meganetaaan marked this pull request as ready for review July 18, 2026 15:28

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7b7feb1c5f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread firmware/host/modules/connectivity/esp32/local-peer-radio.c Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
firmware/scripts/smoke-lin.sh (1)

74-75: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Avoid globally disabling errexit.

Disabling errexit with set +e allows the script to continue running if the timeout command fails, which can inadvertently mask failures if there are subsequent commands, or skip configured ERR traps.

If you need to handle timeout's exit code (for instance, if returning 124 for a timeout is an expected condition) without terminating the script via set -e, it is safer to handle the failure explicitly.

♻️ Proposed refactor to explicitly handle the exit status
-set +e
-timeout "$smoke_timeout" env XSBUG_HOST="$xsbug_host" XSBUG_PORT="$xsbug_port" xvfb-run -a "$MODDABLE/build/bin/lin/release/mcsim" "$smoke_build_root/bin/$platform_path/debug/app/mc.so"
+timeout "$smoke_timeout" env XSBUG_HOST="$xsbug_host" XSBUG_PORT="$xsbug_port" xvfb-run -a "$MODDABLE/build/bin/lin/release/mcsim" "$smoke_build_root/bin/$platform_path/debug/app/mc.so" || exit_code=$?
+# You can optionally evaluate $exit_code here if needed
🤖 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 `@firmware/scripts/smoke-lin.sh` around lines 74 - 75, Remove the global set +e
before the timeout invocation in the smoke script. Update the command handling
around timeout in the smoke execution flow to explicitly capture and evaluate
its exit status, preserving the intended timeout behavior without bypassing
errexit or configured ERR traps.

Source: Linters/SAST tools

🤖 Prompt for all review comments with 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.

Nitpick comments:
In `@firmware/scripts/smoke-lin.sh`:
- Around line 74-75: Remove the global set +e before the timeout invocation in
the smoke script. Update the command handling around timeout in the smoke
execution flow to explicitly capture and evaluate its exit status, preserving
the intended timeout behavior without bypassing errexit or configured ERR traps.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: db20dfba-56f4-4cbb-998e-cb35ac2fd2af

📥 Commits

Reviewing files that changed from the base of the PR and between 7b7feb1 and 8696d1f.

📒 Files selected for processing (20)
  • firmware/host/app/capabilities.ts
  • firmware/host/app/runtime-context.ts
  • firmware/host/modules/connectivity/__tests__/local-peer-frame.test.ts
  • firmware/host/modules/connectivity/__tests__/local-peer-service-xs/local-peer-service-xs.test.ts
  • firmware/host/modules/connectivity/__tests__/local-peer-service-xs/manifest.test.json
  • firmware/host/modules/connectivity/__tests__/stored-wifi-xs/manifest.test.json
  • firmware/host/modules/connectivity/__tests__/stored-wifi-xs/stored-wifi-xs.test.ts
  • firmware/host/modules/connectivity/__tests__/stored-wifi.test.ts
  • firmware/host/modules/connectivity/esp32/local-peer-radio.c
  • firmware/host/modules/connectivity/esp32/local-peer-radio.js
  • firmware/host/modules/connectivity/local-peer-capability.ts
  • firmware/host/modules/connectivity/local-peer-service.ts
  • firmware/host/modules/connectivity/local-peer-types.ts
  • firmware/host/modules/connectivity/manifest.json
  • firmware/scripts/run-module-tests.js
  • firmware/scripts/smoke-lin.sh
  • firmware/scripts/xsbug-log-smoke-server.js
  • web/preference/index.html
  • web/preference/preference.mjs
  • web/web-ui.test.mjs
💤 Files with no reviewable changes (1)
  • firmware/host/modules/connectivity/tests/stored-wifi.test.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • firmware/host/modules/connectivity/local-peer-capability.ts
  • firmware/host/modules/connectivity/tests/local-peer-frame.test.ts
  • firmware/host/modules/connectivity/local-peer-types.ts
  • firmware/host/app/capabilities.ts
  • firmware/host/app/runtime-context.ts
  • firmware/host/modules/connectivity/esp32/local-peer-radio.js
  • firmware/host/modules/connectivity/local-peer-service.ts
  • firmware/host/modules/connectivity/esp32/local-peer-radio.c

@meganetaaan

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@meganetaaan

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@meganetaaan

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@meganetaaan

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@meganetaaan meganetaaan reopened this Jul 19, 2026
# Conflicts:
#	firmware/host/app/setup-mode.ts
#	firmware/host/modules/ui/views/settings/__tests__/settings-view/settings-view.test.ts
#	firmware/host/modules/ui/views/settings/settings-view.ts
@meganetaaan
meganetaaan merged commit 2ea659b into develop Jul 19, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant