CLI for SidePulse
Python
Move iOS app out and add native hook capture experiment
Peter Kuharc39ac1fd0535
diff --git a/experiments/native_hook_capture/.gitignore b/experiments/native_hook_capture/.gitignorenew file mode 100644index 0000000..b71c451--- /dev/null+++ b/experiments/native_hook_capture/.gitignore@@ -0,0 +1 @@+/capturediff --git a/experiments/native_hook_capture/capture.cpp b/experiments/native_hook_capture/capture.cppnew file mode 100644index 0000000..1ada125--- /dev/null+++ b/experiments/native_hook_capture/capture.cpp@@ -0,0 +1,276 @@+#include <array>+#include <cerrno>+#include <chrono>+#include <cstdint>+#include <crt_externs.h>+#include <cstdlib>+#include <cstring>+#include <fcntl.h>+#include <libproc.h>+#include <limits>+#include <string>+#include <string_view>+#include <sys/file.h>+#include <sys/socket.h>+#include <sys/sysctl.h>+#include <sys/un.h>+#include <unistd.h>++namespace {++class UniqueFd {+public:+ explicit UniqueFd(int value = -1) : value_(value) {}+ ~UniqueFd() { if (value_ >= 0) ::close(value_); }+ UniqueFd(const UniqueFd&) = delete;+ UniqueFd& operator=(const UniqueFd&) = delete;+ int get() const { return value_; }++private:+ int value_;+};++struct Arguments {+ std::string provider;+ std::string event;+ std::string log_path;+ std::string spool_path;+ std::string notify_socket;+};++bool take_value(int& index, int count, char** values, std::string& output) {+ if (++index >= count) return false;+ output = values[index];+ return true;+}++bool parse_arguments(int count, char** values, Arguments& args) {+ for (int index = 1; index < count; ++index) {+ const std::string_view flag(values[index]);+ if (flag == "--provider") {+ if (!take_value(index, count, values, args.provider)) return false;+ } else if (flag == "--event") {+ if (!take_value(index, count, values, args.event)) return false;+ } else if (flag == "--log") {+ if (!take_value(index, count, values, args.log_path)) return false;+ } else if (flag == "--spool") {+ if (!take_value(index, count, values, args.spool_path)) return false;+ } else if (flag == "--notify-socket") {+ if (!take_value(index, count, values, args.notify_socket)) return false;+ } else {+ return false;+ }+ }+ if (args.provider.empty() || args.log_path.empty()) return false;+ if (args.spool_path.empty()) args.spool_path = args.log_path + ".spool";+ return true;+}++bool read_stdin(std::string& payload) {+ std::array<char, 16 * 1024> buffer{};+ for (;;) {+ const ssize_t count = ::read(STDIN_FILENO, buffer.data(), buffer.size());+ if (count > 0) {+ payload.append(buffer.data(), static_cast<std::size_t>(count));+ } else if (count == 0) {+ return true;+ } else if (errno != EINTR) {+ return false;+ }+ }+}++std::uint64_t nanoseconds(clockid_t clock) {+ timespec value{};+ if (::clock_gettime(clock, &value) != 0) return 0;+ return static_cast<std::uint64_t>(value.tv_sec) * 1'000'000'000ULL+ + static_cast<std::uint64_t>(value.tv_nsec);+}++void append_u32(std::string& output, std::uint32_t value) {+ for (int shift = 24; shift >= 0; shift -= 8) {+ output.push_back(static_cast<char>((value >> shift) & 0xff));+ }+}++void append_u64(std::string& output, std::uint64_t value) {+ for (int shift = 56; shift >= 0; shift -= 8) {+ output.push_back(static_cast<char>((value >> shift) & 0xff));+ }+}++void append_context_entry(std::string& context, std::string_view key,+ std::string_view value) {+ append_u32(context, static_cast<std::uint32_t>(key.size()));+ append_u32(context, static_cast<std::uint32_t>(value.size()));+ context.append(key);+ context.append(value);+}++void capture_process_arguments(pid_t pid, std::string_view prefix, std::string& context) {+ int query[] = {CTL_KERN, KERN_PROCARGS2, pid};+ std::size_t size = 0;+ if (::sysctl(query, 3, nullptr, &size, nullptr, 0) != 0 || size < sizeof(int)+ || size > 1024 * 1024) {+ return;+ }+ std::string buffer(size, '\0');+ if (::sysctl(query, 3, buffer.data(), &size, nullptr, 0) != 0+ || size < sizeof(int)) {+ return;+ }+ buffer.resize(size);+ int argument_count = 0;+ std::memcpy(&argument_count, buffer.data(), sizeof(argument_count));+ if (argument_count <= 0) return;++ std::size_t cursor = sizeof(argument_count);+ while (cursor < buffer.size() && buffer[cursor] != '\0') ++cursor;+ while (cursor < buffer.size() && buffer[cursor] == '\0') ++cursor;+ for (int index = 0; index < argument_count && cursor < buffer.size(); ++index) {+ const std::size_t start = cursor;+ while (cursor < buffer.size() && buffer[cursor] != '\0') ++cursor;+ append_context_entry(context,+ std::string(prefix) + "arg:" + std::to_string(index),+ std::string_view(buffer.data() + start, cursor - start));+ while (cursor < buffer.size() && buffer[cursor] == '\0') ++cursor;+ }+}++std::string capture_context() {+ std::string context;+ constexpr std::array keys = {+ "SIDEPULSE_AGENT_ORIGIN",+ "SIDEPULSE_AGENT_ORIGIN_KIND",+ "SIDEPULSE_DISABLE_EVENT_SOCKET",+ "TERM_PROGRAM",+ "__CFBundleIdentifier",+ "HOME",+ "XDG_STATE_HOME",+ };+ for (const char* key : keys) {+ if (const char* value = ::getenv(key); value != nullptr) {+ append_context_entry(context, std::string("env:") + key, value);+ }+ }++ char*** environment = ::_NSGetEnviron();+ for (char** item = environment == nullptr ? nullptr : *environment;+ item != nullptr && *item != nullptr; ++item) {+ if (std::string_view(*item).starts_with("VSCODE_")) {+ append_context_entry(context, "env:VSCODE_PRESENT", "1");+ break;+ }+ }++ pid_t pid = ::getppid();+ for (int depth = 0; depth < 10 && pid > 1; ++depth) {+ proc_bsdinfo info{};+ if (::proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, sizeof(info))+ != sizeof(info)) {+ break;+ }+ const std::string prefix = "process:" + std::to_string(depth) + ":";+ append_context_entry(context, prefix + "pid", std::to_string(pid));+ append_context_entry(context, prefix + "ppid", std::to_string(info.pbi_ppid));+ append_context_entry(context, prefix + "comm", info.pbi_comm);+ std::array<char, PROC_PIDPATHINFO_MAXSIZE> path{};+ const int path_size = ::proc_pidpath(pid, path.data(), path.size());+ if (path_size > 0) {+ append_context_entry(context, prefix + "path",+ std::string_view(path.data(), path_size));+ }+ capture_process_arguments(pid, prefix, context);+ pid = static_cast<pid_t>(info.pbi_ppid);+ }+ return context;+}++bool append_size(std::string& output, std::size_t value) {+ if (value > std::numeric_limits<std::uint32_t>::max()) return false;+ append_u32(output, static_cast<std::uint32_t>(value));+ return true;+}++bool build_frame(const Arguments& args, const std::string& context,+ const std::string& payload, std::string& frame) {+ constexpr std::uint32_t fixed_body_size = 36;+ const std::size_t variable_size = args.provider.size() + args.event.size()+ + args.log_path.size() + context.size() + payload.size();+ if (variable_size > std::numeric_limits<std::uint32_t>::max() - fixed_body_size) {+ return false;+ }++ frame.reserve(8 + fixed_body_size + variable_size);+ frame.append("SPH1", 4);+ append_u32(frame, fixed_body_size + static_cast<std::uint32_t>(variable_size));+ append_u64(frame, nanoseconds(CLOCK_REALTIME));+ append_u64(frame, nanoseconds(CLOCK_MONOTONIC));+ if (!append_size(frame, args.provider.size()) || !append_size(frame, args.event.size())+ || !append_size(frame, args.log_path.size()) || !append_size(frame, context.size())+ || !append_size(frame, payload.size())) {+ return false;+ }+ frame.append(args.provider);+ frame.append(args.event);+ frame.append(args.log_path);+ frame.append(context);+ frame.append(payload);+ return true;+}++bool write_all(int descriptor, const std::string& data) {+ std::size_t offset = 0;+ while (offset < data.size()) {+ const ssize_t count = ::write(descriptor, data.data() + offset, data.size() - offset);+ if (count > 0) {+ offset += static_cast<std::size_t>(count);+ } else if (count < 0 && errno == EINTR) {+ continue;+ } else {+ return false;+ }+ }+ return true;+}++bool append_frame(const std::string& path, const std::string& frame) {+ UniqueFd file(::open(path.c_str(), O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0600));+ if (file.get() < 0 || ::flock(file.get(), LOCK_EX) != 0) return false;+ const off_t original_size = ::lseek(file.get(), 0, SEEK_END);+ const bool written = write_all(file.get(), frame);+ if (!written && original_size >= 0) (void)::ftruncate(file.get(), original_size);+ (void)::flock(file.get(), LOCK_UN);+ return written;+}++void notify(const std::string& path) {+ if (path.empty() || path.size() >= sizeof(sockaddr_un::sun_path)) return;+ UniqueFd socket(::socket(AF_UNIX, SOCK_DGRAM, 0));+ if (socket.get() < 0) return;+ const int flags = ::fcntl(socket.get(), F_GETFL, 0);+ if (flags >= 0) (void)::fcntl(socket.get(), F_SETFL, flags | O_NONBLOCK);++ sockaddr_un address{};+ address.sun_family = AF_UNIX;+ std::memcpy(address.sun_path, path.c_str(), path.size() + 1);+ constexpr char wake = 1;+ (void)::sendto(socket.get(), &wake, 1, 0,+ reinterpret_cast<const sockaddr*>(&address), sizeof(address));+}++} // namespace++int main(int argc, char** argv) {+ Arguments args;+ std::string context;+ std::string payload;+ std::string frame;+ if (!parse_arguments(argc, argv, args) || !read_stdin(payload)) return 0;+ context = capture_context();+ if (!build_frame(args, context, payload, frame) || !append_frame(args.spool_path, frame)) {+ return 0;+ }+ notify(args.notify_socket);+ return 0;+}diff --git a/experiments/native_hook_capture/test_capture.py b/experiments/native_hook_capture/test_capture.pynew file mode 100644index 0000000..4290d29--- /dev/null+++ b/experiments/native_hook_capture/test_capture.py@@ -0,0 +1,253 @@+from __future__ import annotations++import concurrent.futures+import os+import socket+import struct+import subprocess+import tempfile+import unittest+from dataclasses import dataclass+from pathlib import Path+++ROOT = Path(__file__).resolve().parent+BINARY = ROOT / "capture"+SOURCE = ROOT / "capture.cpp"+FIXED_HEADER = struct.Struct(">4sIQQIIIII")+++@dataclass(frozen=True)+class Frame:+ realtime_ns: int+ monotonic_ns: int+ provider: bytes+ event: bytes+ log_path: bytes+ context: bytes+ payload: bytes+++def build() -> None:+ subprocess.run(+ [+ "clang++",+ "-std=c++20",+ "-O2",+ "-DNDEBUG",+ "-Wall",+ "-Wextra",+ "-Werror",+ str(SOURCE),+ "-o",+ str(BINARY),+ ],+ check=True,+ )+++def decode(path: Path) -> list[Frame]:+ data = path.read_bytes()+ frames: list[Frame] = []+ offset = 0+ while offset < len(data):+ if len(data) - offset < FIXED_HEADER.size:+ raise AssertionError("incomplete frame header")+ (+ magic,+ body_length,+ realtime_ns,+ monotonic_ns,+ provider_length,+ event_length,+ log_length,+ context_length,+ payload_length,+ ) = FIXED_HEADER.unpack_from(data, offset)+ if magic != b"SPH1":+ raise AssertionError(f"unexpected magic at {offset}: {magic!r}")+ frame_end = offset + 8 + body_length+ if frame_end > len(data):+ raise AssertionError("incomplete frame body")+ cursor = offset + FIXED_HEADER.size++ def take(length: int) -> bytes:+ nonlocal cursor+ result = data[cursor : cursor + length]+ cursor += length+ return result++ provider = take(provider_length)+ event = take(event_length)+ log_path = take(log_length)+ context = take(context_length)+ payload = take(payload_length)+ if cursor != frame_end:+ raise AssertionError("frame lengths do not match body length")+ frames.append(+ Frame(realtime_ns, monotonic_ns, provider, event, log_path, context, payload)+ )+ offset = frame_end+ return frames+++def decode_context(data: bytes) -> dict[str, str]:+ result: dict[str, str] = {}+ offset = 0+ while offset < len(data):+ if len(data) - offset < 8:+ raise AssertionError("incomplete context header")+ key_length, value_length = struct.unpack_from(">II", data, offset)+ offset += 8+ end = offset + key_length + value_length+ if end > len(data):+ raise AssertionError("incomplete context entry")+ key = data[offset : offset + key_length].decode()+ offset += key_length+ value = data[offset : offset + value_length].decode(errors="surrogateescape")+ offset += value_length+ result[key] = value+ return result+++def capture(+ spool: Path,+ payload: bytes,+ *,+ provider: str = "claude",+ event: str | None = None,+ notify_socket: Path | None = None,+ environment: dict[str, str] | None = None,+) -> subprocess.CompletedProcess[bytes]:+ command = [+ str(BINARY),+ "--provider",+ provider,+ "--log",+ f"/tmp/{provider}.jsonl",+ "--spool",+ str(spool),+ ]+ if event is not None:+ command.extend(["--event", event])+ if notify_socket is not None:+ command.extend(["--notify-socket", str(notify_socket)])+ return subprocess.run(+ command,+ input=payload,+ capture_output=True,+ check=False,+ env=environment,+ )+++class CaptureTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls) -> None:+ build()++ def setUp(self) -> None:+ self.temporary = tempfile.TemporaryDirectory(prefix="sidepulse-capture-test-")+ self.addCleanup(self.temporary.cleanup)+ self.root = Path(self.temporary.name)+ self.spool = self.root / "events.spool"++ def test_raw_payloads_round_trip_without_json_processing(self) -> None:+ payloads = (+ b"",+ b" \n\t ",+ b"this is not json",+ b'{"hook_event_name":"PreToo',+ b"null",+ b"[1,2,3]",+ '{"message":"emoji 🚀 ünïcode"}'.encode(),+ b'{"message":"a\\u0000b","path":"C:\\\\tmp"}',+ b'{"message":"' + (b"x" * 500_000) + b'"}',+ b"literal\x00bytes",+ )+ for payload in payloads:+ result = capture(self.spool, payload)+ self.assertEqual(result.returncode, 0)+ self.assertEqual(result.stdout, b"")+ self.assertEqual(result.stderr, b"")+ self.assertEqual([frame.payload for frame in decode(self.spool)], list(payloads))++ def test_provider_event_and_log_metadata_round_trip(self) -> None:+ cases = (+ ("codex", None),+ ("claude", None),+ ("grok", None),+ ("cursor", "preToolUse"),+ )+ for provider, event in cases:+ capture(self.spool, b"{}", provider=provider, event=event)+ frames = decode(self.spool)+ self.assertEqual([frame.provider.decode() for frame in frames], [c[0] for c in cases])+ self.assertEqual([frame.event.decode() for frame in frames], [c[1] or "" for c in cases])+ self.assertEqual(+ [frame.log_path.decode() for frame in frames],+ [f"/tmp/{provider}.jsonl" for provider, _ in cases],+ )+ self.assertTrue(all(frame.realtime_ns > 0 for frame in frames))+ self.assertTrue(all(frame.monotonic_ns > 0 for frame in frames))++ def test_hook_environment_and_process_context_are_captured(self) -> None:+ environment = {+ **os.environ,+ "SIDEPULSE_AGENT_ORIGIN": "Claude in Test Host",+ "SIDEPULSE_AGENT_ORIGIN_KIND": "claude_test",+ "SIDEPULSE_DISABLE_EVENT_SOCKET": "1",+ "TERM_PROGRAM": "TestTerminal",+ "__CFBundleIdentifier": "io.sidepulse.tests",+ "VSCODE_IPC_HOOK_CLI": "/tmp/vscode.sock",+ "HOME": "/tmp/test-home",+ "XDG_STATE_HOME": "/tmp/test-state",+ }+ capture(self.spool, b"{}", environment=environment)+ context = decode_context(decode(self.spool)[0].context)+ self.assertEqual(context["env:SIDEPULSE_AGENT_ORIGIN"], "Claude in Test Host")+ self.assertEqual(context["env:SIDEPULSE_AGENT_ORIGIN_KIND"], "claude_test")+ self.assertEqual(context["env:SIDEPULSE_DISABLE_EVENT_SOCKET"], "1")+ self.assertEqual(context["env:TERM_PROGRAM"], "TestTerminal")+ self.assertEqual(context["env:__CFBundleIdentifier"], "io.sidepulse.tests")+ self.assertEqual(context["env:VSCODE_PRESENT"], "1")+ self.assertEqual(context["env:HOME"], "/tmp/test-home")+ self.assertEqual(context["env:XDG_STATE_HOME"], "/tmp/test-state")+ self.assertTrue(any(key.endswith(":pid") for key in context))+ self.assertTrue(any(key.endswith(":comm") for key in context))+ self.assertTrue(any(":arg:" in key for key in context))++ def test_sequential_invocations_preserve_order(self) -> None:+ expected = [f"event-{index}".encode() for index in range(100)]+ for payload in expected:+ capture(self.spool, payload)+ self.assertEqual([frame.payload for frame in decode(self.spool)], expected)++ def test_concurrent_writers_never_interleave_frames(self) -> None:+ expected = {f"writer-{index}".encode() for index in range(80)}+ with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:+ results = list(pool.map(lambda payload: capture(self.spool, payload), expected))+ self.assertTrue(all(result.returncode == 0 for result in results))+ self.assertEqual({frame.payload for frame in decode(self.spool)}, expected)++ def test_notification_is_nonblocking_and_contains_no_event_data(self) -> None:+ notify_path = self.root / "notify.sock"+ listener = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)+ self.addCleanup(listener.close)+ listener.bind(str(notify_path))+ listener.settimeout(1)+ payload = b'{"secret":"not sent over notification socket"}'+ result = capture(self.spool, payload, notify_socket=notify_path)+ self.assertEqual(result.returncode, 0)+ self.assertEqual(listener.recv(16), b"\x01")+ self.assertEqual(decode(self.spool)[0].payload, payload)++ def test_missing_listener_and_bad_arguments_fail_open_silently(self) -> None:+ result = capture(self.spool, b"{}", notify_socket=self.root / "missing.sock")+ self.assertEqual((result.returncode, result.stdout, result.stderr), (0, b"", b""))+ bad = subprocess.run([str(BINARY), "--provider"], capture_output=True)+ self.assertEqual((bad.returncode, bad.stdout, bad.stderr), (0, b"", b""))+++if __name__ == "__main__":+ unittest.main()diff --git a/ios/SidePulse/README.md b/ios/SidePulse/README.mddeleted file mode 100644index 44db986..0000000--- a/ios/SidePulse/README.md+++ /dev/null@@ -1,192 +0,0 @@-# SidePulse for iOS--SidePulse is a push inbox that can optionally write LED programs to `LEDS.LED`-on a SidePulse Dot USB drive attached to an iPhone or iPad.--The app supports:--- General-purpose APNs pushes, stored newest-first in the inbox.-- Tiny named-pattern pushes such as `{"pattern":"green_pulse_2"}`.-- Raw LED pushes using `leds`, `LEDS.LED`, or `text`.-- Literal `\n`, `\r`, `\t`, and `\\` escapes in LED text are decoded before- validation and writing.-- Shortcuts or URL actions such as `sidepulse://write?pattern=success`.-- Optional SidePulse Dot folder writes through Files.--The bundle identifier is `io.sidepulse.app`.--## iOS setup--1. Open `SidePulse.xcodeproj` in Xcode.-2. Select the `SidePulse` target.-3. Select your Apple Developer team.-4. Confirm the bundle identifier is `io.sidepulse.app`.-5. Confirm these capabilities:- - Push Notifications- - Background Modes -> Remote notifications-6. Build and run on a real iPhone or iPad. APNs push tokens do not work on the- simulator.-7. Tap **Get Push Token** and copy the token.-8. Tap **Set Up SidePulse Dot Folder**, then select the SidePulse Dot USB drive folder- containing `LEDS.LED` in Files.--If no SidePulse Dot folder is configured, pushes still appear in the inbox. The app-does not treat that as a user-facing failure.--## Background pushes--SidePulse handles silent pushes in-`application(_:didReceiveRemoteNotification:fetchCompletionHandler:)`. Silent-delivery is still controlled by iOS: Background App Refresh must be enabled, the-app must not be force-quit, and delivery can be delayed. Visible alert pushes-are also processed when delivered or opened.--For silent/background writes, APNs should use:--```text-apns-push-type: background-apns-priority: 5-apns-topic: io.sidepulse.app-```--## Payloads--Full LED text wins over pattern names:--```json-{- "aps": {"content-available": 1},- "LEDS.LED": "#00ff00 280ms pulse\noff 160ms none\n"-}-```--Tiny named-pattern push:--```json-{- "aps": {"content-available": 1},- "pattern": "green_pulse_2"-}-```--Supported pattern names:--```text-off-green_pulse_2-success-error-working-waiting-white_breathe-```--The app also accepts arbitrary `data` or custom payload fields and stores them-as general pushes when no LED text or known pattern is present.--## Fast push server--Create a virtual environment:--```sh-cd ios/SidePulse/tools-python3 -m venv .venv-source .venv/bin/activate-python -m pip install -r requirements.txt-```--Set APNs credentials and server defaults:--```sh-export APNS_TEAM_ID="YOUR_TEAM_ID"-export APNS_KEY_ID="YOUR_KEY_ID"-export APNS_AUTH_KEY="/path/to/AuthKey_YOUR_KEY_ID.p8"-export APNS_BUNDLE_ID="io.sidepulse.app"-export APNS_ENV="sandbox"-export SIDEPULSE_DEVICE_TOKEN="token copied from the app"-export SIDEPULSE_SHARED_SECRET="choose-a-local-testing-secret"-```--Run the server:--```sh-python server.py-```--Open `http://127.0.0.1:8787` for the simple sender page, or use curl:--```sh-curl -X POST http://127.0.0.1:8787/v1/push \- -H "Authorization: Bearer $SIDEPULSE_SHARED_SECRET" \- -H "content-type: application/json" \- -d '{"pattern":"green_pulse_2"}'-```--Send raw LED text:--```sh-curl -X POST http://127.0.0.1:8787/v1/push \- -H "Authorization: Bearer $SIDEPULSE_SHARED_SECRET" \- -H "content-type: application/json" \- -d '{"leds":"#00ff00 280ms pulse\noff 160ms none\n"}'-```--The helper script calls the same endpoint:--```sh-python send_push.py --pattern green_pulse_2-```--## API--`GET /health`--Returns server health.--`GET /v1/patterns`--Returns server-known pattern names and LED text.--`POST /v1/push`--Friendly envelope:--```json-{- "device_token": "optional if SIDEPULSE_DEVICE_TOKEN is set",- "pattern": "green_pulse_2",- "leds": "optional raw LEDS.LED",- "payload": {"optional": "extra custom payload fields"},- "apns": {- "push_type": "background",- "priority": 5,- "collapse_id": "optional",- "expiration": "optional"- }-}-```--`POST /v1/push/raw`--Passes the JSON body through as the exact APNs payload. Provide the device token-with `?device_token=...`, `X-Side-Device-Token`, or `SIDEPULSE_DEVICE_TOKEN`.-Optional APNs overrides can be sent as `apns-push-type`, `apns-priority`,-`apns-collapse-id`, `apns-expiration`, or `apns-topic` request headers.--```sh-curl -X POST "http://127.0.0.1:8787/v1/push/raw?device_token=$SIDEPULSE_DEVICE_TOKEN" \- -H "Authorization: Bearer $SIDEPULSE_SHARED_SECRET" \- -H "content-type: application/json" \- -H "apns-push-type: background" \- -H "apns-priority: 5" \- -d '{"aps":{"content-available":1},"pattern":"success","data":{"source":"curl"}}'-```--## Notes--- The server uses FastAPI, uvicorn, a shared `httpx.AsyncClient(http2=True)`,- connection pooling, and cached APNs JWT refresh.-- SidePulse server settings use the `SIDEPULSE_*` environment-variable prefix.-- Keep LED programs at or below 512 bytes and 20 physical lines for the SidePulse Dot writer. The DSL is- documented in the repo root at `LEDS_FORMAT.md`.-- The generated source app icon is kept at `SidePulseIconSource.png`.diff --git a/ios/SidePulse/SidePulse.xcodeproj/project.pbxproj b/ios/SidePulse/SidePulse.xcodeproj/project.pbxprojdeleted file mode 100644index a71b01d..0000000--- a/ios/SidePulse/SidePulse.xcodeproj/project.pbxproj+++ /dev/null@@ -1,369 +0,0 @@-// !$*UTF8*$!-{- archiveVersion = 1;- classes = {- };- objectVersion = 56;- objects = {--/* Begin PBXBuildFile section */- 9F0000010000000000000001 /* SidePulseApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000101 /* SidePulseApp.swift */; };- 9F0000010000000000000002 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000102 /* ContentView.swift */; };- 9F0000010000000000000003 /* AppModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000103 /* AppModel.swift */; };- 9F0000010000000000000004 /* DriveWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000104 /* DriveWriter.swift */; };- 9F0000010000000000000005 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000105 /* AppDelegate.swift */; };- 9F0000010000000000000006 /* FolderPicker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000106 /* FolderPicker.swift */; };- 9F0000010000000000000007 /* WriteLEDsIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000107 /* WriteLEDsIntent.swift */; };- 9F0000010000000000000008 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000108 /* Assets.xcassets */; };- 9F0000010000000000000009 /* EventLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000112 /* EventLog.swift */; };- 9F0000010000000000000010 /* PushPayload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000113 /* PushPayload.swift */; };-/* End PBXBuildFile section */--/* Begin PBXFileReference section */- 9F0000010000000000000101 /* SidePulseApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidePulseApp.swift; sourceTree = "<group>"; };- 9F0000010000000000000102 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = "<group>"; };- 9F0000010000000000000103 /* AppModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppModel.swift; sourceTree = "<group>"; };- 9F0000010000000000000104 /* DriveWriter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DriveWriter.swift; sourceTree = "<group>"; };- 9F0000010000000000000105 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };- 9F0000010000000000000106 /* FolderPicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FolderPicker.swift; sourceTree = "<group>"; };- 9F0000010000000000000107 /* WriteLEDsIntent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WriteLEDsIntent.swift; sourceTree = "<group>"; };- 9F0000010000000000000108 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };- 9F0000010000000000000109 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };- 9F0000010000000000000110 /* SidePulse.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = SidePulse.entitlements; sourceTree = "<group>"; };- 9F0000010000000000000111 /* SidePulse.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SidePulse.app; sourceTree = BUILT_PRODUCTS_DIR; };- 9F0000010000000000000112 /* EventLog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventLog.swift; sourceTree = "<group>"; };- 9F0000010000000000000113 /* PushPayload.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PushPayload.swift; sourceTree = "<group>"; };-/* End PBXFileReference section */--/* Begin PBXFrameworksBuildPhase section */- 9F0000010000000000000201 /* Frameworks */ = {- isa = PBXFrameworksBuildPhase;- buildActionMask = 2147483647;- files = (- );- runOnlyForDeploymentPostprocessing = 0;- };-/* End PBXFrameworksBuildPhase section */--/* Begin PBXGroup section */- 9F0000010000000000000301 = {- isa = PBXGroup;- children = (- 9F0000010000000000000302 /* SidePulse */,- 9F0000010000000000000303 /* Products */,- );- sourceTree = "<group>";- };- 9F0000010000000000000302 /* SidePulse */ = {- isa = PBXGroup;- children = (- 9F0000010000000000000101 /* SidePulseApp.swift */,- 9F0000010000000000000102 /* ContentView.swift */,- 9F0000010000000000000103 /* AppModel.swift */,- 9F0000010000000000000104 /* DriveWriter.swift */,- 9F0000010000000000000105 /* AppDelegate.swift */,- 9F0000010000000000000112 /* EventLog.swift */,- 9F0000010000000000000113 /* PushPayload.swift */,- 9F0000010000000000000106 /* FolderPicker.swift */,- 9F0000010000000000000107 /* WriteLEDsIntent.swift */,- 9F0000010000000000000108 /* Assets.xcassets */,- 9F0000010000000000000109 /* Info.plist */,- 9F0000010000000000000110 /* SidePulse.entitlements */,- );- path = SidePulse;- sourceTree = "<group>";- };- 9F0000010000000000000303 /* Products */ = {- isa = PBXGroup;- children = (- 9F0000010000000000000111 /* SidePulse.app */,- );- name = Products;- sourceTree = "<group>";- };-/* End PBXGroup section */--/* Begin PBXNativeTarget section */- 9F0000010000000000000401 /* SidePulse */ = {- isa = PBXNativeTarget;- buildConfigurationList = 9F0000010000000000000902 /* Build configuration list for PBXNativeTarget "SidePulse" */;- buildPhases = (- 9F0000010000000000000501 /* Sources */,- 9F0000010000000000000201 /* Frameworks */,- 9F0000010000000000000601 /* Resources */,- );- buildRules = (- );- dependencies = (- );- name = SidePulse;- productName = SidePulse;- productReference = 9F0000010000000000000111 /* SidePulse.app */;- productType = "com.apple.product-type.application";- };-/* End PBXNativeTarget section */--/* Begin PBXProject section */- 9F0000010000000000000701 /* Project object */ = {- isa = PBXProject;- attributes = {- BuildIndependentTargetsInParallel = 1;- LastSwiftUpdateCheck = 1530;- LastUpgradeCheck = 1530;- TargetAttributes = {- 9F0000010000000000000401 = {- CreatedOnToolsVersion = 15.3;- };- };- };- buildConfigurationList = 9F0000010000000000000901 /* Build configuration list for PBXProject "SidePulse" */;- compatibilityVersion = "Xcode 14.0";- developmentRegion = en;- hasScannedForEncodings = 0;- knownRegions = (- en,- Base,- );- mainGroup = 9F0000010000000000000301;- productRefGroup = 9F0000010000000000000303 /* Products */;- projectDirPath = "";- projectRoot = "";- targets = (- 9F0000010000000000000401 /* SidePulse */,- );- };-/* End PBXProject section */--/* Begin PBXResourcesBuildPhase section */- 9F0000010000000000000601 /* Resources */ = {- isa = PBXResourcesBuildPhase;- buildActionMask = 2147483647;- files = (- 9F0000010000000000000008 /* Assets.xcassets in Resources */,- );- runOnlyForDeploymentPostprocessing = 0;- };-/* End PBXResourcesBuildPhase section */--/* Begin PBXSourcesBuildPhase section */- 9F0000010000000000000501 /* Sources */ = {- isa = PBXSourcesBuildPhase;- buildActionMask = 2147483647;- files = (- 9F0000010000000000000001 /* SidePulseApp.swift in Sources */,- 9F0000010000000000000002 /* ContentView.swift in Sources */,- 9F0000010000000000000003 /* AppModel.swift in Sources */,- 9F0000010000000000000004 /* DriveWriter.swift in Sources */,- 9F0000010000000000000005 /* AppDelegate.swift in Sources */,- 9F0000010000000000000009 /* EventLog.swift in Sources */,- 9F0000010000000000000010 /* PushPayload.swift in Sources */,- 9F0000010000000000000006 /* FolderPicker.swift in Sources */,- 9F0000010000000000000007 /* WriteLEDsIntent.swift in Sources */,- );- runOnlyForDeploymentPostprocessing = 0;- };-/* End PBXSourcesBuildPhase section */--/* Begin XCBuildConfiguration section */- 9F0000010000000000000801 /* Debug */ = {- isa = XCBuildConfiguration;- buildSettings = {- ALWAYS_SEARCH_USER_PATHS = NO;- CLANG_ANALYZER_NONNULL = YES;- CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;- CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";- CLANG_ENABLE_MODULES = YES;- CLANG_ENABLE_OBJC_ARC = YES;- CLANG_ENABLE_OBJC_WEAK = YES;- CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;- CLANG_WARN_BOOL_CONVERSION = YES;- CLANG_WARN_COMMA = YES;- CLANG_WARN_CONSTANT_CONVERSION = YES;- CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;- CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;- CLANG_WARN_DOCUMENTATION_COMMENTS = YES;- CLANG_WARN_EMPTY_BODY = YES;- CLANG_WARN_ENUM_CONVERSION = YES;- CLANG_WARN_INFINITE_RECURSION = YES;- CLANG_WARN_INT_CONVERSION = YES;- CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;- CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;- CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;- CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;- CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;- CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;- CLANG_WARN_STRICT_PROTOTYPES = YES;- CLANG_WARN_SUSPICIOUS_MOVE = YES;- CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;- CLANG_WARN_UNREACHABLE_CODE = YES;- CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;- COPY_PHASE_STRIP = NO;- DEBUG_INFORMATION_FORMAT = dwarf;- ENABLE_STRICT_OBJC_MSGSEND = YES;- ENABLE_TESTABILITY = YES;- ENABLE_USER_SCRIPT_SANDBOXING = YES;- GCC_C_LANGUAGE_STANDARD = gnu17;- GCC_DYNAMIC_NO_PIC = NO;- GCC_NO_COMMON_BLOCKS = YES;- GCC_OPTIMIZATION_LEVEL = 0;- GCC_PREPROCESSOR_DEFINITIONS = (- "DEBUG=1",- "$(inherited)",- );- GCC_WARN_64_TO_32_BIT_CONVERSION = YES;- GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;- GCC_WARN_UNDECLARED_SELECTOR = YES;- GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;- GCC_WARN_UNUSED_FUNCTION = YES;- GCC_WARN_UNUSED_VARIABLE = YES;- IPHONEOS_DEPLOYMENT_TARGET = 16.0;- MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;- MTL_FAST_MATH = YES;- ONLY_ACTIVE_ARCH = YES;- SDKROOT = iphoneos;- SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";- SWIFT_OPTIMIZATION_LEVEL = "-Onone";- };- name = Debug;- };- 9F0000010000000000000802 /* Release */ = {- isa = XCBuildConfiguration;- buildSettings = {- ALWAYS_SEARCH_USER_PATHS = NO;- CLANG_ANALYZER_NONNULL = YES;- CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;- CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";- CLANG_ENABLE_MODULES = YES;- CLANG_ENABLE_OBJC_ARC = YES;- CLANG_ENABLE_OBJC_WEAK = YES;- CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;- CLANG_WARN_BOOL_CONVERSION = YES;- CLANG_WARN_COMMA = YES;- CLANG_WARN_CONSTANT_CONVERSION = YES;- CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;- CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;- CLANG_WARN_DOCUMENTATION_COMMENTS = YES;- CLANG_WARN_EMPTY_BODY = YES;- CLANG_WARN_ENUM_CONVERSION = YES;- CLANG_WARN_INFINITE_RECURSION = YES;- CLANG_WARN_INT_CONVERSION = YES;- CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;- CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;- CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;- CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;- CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;- CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;- CLANG_WARN_STRICT_PROTOTYPES = YES;- CLANG_WARN_SUSPICIOUS_MOVE = YES;- CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;- CLANG_WARN_UNREACHABLE_CODE = YES;- CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;- COPY_PHASE_STRIP = NO;- DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";- ENABLE_NS_ASSERTIONS = NO;- ENABLE_STRICT_OBJC_MSGSEND = YES;- ENABLE_USER_SCRIPT_SANDBOXING = YES;- GCC_C_LANGUAGE_STANDARD = gnu17;- GCC_NO_COMMON_BLOCKS = YES;- GCC_WARN_64_TO_32_BIT_CONVERSION = YES;- GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;- GCC_WARN_UNDECLARED_SELECTOR = YES;- GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;- GCC_WARN_UNUSED_FUNCTION = YES;- GCC_WARN_UNUSED_VARIABLE = YES;- IPHONEOS_DEPLOYMENT_TARGET = 16.0;- MTL_ENABLE_DEBUG_INFO = NO;- MTL_FAST_MATH = YES;- SDKROOT = iphoneos;- SWIFT_COMPILATION_MODE = wholemodule;- VALIDATE_PRODUCT = YES;- };- name = Release;- };- 9F0000010000000000000803 /* Debug */ = {- isa = XCBuildConfiguration;- buildSettings = {- ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;- ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;- CODE_SIGN_ENTITLEMENTS = SidePulse/SidePulse.entitlements;- CODE_SIGN_STYLE = Automatic;- CURRENT_PROJECT_VERSION = 1;- DEVELOPMENT_ASSET_PATHS = "";- DEVELOPMENT_TEAM = "";- ENABLE_PREVIEWS = YES;- GENERATE_INFOPLIST_FILE = NO;- INFOPLIST_FILE = SidePulse/Info.plist;- INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;- INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;- INFOPLIST_KEY_UILaunchScreen_Generation = YES;- INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";- INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";- LD_RUNPATH_SEARCH_PATHS = (- "$(inherited)",- "@executable_path/Frameworks",- );- MARKETING_VERSION = 1.0;- PRODUCT_BUNDLE_IDENTIFIER = io.sidepulse.app;- PRODUCT_NAME = SidePulse;- SWIFT_EMIT_LOC_STRINGS = YES;- SWIFT_VERSION = 5.0;- TARGETED_DEVICE_FAMILY = "1,2";- };- name = Debug;- };- 9F0000010000000000000804 /* Release */ = {- isa = XCBuildConfiguration;- buildSettings = {- ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;- ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;- CODE_SIGN_ENTITLEMENTS = SidePulse/SidePulse.entitlements;- CODE_SIGN_STYLE = Automatic;- CURRENT_PROJECT_VERSION = 1;- DEVELOPMENT_ASSET_PATHS = "";- DEVELOPMENT_TEAM = "";- ENABLE_PREVIEWS = YES;- GENERATE_INFOPLIST_FILE = NO;- INFOPLIST_FILE = SidePulse/Info.plist;- INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;- INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;- INFOPLIST_KEY_UILaunchScreen_Generation = YES;- INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";- INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";- LD_RUNPATH_SEARCH_PATHS = (- "$(inherited)",- "@executable_path/Frameworks",- );- MARKETING_VERSION = 1.0;- PRODUCT_BUNDLE_IDENTIFIER = io.sidepulse.app;- PRODUCT_NAME = SidePulse;- SWIFT_EMIT_LOC_STRINGS = YES;- SWIFT_VERSION = 5.0;- TARGETED_DEVICE_FAMILY = "1,2";- };- name = Release;- };-/* End XCBuildConfiguration section */--/* Begin XCConfigurationList section */- 9F0000010000000000000901 /* Build configuration list for PBXProject "SidePulse" */ = {- isa = XCConfigurationList;- buildConfigurations = (- 9F0000010000000000000801 /* Debug */,- 9F0000010000000000000802 /* Release */,- );- defaultConfigurationIsVisible = 0;- defaultConfigurationName = Release;- };- 9F0000010000000000000902 /* Build configuration list for PBXNativeTarget "SidePulse" */ = {- isa = XCConfigurationList;- buildConfigurations = (- 9F0000010000000000000803 /* Debug */,- 9F0000010000000000000804 /* Release */,- );- defaultConfigurationIsVisible = 0;- defaultConfigurationName = Release;- };-/* End XCConfigurationList section */- };- rootObject = 9F0000010000000000000701 /* Project object */;-}diff --git a/ios/SidePulse/SidePulse/AppDelegate.swift b/ios/SidePulse/SidePulse/AppDelegate.swiftdeleted file mode 100644index cbda01c..0000000--- a/ios/SidePulse/SidePulse/AppDelegate.swift+++ /dev/null@@ -1,131 +0,0 @@-import Foundation-import UIKit-import UserNotifications--final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {- func application(- _ application: UIApplication,- didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil- ) -> Bool {- UNUserNotificationCenter.current().delegate = self- application.registerForRemoteNotifications()- EventLog.append("App launched; registered for remote notifications")-- if let userInfo = launchOptions?[.remoteNotification] as? [AnyHashable: Any] {- processNotification(userInfo, source: "Launch notification")- }-- return true- }-- func application(- _ application: UIApplication,- didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data- ) {- Task { @MainActor in- AppModel.shared.setPushToken(from: deviceToken)- }- }-- func application(- _ application: UIApplication,- didFailToRegisterForRemoteNotificationsWithError error: Error- ) {- EventLog.append("APNs registration failed: \(error.localizedDescription)")- Task { @MainActor in- AppModel.shared.recordError(error)- }- }-- func application(- _ application: UIApplication,- didReceiveRemoteNotification userInfo: [AnyHashable: Any],- fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void- ) {- let didHandle = processNotification(userInfo, source: "Background push")- completionHandler(didHandle ? .newData : .failed)- }-- func application(- _ app: UIApplication,- open url: URL,- options: [UIApplication.OpenURLOptionsKey: Any] = [:]- ) -> Bool {- guard let resolution = PushPayloadResolver.resolve(url: url) else {- return false- }-- return processResolvedPayload(resolution, source: "Shortcut URL")- }-- func userNotificationCenter(- _ center: UNUserNotificationCenter,- willPresent notification: UNNotification- ) async -> UNNotificationPresentationOptions {- [.banner, .sound]- }-- func userNotificationCenter(- _ center: UNUserNotificationCenter,- didReceive response: UNNotificationResponse- ) async {- processNotification(- response.notification.request.content.userInfo,- source: "Opened notification"- )- }-- @discardableResult- private func processNotification(_ userInfo: [AnyHashable: Any], source: String) -> Bool {- let keys = userInfo.keys.map { String(describing: $0) }.sorted().joined(separator: ",")- EventLog.append("\(source) received; keys=[\(keys)]")-- let resolution = PushPayloadResolver.resolve(userInfo: userInfo)- return processResolvedPayload(resolution, source: source)- }-- @discardableResult- private func processResolvedPayload(_ resolution: PushPayloadResolution, source: String) -> Bool {- var status: ReceivedPush.WriteStatus = .received- var errorMessage: String?-- if resolution.isUnsupportedPattern {- status = .unsupportedPattern- EventLog.append("\(source) stored unsupported pattern \(resolution.patternName ?? "")")- } else if let ledText = resolution.resolvedLEDText {- if DriveWriter.shared.hasSavedFolder {- do {- let targetURL = try DriveWriter.shared.write(ledText)- status = .wrote- EventLog.append("\(source) wrote \(targetURL.lastPathComponent)")- } catch {- status = .failed- errorMessage = error.localizedDescription- EventLog.append("\(source) failed: \(error.localizedDescription)")- }- } else {- status = .noFolder- EventLog.append("\(source) stored LED payload; no SidePulse Dot folder selected")- }- } else {- EventLog.append("\(source) stored general push")- }-- let push = ReceivedPush(- source: source,- title: resolution.displayTitle,- body: resolution.displayBody,- patternName: resolution.patternName,- ledText: resolution.resolvedLEDText,- payloadSummary: resolution.payloadSummary,- writeStatus: status,- errorMessage: errorMessage- )-- Task { @MainActor in- AppModel.shared.recordReceivedPush(push)- }-- return status != .failed- }-}diff --git a/ios/SidePulse/SidePulse/AppModel.swift b/ios/SidePulse/SidePulse/AppModel.swiftdeleted file mode 100644index 7f9a438..0000000--- a/ios/SidePulse/SidePulse/AppModel.swift+++ /dev/null@@ -1,215 +0,0 @@-import Foundation-import UIKit--@MainActor-final class AppModel: ObservableObject {- static let shared = AppModel()-- @Published var pushToken: String {- didSet { UserDefaults.standard.set(pushToken, forKey: Defaults.pushToken) }- }-- @Published var selectedFolderPath: String = "No USB folder selected"- @Published var hasFolderAccess: Bool = false-- @Published var ledText: String {- didSet { UserDefaults.standard.set(ledText, forKey: Defaults.ledText) }- }-- @Published var serverBaseURL: String {- didSet { UserDefaults.standard.set(serverBaseURL, forKey: Defaults.serverBaseURL) }- }-- @Published var sharedSecret: String {- didSet { UserDefaults.standard.set(sharedSecret, forKey: Defaults.sharedSecret) }- }-- @Published var lastMessage: String = "Ready"- @Published var eventLog: [String] = []- @Published var receivedPushes: [ReceivedPush] {- didSet { persistReceivedPushes() }- }-- private enum Defaults {- static let pushToken = "pushToken"- static let ledText = "ledText"- static let serverBaseURL = "serverBaseURL"- static let sharedSecret = "sharedSecret"- static let receivedPushes = "receivedPushes"- }-- private init() {- self.pushToken = UserDefaults.standard.string(forKey: Defaults.pushToken) ?? ""- self.ledText = UserDefaults.standard.string(forKey: Defaults.ledText) ?? """- #404040 1.4s pulse- off 400ms none- repeat- """- self.serverBaseURL = UserDefaults.standard.string(forKey: Defaults.serverBaseURL) ?? "http://127.0.0.1:8787"- self.sharedSecret = UserDefaults.standard.string(forKey: Defaults.sharedSecret) ?? ""- self.receivedPushes = Self.loadReceivedPushes()- self.eventLog = EventLog.entries()- refreshFolderStatus()- }-- func setPushToken(from deviceToken: Data) {- pushToken = deviceToken.map { String(format: "%02x", $0) }.joined()- EventLog.append("APNs token updated")- lastMessage = "Push token updated"- refreshEventLog()- }-- func refreshFolderStatus() {- hasFolderAccess = DriveWriter.shared.hasSavedFolder- selectedFolderPath = DriveWriter.shared.savedFolderDisplayName- }-- func recordWriteSuccess(_ message: String) {- EventLog.append(message)- lastMessage = message- refreshFolderStatus()- refreshEventLog()- }-- func recordError(_ error: Error) {- let message = error.localizedDescription- EventLog.append("Error: \(message)")- lastMessage = message- refreshFolderStatus()- refreshEventLog()- }-- func recordReceivedPush(_ push: ReceivedPush) {- var next = [push]- next.append(contentsOf: receivedPushes)- if next.count > 50 {- next.removeLast(next.count - 50)- }- receivedPushes = next-- let status = push.writeStatus.displayName- EventLog.append("\(push.source): \(push.title) (\(status))")- lastMessage = "\(push.title) - \(status)"- refreshFolderStatus()- refreshEventLog()- }-- func clearReceivedPushes() {- receivedPushes = []- lastMessage = "Cleared received pushes"- }-- func refreshEventLog() {- eventLog = EventLog.entries()- }-- func clearEventLog() {- EventLog.clear()- refreshEventLog()- }-- var preauthenticatedPostURL: String? {- let trimmedBase = serverBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)- .trimmingCharacters(in: CharacterSet(charactersIn: "/"))- guard !trimmedBase.isEmpty, !pushToken.isEmpty else {- return nil- }-- var components = URLComponents(string: trimmedBase + "/v1/push")- var items = [- URLQueryItem(name: "device_token", value: pushToken)- ]-- if !sharedSecret.isEmpty {- items.append(URLQueryItem(name: "key", value: sharedSecret))- }-- components?.queryItems = items- return components?.url?.absoluteString- }-- var pushEndpointURL: String? {- let trimmedBase = serverBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)- .trimmingCharacters(in: CharacterSet(charactersIn: "/"))- guard !trimmedBase.isEmpty else {- return nil- }- return trimmedBase + "/v1/push"- }-- var curlExample: String? {- guard let pushEndpointURL else {- return nil- }-- let tokenLine = pushToken.isEmpty ? "" : "\n -d '{\"device_token\":\"\(pushToken)\",\"pattern\":\"green_pulse_2\"}'"- let authHeader = sharedSecret.isEmpty ? "" : " \\\n -H \"Authorization: Bearer \(sharedSecret)\""- if tokenLine.isEmpty {- return """- curl -X POST \(pushEndpointURL)\(authHeader) \\- -H "content-type: application/json" \\- -d '{"pattern":"green_pulse_2"}'- """- }-- return """- curl -X POST \(pushEndpointURL)\(authHeader) \\- -H "content-type: application/json" \(tokenLine)- """- }-- var shortcutWriteURL: String? {- guard !ledText.isEmpty else {- return nil- }-- var components = URLComponents()- components.scheme = "sidepulse"- components.host = "write"- components.queryItems = [- URLQueryItem(name: "text", value: ledText)- ]- return components.url?.absoluteString- }-- func shortcutPatternURL(for pattern: LEDPattern) -> String? {- var components = URLComponents()- components.scheme = "sidepulse"- components.host = "write"- components.queryItems = [- URLQueryItem(name: "pattern", value: pattern.name)- ]- return components.url?.absoluteString- }-- private func persistReceivedPushes() {- if let data = try? JSONEncoder().encode(receivedPushes) {- UserDefaults.standard.set(data, forKey: Defaults.receivedPushes)- }- }-- private static func loadReceivedPushes() -> [ReceivedPush] {- guard let data = UserDefaults.standard.data(forKey: Defaults.receivedPushes),- let pushes = try? JSONDecoder().decode([ReceivedPush].self, from: data) else {- return []- }- return Array(pushes.prefix(50))- }-}--extension ReceivedPush.WriteStatus {- var displayName: String {- switch self {- case .received:- return "Received"- case .wrote:- return "Wrote LEDS.LED"- case .noFolder:- return "Folder needed"- case .failed:- return "Failed"- case .unsupportedPattern:- return "Unknown pattern"- }- }-}diff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AccentColor.colorset/Contents.json b/ios/SidePulse/SidePulse/Assets.xcassets/AccentColor.colorset/Contents.jsondeleted file mode 100644index eb87897..0000000--- a/ios/SidePulse/SidePulse/Assets.xcassets/AccentColor.colorset/Contents.json+++ /dev/null@@ -1,11 +0,0 @@-{- "colors" : [- {- "idiom" : "universal"- }- ],- "info" : {- "author" : "xcode",- "version" : 1- }-}diff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Contents.jsondeleted file mode 100644index 374b093..0000000--- a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Contents.json+++ /dev/null@@ -1,116 +0,0 @@-{- "images" : [- {- "filename" : "[email protected]",- "idiom" : "iphone",- "scale" : "2x",- "size" : "20x20"- },- {- "filename" : "[email protected]",- "idiom" : "iphone",- "scale" : "3x",- "size" : "20x20"- },- {- "filename" : "[email protected]",- "idiom" : "iphone",- "scale" : "2x",- "size" : "29x29"- },- {- "filename" : "[email protected]",- "idiom" : "iphone",- "scale" : "3x",- "size" : "29x29"- },- {- "filename" : "[email protected]",- "idiom" : "iphone",- "scale" : "2x",- "size" : "40x40"- },- {- "filename" : "[email protected]",- "idiom" : "iphone",- "scale" : "3x",- "size" : "40x40"- },- {- "filename" : "[email protected]",- "idiom" : "iphone",- "scale" : "2x",- "size" : "60x60"- },- {- "filename" : "[email protected]",- "idiom" : "iphone",- "scale" : "3x",- "size" : "60x60"- },- {- "filename" : "Icon-App-20x20@1x~ipad.png",- "idiom" : "ipad",- "scale" : "1x",- "size" : "20x20"- },- {- "filename" : "Icon-App-20x20@2x~ipad.png",- "idiom" : "ipad",- "scale" : "2x",- "size" : "20x20"- },- {- "filename" : "Icon-App-29x29@1x~ipad.png",- "idiom" : "ipad",- "scale" : "1x",- "size" : "29x29"- },- {- "filename" : "Icon-App-29x29@2x~ipad.png",- "idiom" : "ipad",- "scale" : "2x",- "size" : "29x29"- },- {- "filename" : "Icon-App-40x40@1x~ipad.png",- "idiom" : "ipad",- "scale" : "1x",- "size" : "40x40"- },- {- "filename" : "Icon-App-40x40@2x~ipad.png",- "idiom" : "ipad",- "scale" : "2x",- "size" : "40x40"- },- {- "filename" : "Icon-App-76x76@1x~ipad.png",- "idiom" : "ipad",- "scale" : "1x",- "size" : "76x76"- },- {- "filename" : "Icon-App-76x76@2x~ipad.png",- "idiom" : "ipad",- "scale" : "2x",- "size" : "76x76"- },- {- "filename" : "Icon-App-83.5x83.5@2x~ipad.png",- "idiom" : "ipad",- "scale" : "2x",- "size" : "83.5x83.5"- },- {- "filename" : "[email protected]",- "idiom" : "ios-marketing",- "scale" : "1x",- "size" : "1024x1024"- }- ],- "info" : {- "author" : "xcode",- "version" : 1- }-}diff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected]deleted file mode 100644index acbb0e7..0000000Binary files a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected] and /dev/null differdiff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x~ipad.png b/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x~ipad.pngdeleted file mode 100644index 50e9661..0000000Binary files a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x~ipad.png and /dev/null differdiff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected]deleted file mode 100644index e66f18c..0000000Binary files a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected] and /dev/null differdiff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x~ipad.png b/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x~ipad.pngdeleted file mode 100644index e66f18c..0000000Binary files a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x~ipad.png and /dev/null differdiff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected]deleted file mode 100644index 518b435..0000000Binary files a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected] and /dev/null differdiff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x~ipad.png b/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x~ipad.pngdeleted file mode 100644index 888668e..0000000Binary files a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x~ipad.png and /dev/null differdiff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected]deleted file mode 100644index b085ce1..0000000Binary files a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected] and /dev/null differdiff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x~ipad.png b/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x~ipad.pngdeleted file mode 100644index b085ce1..0000000Binary files a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x~ipad.png and /dev/null differdiff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected]deleted file mode 100644index 43966c2..0000000Binary files a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected] and /dev/null differdiff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x~ipad.png b/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x~ipad.pngdeleted file mode 100644index e66f18c..0000000Binary files a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x~ipad.png and /dev/null differdiff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected]deleted file mode 100644index 0ab6e63..0000000Binary files a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected] and /dev/null differdiff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x~ipad.png b/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x~ipad.pngdeleted file mode 100644index 0ab6e63..0000000Binary files a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x~ipad.png and /dev/null differdiff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected]deleted file mode 100644index 1b10f4c..0000000Binary files a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected] and /dev/null differdiff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected]deleted file mode 100644index 1b10f4c..0000000Binary files a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected] and /dev/null differdiff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected]deleted file mode 100644index 7d2ea8a..0000000Binary files a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/[email protected] and /dev/null differdiff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x~ipad.png b/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x~ipad.pngdeleted file mode 100644index 5737d59..0000000Binary files a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x~ipad.png and /dev/null differdiff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x~ipad.png b/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x~ipad.pngdeleted file mode 100644index 930b0e0..0000000Binary files a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x~ipad.png and /dev/null differdiff --git a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x~ipad.png b/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x~ipad.pngdeleted file mode 100644index 9862c50..0000000Binary files a/ios/SidePulse/SidePulse/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x~ipad.png and /dev/null differdiff --git a/ios/SidePulse/SidePulse/Assets.xcassets/Contents.json b/ios/SidePulse/SidePulse/Assets.xcassets/Contents.jsondeleted file mode 100644index 73c0059..0000000--- a/ios/SidePulse/SidePulse/Assets.xcassets/Contents.json+++ /dev/null@@ -1,6 +0,0 @@-{- "info" : {- "author" : "xcode",- "version" : 1- }-}diff --git a/ios/SidePulse/SidePulse/ContentView.swift b/ios/SidePulse/SidePulse/ContentView.swiftdeleted file mode 100644index 18c6841..0000000--- a/ios/SidePulse/SidePulse/ContentView.swift+++ /dev/null@@ -1,679 +0,0 @@-import SwiftUI-import UIKit-import UserNotifications--@MainActor-struct ContentView: View {- @StateObject private var model: AppModel- @State private var isShowingFolderPicker = false- @State private var activeSheet: ActiveSheet?-- init() {- _model = StateObject(wrappedValue: AppModel.shared)- }-- init(model: AppModel) {- _model = StateObject(wrappedValue: model)- }-- var body: some View {- NavigationStack {- ScrollView {- VStack(alignment: .leading, spacing: 16) {- HeaderPanel(model: model) {- activeSheet = .token- requestPushToken()- }-- RecentPushesPanel(pushes: Array(model.receivedPushes.prefix(5)))-- SidePulseDotSetupPanel(model: model) {- activeSheet = .folderSetup- }-- QuickPatternsPanel { pattern in- write(pattern)- }- }- .padding(16)- }- .background(Color(.systemGroupedBackground))- .navigationTitle("SidePulse")- .toolbar {- ToolbarItem(placement: .topBarTrailing) {- NavigationLink {- SettingsView(- model: model,- requestPushToken: requestPushToken,- showFolderPicker: showFolderPicker- )- } label: {- Image(systemName: "gearshape")- }- .accessibilityLabel("Settings")- }- }- }- .sheet(item: $activeSheet) { sheet in- switch sheet {- case .token:- TokenSheet(model: model, requestPushToken: requestPushToken)- case .folderSetup:- FolderSetupSheet {- showFolderPicker()- }- }- }- .sheet(isPresented: $isShowingFolderPicker) {- FolderPicker { url in- isShowingFolderPicker = false- do {- try DriveWriter.shared.saveFolder(url)- model.refreshFolderStatus()- model.lastMessage = "Selected \(url.lastPathComponent)"- } catch {- model.recordError(error)- }- } onCancel: {- isShowingFolderPicker = false- }- }- .onAppear {- model.refreshFolderStatus()- }- }-- private func requestPushToken() {- UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { _, error in- Task { @MainActor in- if let error {- model.recordError(error)- return- }-- UIApplication.shared.registerForRemoteNotifications()- model.lastMessage = "Registering with APNs"- }- }- }-- private func showFolderPicker() {- activeSheet = nil- DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {- isShowingFolderPicker = true- }- }-- private func write(_ pattern: LEDPattern) {- let pushBase = ReceivedPush(- source: "Quick Pattern",- title: pattern.displayName,- body: pattern.detail,- patternName: pattern.name,- ledText: pattern.ledText,- payloadSummary: "{\"pattern\":\"\(pattern.name)\"}",- writeStatus: .received- )-- guard model.hasFolderAccess else {- var push = pushBase- push.writeStatus = .noFolder- model.recordReceivedPush(push)- activeSheet = .folderSetup- return- }-- do {- let targetURL = try DriveWriter.shared.write(pattern.ledText)- var push = pushBase- push.body = "Wrote \(targetURL.lastPathComponent)"- push.writeStatus = .wrote- model.recordReceivedPush(push)- } catch {- var push = pushBase- push.writeStatus = .failed- push.errorMessage = error.localizedDescription- model.recordReceivedPush(push)- }- }-}--private enum ActiveSheet: Identifiable {- case token- case folderSetup-- var id: String {- switch self {- case .token:- return "token"- case .folderSetup:- return "folderSetup"- }- }-}--private struct HeaderPanel: View {- @ObservedObject var model: AppModel- let getToken: () -> Void-- var body: some View {- Panel {- VStack(alignment: .leading, spacing: 14) {- HStack(alignment: .top) {- VStack(alignment: .leading, spacing: 5) {- Label("SidePulse", systemImage: "dot.radiowaves.left.and.right")- .font(.title2.weight(.semibold))- Text("Push inbox and SidePulse Dot writer")- .font(.subheadline)- .foregroundStyle(.secondary)- }-- Spacer()-- StatusPill(isConnected: model.hasFolderAccess)- }-- Button {- getToken()- } label: {- Label(model.pushToken.isEmpty ? "Get Push Token" : "Show Push Token", systemImage: "key.horizontal")- .frame(maxWidth: .infinity)- }- .buttonStyle(.borderedProminent)- }- }- }-}--private struct StatusPill: View {- let isConnected: Bool-- var body: some View {- Label(isConnected ? "Folder connected" : "No folder", systemImage: isConnected ? "checkmark.circle.fill" : "exclamationmark.circle")- .font(.caption.weight(.semibold))- .foregroundStyle(isConnected ? Color.green : Color.orange)- .lineLimit(1)- }-}--private struct RecentPushesPanel: View {- let pushes: [ReceivedPush]-- var body: some View {- VStack(alignment: .leading, spacing: 10) {- HStack {- Text("Latest Pushes")- .font(.headline)- Spacer()- Text("\(pushes.count)")- .font(.caption.weight(.semibold))- .foregroundStyle(.secondary)- }-- if pushes.isEmpty {- EmptyInboxView()- } else {- VStack(spacing: 8) {- ForEach(pushes) { push in- ReceivedPushRow(push: push)- }- }- }- }- }-}--private struct EmptyInboxView: View {- var body: some View {- Panel {- HStack(spacing: 12) {- Image(systemName: "tray")- .font(.title3)- .foregroundStyle(.secondary)- .frame(width: 32, height: 32)-- VStack(alignment: .leading, spacing: 3) {- Text("No pushes received")- .font(.subheadline.weight(.semibold))- Text("SidePulse will store general pushes here even without a SidePulse Dot device.")- .font(.footnote)- .foregroundStyle(.secondary)- }- }- }- }-}--private struct ReceivedPushRow: View {- let push: ReceivedPush-- var body: some View {- Panel {- HStack(alignment: .top, spacing: 12) {- Image(systemName: push.writeStatus.symbolName)- .font(.headline)- .foregroundStyle(push.writeStatus.tint)- .frame(width: 28, height: 28)-- VStack(alignment: .leading, spacing: 5) {- HStack(alignment: .firstTextBaseline) {- Text(push.title)- .font(.subheadline.weight(.semibold))- .lineLimit(1)- Spacer(minLength: 8)- Text(push.receivedAt, style: .relative)- .font(.caption)- .foregroundStyle(.secondary)- }-- Text(push.body)- .font(.footnote)- .foregroundStyle(.secondary)- .lineLimit(2)-- HStack(spacing: 8) {- Text(push.writeStatus.displayName)- .font(.caption.weight(.medium))- .foregroundStyle(push.writeStatus.tint)-- if let patternName = push.patternName {- Text(patternName)- .font(.caption.monospaced())- .foregroundStyle(.secondary)- } else if push.ledByteCount > 0 {- Text("\(push.ledByteCount) bytes")- .font(.caption.monospaced())- .foregroundStyle(.secondary)- }- }- }- }- }- }-}--private struct SidePulseDotSetupPanel: View {- @ObservedObject var model: AppModel- let openSetup: () -> Void-- var body: some View {- Panel {- VStack(alignment: .leading, spacing: 12) {- HStack(alignment: .top, spacing: 12) {- Image(systemName: "externaldrive")- .font(.title2)- .foregroundStyle(model.hasFolderAccess ? Color.green : Color.accentColor)- .frame(width: 34, height: 34)-- VStack(alignment: .leading, spacing: 5) {- Text("SidePulse Dot Folder")- .font(.headline)- Text(model.selectedFolderPath)- .font(.footnote)- .foregroundStyle(.secondary)- .lineLimit(2)- }- }-- Button {- openSetup()- } label: {- Label(model.hasFolderAccess ? "Change LED Folder" : "Set Up SidePulse Dot Folder", systemImage: "folder.badge.plus")- .frame(maxWidth: .infinity)- }- .buttonStyle(.bordered)- }- }- }-}--private struct QuickPatternsPanel: View {- let writePattern: (LEDPattern) -> Void- private let columns = [- GridItem(.adaptive(minimum: 150), spacing: 10)- ]-- var body: some View {- VStack(alignment: .leading, spacing: 10) {- Text("Quick Patterns")- .font(.headline)-- LazyVGrid(columns: columns, spacing: 10) {- ForEach(LEDPatternCatalog.patterns) { pattern in- Button {- writePattern(pattern)- } label: {- PatternButtonLabel(pattern: pattern)- }- .buttonStyle(.plain)- }- }- }- }-}--private struct PatternButtonLabel: View {- let pattern: LEDPattern-- var body: some View {- Panel {- HStack(spacing: 10) {- Circle()- .fill(Color(hex: pattern.tintHex))- .frame(width: 12, height: 12)-- VStack(alignment: .leading, spacing: 3) {- Text(pattern.displayName)- .font(.subheadline.weight(.semibold))- .foregroundStyle(.primary)- .lineLimit(1)- Text(pattern.name)- .font(.caption.monospaced())- .foregroundStyle(.secondary)- .lineLimit(1)- }-- Spacer(minLength: 0)- }- .frame(maxWidth: .infinity, minHeight: 52, alignment: .leading)- }- }-}--private struct TokenSheet: View {- @ObservedObject var model: AppModel- let requestPushToken: () -> Void- @Environment(\.dismiss) private var dismiss-- var body: some View {- NavigationStack {- Form {- Section("Push Token") {- if model.pushToken.isEmpty {- Text("No token yet")- .foregroundStyle(.secondary)- } else {- Text(model.pushToken)- .font(.system(.footnote, design: .monospaced))- .textSelection(.enabled)-- Button {- UIPasteboard.general.string = model.pushToken- model.lastMessage = "Copied push token"- } label: {- Label("Copy Token", systemImage: "doc.on.doc")- }- }-- Button {- requestPushToken()- } label: {- Label("Request Token", systemImage: "bell.badge")- }- }- }- .navigationTitle("Push Token")- .toolbar {- ToolbarItem(placement: .topBarTrailing) {- Button("Done") {- dismiss()- }- }- }- }- }-}--private struct FolderSetupSheet: View {- let openPicker: () -> Void- @Environment(\.dismiss) private var dismiss-- var body: some View {- NavigationStack {- VStack(alignment: .leading, spacing: 18) {- Label("SidePulse Dot Device in Files", systemImage: "externaldrive")- .font(.title3.weight(.semibold))-- VStack(alignment: .leading, spacing: 10) {- Text("1. Attach the SidePulse Dot USB drive to this iPhone or iPad.")- Text("2. Open Files and select the SidePulse Dot USB drive folder containing LEDS.LED.")- Text("3. SidePulse will remember that folder for later pushes and Shortcuts.")- }- .font(.body)- .foregroundStyle(.secondary)-- Button {- dismiss()- openPicker()- } label: {- Label("Open Files", systemImage: "folder")- .frame(maxWidth: .infinity)- }- .buttonStyle(.borderedProminent)-- Spacer()- }- .padding(20)- .navigationTitle("Set Up Folder")- .toolbar {- ToolbarItem(placement: .topBarTrailing) {- Button("Done") {- dismiss()- }- }- }- }- }-}--private struct SettingsView: View {- @ObservedObject var model: AppModel- let requestPushToken: () -> Void- let showFolderPicker: () -> Void-- var body: some View {- Form {- Section("Push Token") {- Button {- requestPushToken()- } label: {- Label("Get Push Token", systemImage: "key.horizontal")- }-- if model.pushToken.isEmpty {- Text("No token yet")- .foregroundStyle(.secondary)- } else {- Text(model.pushToken)- .font(.system(.footnote, design: .monospaced))- .textSelection(.enabled)-- Button {- UIPasteboard.general.string = model.pushToken- model.lastMessage = "Copied push token"- } label: {- Label("Copy Token", systemImage: "doc.on.doc")- }- }- }-- Section("SidePulse Dot") {- LabeledContent("Folder", value: model.selectedFolderPath)-- Button {- showFolderPicker()- } label: {- Label("Set Up LED Folder", systemImage: "folder.badge.plus")- }- }-- Section("Advanced Server") {- TextField("Proxy base URL", text: $model.serverBaseURL)- .textInputAutocapitalization(.never)- .autocorrectionDisabled()- .keyboardType(.URL)-- SecureField("Shared secret", text: $model.sharedSecret)- .textInputAutocapitalization(.never)- .autocorrectionDisabled()-- if let endpoint = model.pushEndpointURL {- Text(endpoint)- .font(.system(.footnote, design: .monospaced))- .textSelection(.enabled)- }-- if let curlExample = model.curlExample {- Text(curlExample)- .font(.system(.caption, design: .monospaced))- .textSelection(.enabled)-- Button {- UIPasteboard.general.string = curlExample- model.lastMessage = "Copied curl example"- } label: {- Label("Copy Curl", systemImage: "terminal")- }- }- }-- Section("Raw LED Editor") {- TextEditor(text: $model.ledText)- .font(.system(.body, design: .monospaced))- .frame(minHeight: 140)-- Button {- writeLocalTest()- } label: {- Label("Write to USB", systemImage: "square.and.arrow.down")- }-- if let shortcutURL = model.shortcutWriteURL {- Button {- UIPasteboard.general.string = shortcutURL- model.lastMessage = "Copied Shortcut URL"- } label: {- Label("Copy Shortcut URL", systemImage: "link.badge.plus")- }- }- }-- Section("Diagnostics") {- Button {- model.refreshEventLog()- } label: {- Label("Refresh Log", systemImage: "arrow.clockwise")- }-- Button(role: .destructive) {- model.clearEventLog()- } label: {- Label("Clear Log", systemImage: "trash")- }-- if model.eventLog.isEmpty {- Text("No events")- .foregroundStyle(.secondary)- } else {- ForEach(model.eventLog.reversed(), id: \.self) { line in- Text(line)- .font(.system(.caption, design: .monospaced))- .textSelection(.enabled)- }- }- }-- Section("Inbox") {- Button(role: .destructive) {- model.clearReceivedPushes()- } label: {- Label("Clear Received Pushes", systemImage: "tray.and.arrow.down")- }- }- }- .navigationTitle("Settings")- }-- private func writeLocalTest() {- do {- let targetURL = try DriveWriter.shared.write(model.ledText)- model.recordWriteSuccess("Wrote \(targetURL.lastPathComponent)")- } catch {- model.recordError(error)- }- }-}--private struct Panel<Content: View>: View {- @ViewBuilder let content: () -> Content-- var body: some View {- content()- .padding(14)- .background(Color(.secondarySystemGroupedBackground))- .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))- }-}--private extension ReceivedPush.WriteStatus {- var symbolName: String {- switch self {- case .received:- return "tray.fill"- case .wrote:- return "checkmark.circle.fill"- case .noFolder:- return "folder.badge.questionmark"- case .failed:- return "xmark.octagon.fill"- case .unsupportedPattern:- return "questionmark.circle.fill"- }- }-- var tint: Color {- switch self {- case .received:- return .blue- case .wrote:- return .green- case .noFolder:- return .orange- case .failed:- return .red- case .unsupportedPattern:- return .purple- }- }-}--private extension Color {- init(hex: String) {- let cleaned = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)- var value: UInt64 = 0- Scanner(string: cleaned).scanHexInt64(&value)-- let red: UInt64- let green: UInt64- let blue: UInt64-- switch cleaned.count {- case 6:- red = (value >> 16) & 0xff- green = (value >> 8) & 0xff- blue = value & 0xff- default:- red = 0x3b- green = 0x82- blue = 0xf6- }-- self.init(- .sRGB,- red: Double(red) / 255,- green: Double(green) / 255,- blue: Double(blue) / 255,- opacity: 1- )- }-}diff --git a/ios/SidePulse/SidePulse/DriveWriter.swift b/ios/SidePulse/SidePulse/DriveWriter.swiftdeleted file mode 100644index 2328ff0..0000000--- a/ios/SidePulse/SidePulse/DriveWriter.swift+++ /dev/null@@ -1,175 +0,0 @@-import Foundation--enum DriveWriterError: LocalizedError {- case noFolderSelected- case bookmarkStale- case accessDenied- case textTooLarge(Int)- case tooManyLines(Int)- case missingText-- var errorDescription: String? {- switch self {- case .noFolderSelected:- return "Pick the USB drive folder first."- case .bookmarkStale:- return "The saved Files permission is stale. Pick the USB folder again."- case .accessDenied:- return "iOS did not grant access to the selected USB folder."- case .textTooLarge(let byteCount):- return "LEDS.LED is \(byteCount) bytes. Keep it at or below 512 bytes."- case .tooManyLines(let lineCount):- return "LEDS.LED has \(lineCount) physical lines. Keep it at or below 20 lines."- case .missingText:- return "No LED text was provided."- }- }-}--final class DriveWriter {- static let shared = DriveWriter()-- private let bookmarkKey = "usbFolderBookmark"- private let defaultFileName = "LEDS.LED"- private let maxLEDBytes = 512- private let maxLEDLines = 20-- private init() {}-- var fileName: String {- defaultFileName- }-- var hasSavedFolder: Bool {- UserDefaults.standard.data(forKey: bookmarkKey) != nil- }-- var savedFolderDisplayName: String {- guard let url = try? resolveFolderURL() else {- return "No USB folder selected"- }-- return url.path- }-- func saveFolder(_ url: URL) throws {- EventLog.append("Saving USB folder bookmark: \(url.lastPathComponent)")- let startedAccess = url.startAccessingSecurityScopedResource()- defer {- if startedAccess {- url.stopAccessingSecurityScopedResource()- }- }-- let bookmark = try url.bookmarkData(- options: [],- includingResourceValuesForKeys: nil,- relativeTo: nil- )- UserDefaults.standard.set(bookmark, forKey: bookmarkKey)- EventLog.append("Saved USB folder bookmark")- }-- @discardableResult- func write(_ text: String) throws -> URL {- let program = normalizeLEDText(text)- let trimmed = program.trimmingCharacters(in: .whitespacesAndNewlines)- guard !trimmed.isEmpty else {- throw DriveWriterError.missingText- }-- let byteCount = program.data(using: .utf8)?.count ?? 0- guard byteCount <= maxLEDBytes else {- throw DriveWriterError.textTooLarge(byteCount)- }-- let lineCount = physicalLineCount(program)- guard lineCount <= maxLEDLines else {- throw DriveWriterError.tooManyLines(lineCount)- }-- let folderURL = try resolveFolderURL()- let startedAccess = folderURL.startAccessingSecurityScopedResource()- guard startedAccess else {- throw DriveWriterError.accessDenied- }-- defer {- folderURL.stopAccessingSecurityScopedResource()- }-- let targetURL = folderURL.appendingPathComponent(fileName, isDirectory: false)- let data = Data(program.utf8)- try data.write(to: targetURL)- EventLog.append("Wrote \(data.count) bytes to \(targetURL.lastPathComponent)")- return targetURL- }-- private func resolveFolderURL() throws -> URL {- guard let bookmark = UserDefaults.standard.data(forKey: bookmarkKey) else {- throw DriveWriterError.noFolderSelected- }-- var isStale = false- let url = try URL(- resolvingBookmarkData: bookmark,- options: [],- relativeTo: nil,- bookmarkDataIsStale: &isStale- )-- if isStale {- throw DriveWriterError.bookmarkStale- }-- return url- }-- private func physicalLineCount(_ text: String) -> Int {- let normalized = text- .replacingOccurrences(of: "\r\n", with: "\n")- .replacingOccurrences(of: "\r", with: "\n")- var lines = normalized.split(separator: "\n", omittingEmptySubsequences: false).count- if normalized.hasSuffix("\n") {- lines -= 1- }- return max(lines, 1)- }-- private func normalizeLEDText(_ text: String) -> String {- var output = ""- var index = text.startIndex-- while index < text.endIndex {- let character = text[index]- guard character == "\\",- let nextIndex = text.index(index, offsetBy: 1, limitedBy: text.endIndex),- nextIndex < text.endIndex else {- output.append(character)- index = text.index(after: index)- continue- }-- let nextCharacter = text[nextIndex]- switch nextCharacter {- case "n":- output.append("\n")- index = text.index(after: nextIndex)- case "r":- output.append("\r")- index = text.index(after: nextIndex)- case "t":- output.append("\t")- index = text.index(after: nextIndex)- case "\\":- output.append("\\")- index = text.index(after: nextIndex)- default:- output.append(character)- index = text.index(after: index)- }- }-- return output- }-}diff --git a/ios/SidePulse/SidePulse/EventLog.swift b/ios/SidePulse/SidePulse/EventLog.swiftdeleted file mode 100644index e07d48a..0000000--- a/ios/SidePulse/SidePulse/EventLog.swift+++ /dev/null@@ -1,30 +0,0 @@-import Foundation-import OSLog--enum EventLog {- private static let logger = Logger(subsystem: "io.sidepulse.app", category: "SidePulse")- private static let defaultsKey = "eventLog"- private static let maxEntries = 40-- static func append(_ message: String) {- let timestamp = ISO8601DateFormatter().string(from: Date())- let line = "\(timestamp) \(message)"- logger.info("\(line, privacy: .public)")-- let defaults = UserDefaults.standard- var entries = defaults.stringArray(forKey: defaultsKey) ?? []- entries.append(line)- if entries.count > maxEntries {- entries.removeFirst(entries.count - maxEntries)- }- defaults.set(entries, forKey: defaultsKey)- }-- static func entries() -> [String] {- UserDefaults.standard.stringArray(forKey: defaultsKey) ?? []- }-- static func clear() {- UserDefaults.standard.removeObject(forKey: defaultsKey)- }-}diff --git a/ios/SidePulse/SidePulse/FolderPicker.swift b/ios/SidePulse/SidePulse/FolderPicker.swiftdeleted file mode 100644index 242f91a..0000000--- a/ios/SidePulse/SidePulse/FolderPicker.swift+++ /dev/null@@ -1,41 +0,0 @@-import SwiftUI-import UniformTypeIdentifiers--struct FolderPicker: UIViewControllerRepresentable {- let onPick: (URL) -> Void- let onCancel: () -> Void-- func makeUIViewController(context: Context) -> UIDocumentPickerViewController {- let picker = UIDocumentPickerViewController(forOpeningContentTypes: [.folder], asCopy: false)- picker.allowsMultipleSelection = false- picker.delegate = context.coordinator- return picker- }-- func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {}-- func makeCoordinator() -> Coordinator {- Coordinator(parent: self)- }-- final class Coordinator: NSObject, UIDocumentPickerDelegate {- private let parent: FolderPicker-- init(parent: FolderPicker) {- self.parent = parent- }-- func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {- guard let url = urls.first else {- parent.onCancel()- return- }-- parent.onPick(url)- }-- func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {- parent.onCancel()- }- }-}diff --git a/ios/SidePulse/SidePulse/Info.plist b/ios/SidePulse/SidePulse/Info.plistdeleted file mode 100644index 5798b60..0000000--- a/ios/SidePulse/SidePulse/Info.plist+++ /dev/null@@ -1,60 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>CFBundleDevelopmentRegion</key>- <string>$(DEVELOPMENT_LANGUAGE)</string>- <key>CFBundleDisplayName</key>- <string>SidePulse</string>- <key>CFBundleExecutable</key>- <string>$(EXECUTABLE_NAME)</string>- <key>CFBundleIdentifier</key>- <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>- <key>CFBundleInfoDictionaryVersion</key>- <string>6.0</string>- <key>CFBundleName</key>- <string>$(PRODUCT_NAME)</string>- <key>CFBundlePackageType</key>- <string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>- <key>CFBundleShortVersionString</key>- <string>1.0</string>- <key>CFBundleURLTypes</key>- <array>- <dict>- <key>CFBundleURLName</key>- <string>io.sidepulse.app.url</string>- <key>CFBundleURLSchemes</key>- <array>- <string>sidepulse</string>- </array>- </dict>- </array>- <key>CFBundleVersion</key>- <string>1</string>- <key>LSRequiresIPhoneOS</key>- <true/>- <key>LSSupportsOpeningDocumentsInPlace</key>- <true/>- <key>UIApplicationSupportsIndirectInputEvents</key>- <true/>- <key>UIBackgroundModes</key>- <array>- <string>remote-notification</string>- </array>- <key>UILaunchScreen</key>- <dict/>- <key>UISupportedInterfaceOrientations</key>- <array>- <string>UIInterfaceOrientationPortrait</string>- <string>UIInterfaceOrientationLandscapeLeft</string>- <string>UIInterfaceOrientationLandscapeRight</string>- </array>- <key>UISupportedInterfaceOrientations~ipad</key>- <array>- <string>UIInterfaceOrientationPortrait</string>- <string>UIInterfaceOrientationPortraitUpsideDown</string>- <string>UIInterfaceOrientationLandscapeLeft</string>- <string>UIInterfaceOrientationLandscapeRight</string>- </array>-</dict>-</plist>diff --git a/ios/SidePulse/SidePulse/PushPayload.swift b/ios/SidePulse/SidePulse/PushPayload.swiftdeleted file mode 100644index 0927fc6..0000000--- a/ios/SidePulse/SidePulse/PushPayload.swift+++ /dev/null@@ -1,301 +0,0 @@-import Foundation--struct LEDPattern: Identifiable, Codable, Hashable {- let name: String- let displayName: String- let detail: String- let ledText: String- let tintHex: String-- var id: String { name }-- var byteCount: Int {- ledText.data(using: .utf8)?.count ?? 0- }-}--enum LEDPatternCatalog {- static let patterns: [LEDPattern] = [- LEDPattern(- name: "off",- displayName: "Off",- detail: "Clear the LEDs",- ledText: "off\n",- tintHex: "#6b7280"- ),- LEDPattern(- name: "green_pulse_2",- displayName: "Two Green Pulses",- detail: "Two quick confirmation pulses",- ledText: "#00ff00 280ms pulse\noff 160ms none\n#00ff00 280ms pulse\noff 320ms none\n",- tintHex: "#20c997"- ),- LEDPattern(- name: "success",- displayName: "Success",- detail: "Soft green success glow",- ledText: "#00ff66 450ms cosine\noff 160ms none\n",- tintHex: "#22c55e"- ),- LEDPattern(- name: "error",- displayName: "Error",- detail: "Red attention blink",- ledText: "#ff1f3d 120ms none\noff 120ms none\nrepeat 3\n",- tintHex: "#ef4444"- ),- LEDPattern(- name: "working",- displayName: "Working",- detail: "Blue activity pulse",- ledText: "#0066ff 900ms pulse\n#00ccff 900ms pulse\nrepeat\n",- tintHex: "#0ea5e9"- ),- LEDPattern(- name: "waiting",- displayName: "Waiting",- detail: "Amber waiting breath",- ledText: "#ffaa00 1.2s pulse\noff 500ms none\nrepeat\n",- tintHex: "#f59e0b"- ),- LEDPattern(- name: "white_breathe",- displayName: "White Breathe",- detail: "Soft neutral breathing",- ledText: "#404040 1.4s pulse\noff 400ms none\nrepeat\n",- tintHex: "#f8fafc"- )- ]-- static func pattern(named name: String?) -> LEDPattern? {- guard let name else {- return nil- }-- let normalized = name.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()- return patterns.first { $0.name.lowercased() == normalized }- }-}--struct ReceivedPush: Identifiable, Codable, Hashable {- enum WriteStatus: String, Codable, Hashable {- case received- case wrote- case noFolder- case failed- case unsupportedPattern- }-- var id: UUID = UUID()- var receivedAt: Date = Date()- var source: String- var title: String- var body: String- var patternName: String?- var ledText: String?- var payloadSummary: String- var writeStatus: WriteStatus- var errorMessage: String?-- var ledByteCount: Int {- ledText?.data(using: .utf8)?.count ?? 0- }-}--struct PushPayloadResolution {- let sourceTitle: String- let sourceBody: String- let patternName: String?- let pattern: LEDPattern?- let ledText: String?- let payloadSummary: String-- var resolvedLEDText: String? {- ledText ?? pattern?.ledText- }-- var isUnsupportedPattern: Bool {- patternName != nil && pattern == nil && ledText == nil- }-- var displayTitle: String {- if !sourceTitle.isEmpty {- return sourceTitle- }- if let pattern {- return pattern.displayName- }- if isUnsupportedPattern {- return "Unknown Pattern"- }- if ledText != nil {- return "LEDS.LED Push"- }- return "Push Received"- }-- var displayBody: String {- if !sourceBody.isEmpty {- return sourceBody- }- if let pattern {- return pattern.detail- }- if let patternName {- return patternName- }- if let ledText {- let byteCount = ledText.data(using: .utf8)?.count ?? 0- return "\(byteCount) bytes"- }- return payloadSummary- }-}--enum PushPayloadResolver {- private static let ledKeys = ["leds", "LEDS.LED", "LEDS.led", "text"]-- static func resolve(userInfo: [AnyHashable: Any]) -> PushPayloadResolution {- let payload = normalizedDictionary(userInfo)- let candidates = candidateDictionaries(from: payload)- let ledText = firstString(in: candidates, keys: ledKeys)- let requestedPattern = firstString(in: candidates, keys: ["pattern"])- let pattern = ledText == nil ? LEDPatternCatalog.pattern(named: requestedPattern) : nil- let alert = alertText(from: payload)-- return PushPayloadResolution(- sourceTitle: alert.title,- sourceBody: alert.body,- patternName: requestedPattern,- pattern: pattern,- ledText: ledText,- payloadSummary: summary(from: payload)- )- }-- static func resolve(url: URL) -> PushPayloadResolution? {- guard url.scheme == "sidepulse" else {- return nil- }-- let command = url.host ?? url.path.trimmingCharacters(in: CharacterSet(charactersIn: "/"))- guard command == "write" else {- return nil- }-- let components = URLComponents(url: url, resolvingAgainstBaseURL: false)- var payload: [String: Any] = [:]- components?.queryItems?.forEach { item in- payload[item.name] = item.value ?? ""- }-- guard !payload.isEmpty else {- return nil- }-- var userInfo: [AnyHashable: Any] = [:]- payload.forEach { key, value in- userInfo[AnyHashable(key)] = value- }- return resolve(userInfo: userInfo)- }-- private static func candidateDictionaries(from payload: [String: Any]) -> [[String: Any]] {- var dictionaries = [payload]- for key in ["payload", "data"] {- if let nested = payload[key] as? [String: Any] {- dictionaries.append(nested)- }- }- return dictionaries- }-- private static func firstString(in dictionaries: [[String: Any]], keys: [String]) -> String? {- for dictionary in dictionaries {- for key in keys {- if let value = dictionary[key] as? String {- let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)- return trimmed.isEmpty ? value : value- }- }- }- return nil- }-- private static func alertText(from payload: [String: Any]) -> (title: String, body: String) {- let directTitle = payload["title"] as? String ?? ""- let directBody = payload["body"] as? String ?? ""-- guard let aps = payload["aps"] as? [String: Any] else {- return (directTitle, directBody)- }-- if let alert = aps["alert"] as? String {- return (directTitle, directBody.isEmpty ? alert : directBody)- }-- if let alert = aps["alert"] as? [String: Any] {- return (- directTitle.isEmpty ? (alert["title"] as? String ?? "") : directTitle,- directBody.isEmpty ? (alert["body"] as? String ?? "") : directBody- )- }-- return (directTitle, directBody)- }-- private static func summary(from payload: [String: Any]) -> String {- let visiblePayload = payload.filter { key, _ in- key != "aps"- }-- guard !visiblePayload.isEmpty else {- return "APNs notification"- }-- if JSONSerialization.isValidJSONObject(visiblePayload),- let data = try? JSONSerialization.data(withJSONObject: visiblePayload, options: [.sortedKeys]),- let json = String(data: data, encoding: .utf8) {- return truncated(json)- }-- return truncated(visiblePayload.keys.sorted().joined(separator: ", "))- }-- private static func truncated(_ value: String) -> String {- guard value.count > 280 else {- return value- }-- let endIndex = value.index(value.startIndex, offsetBy: 280)- return String(value[..<endIndex]) + "..."- }-- private static func normalizedDictionary(_ input: [AnyHashable: Any]) -> [String: Any] {- var output: [String: Any] = [:]- for (key, value) in input {- output[String(describing: key)] = normalizedValue(value)- }- return output- }-- private static func normalizedValue(_ value: Any) -> Any {- if let dictionary = value as? [AnyHashable: Any] {- return normalizedDictionary(dictionary)- }-- if let dictionary = value as? NSDictionary {- var output: [String: Any] = [:]- dictionary.forEach { key, value in- output[String(describing: key)] = normalizedValue(value)- }- return output- }-- if let array = value as? [Any] {- return array.map { normalizedValue($0) }- }-- return value- }-}diff --git a/ios/SidePulse/SidePulse/SidePulse.entitlements b/ios/SidePulse/SidePulse/SidePulse.entitlementsdeleted file mode 100644index 2cf0210..0000000--- a/ios/SidePulse/SidePulse/SidePulse.entitlements+++ /dev/null@@ -1,8 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>aps-environment</key>- <string>development</string>-</dict>-</plist>diff --git a/ios/SidePulse/SidePulse/SidePulseApp.swift b/ios/SidePulse/SidePulse/SidePulseApp.swiftdeleted file mode 100644index 4867e02..0000000--- a/ios/SidePulse/SidePulse/SidePulseApp.swift+++ /dev/null@@ -1,12 +0,0 @@-import SwiftUI--@main-struct SidePulseApp: App {- @UIApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate-- var body: some Scene {- WindowGroup {- ContentView()- }- }-}diff --git a/ios/SidePulse/SidePulse/WriteLEDsIntent.swift b/ios/SidePulse/SidePulse/WriteLEDsIntent.swiftdeleted file mode 100644index 7635e19..0000000--- a/ios/SidePulse/SidePulse/WriteLEDsIntent.swift+++ /dev/null@@ -1,41 +0,0 @@-import AppIntents-import Foundation--@available(iOS 16.0, *)-struct WriteLEDsIntent: AppIntent {- static var title: LocalizedStringResource = "Write SidePulse LEDS.LED"- static var description = IntentDescription("Writes the supplied LED program to LEDS.LED on the selected USB drive.")- static var openAppWhenRun = false-- @Parameter(title: "LEDS.LED Text")- var ledsText: String-- init() {}-- init(ledsText: String) {- self.ledsText = ledsText- }-- func perform() async throws -> some IntentResult {- _ = try DriveWriter.shared.write(ledsText)- await MainActor.run {- AppModel.shared.recordWriteSuccess("Shortcut wrote LEDS.LED")- }- return .result()- }-}--@available(iOS 16.0, *)-struct SidePulseShortcuts: AppShortcutsProvider {- static var appShortcuts: [AppShortcut] {- AppShortcut(- intent: WriteLEDsIntent(),- phrases: [- "Write \(.applicationName) LEDs",- "Send \(.applicationName) LEDs"- ],- shortTitle: "Write LEDs",- systemImageName: "externaldrive"- )- }-}diff --git a/ios/SidePulse/SidePulseIconSource.png b/ios/SidePulse/SidePulseIconSource.pngdeleted file mode 100644index acbb0e7..0000000Binary files a/ios/SidePulse/SidePulseIconSource.png and /dev/null differdiff --git a/ios/SidePulse/examples/LEDS.example.led b/ios/SidePulse/examples/LEDS.example.leddeleted file mode 100644index 4ad13f5..0000000--- a/ios/SidePulse/examples/LEDS.example.led+++ /dev/null@@ -1,3 +0,0 @@-#404040 1.4s pulse-off 400ms none-repeatdiff --git a/ios/SidePulse/tools/.gitignore b/ios/SidePulse/tools/.gitignoredeleted file mode 100644index 7e0e243..0000000--- a/ios/SidePulse/tools/.gitignore+++ /dev/null@@ -1,5 +0,0 @@-.venv/-__pycache__/-*.pyc-*.env-sidepulse.envdiff --git a/ios/SidePulse/tools/apns_client.py b/ios/SidePulse/tools/apns_client.pydeleted file mode 100644index c80c82f..0000000--- a/ios/SidePulse/tools/apns_client.py+++ /dev/null@@ -1,278 +0,0 @@-from __future__ import annotations--import base64-import json-import os-import time-from dataclasses import dataclass-from pathlib import Path-from typing import Any--import httpx-from cryptography.hazmat.primitives import hashes, serialization-from cryptography.hazmat.primitives.asymmetric import ec, utils---MAX_LEDS_BYTES = 512-MAX_LEDS_LINES = 20-APNS_JWT_REFRESH_SECONDS = 50 * 60---class APNsConfigError(RuntimeError):- pass---class LEDPayloadError(ValueError):- pass---@dataclass(frozen=True)-class APNsConfig:- team_id: str- key_id: str- auth_key_path: Path- bundle_id: str- environment: str = "sandbox"-- @classmethod- def from_env(cls) -> "APNsConfig":- missing = [- name- for name in ("APNS_TEAM_ID", "APNS_KEY_ID", "APNS_AUTH_KEY", "APNS_BUNDLE_ID")- if not os.environ.get(name)- ]- if missing:- raise APNsConfigError(f"Missing environment variables: {', '.join(missing)}")-- return cls(- team_id=os.environ["APNS_TEAM_ID"],- key_id=os.environ["APNS_KEY_ID"],- auth_key_path=Path(os.environ["APNS_AUTH_KEY"]).expanduser(),- bundle_id=os.environ["APNS_BUNDLE_ID"],- environment=os.environ.get("APNS_ENV", "sandbox"),- )-- @property- def host(self) -> str:- if self.environment.lower() in {"prod", "production"}:- return "api.push.apple.com"- return "api.sandbox.push.apple.com"---@dataclass(frozen=True)-class APNsResponse:- status_code: int- apns_id: str | None- body: dict[str, Any] | str-- @property- def ok(self) -> bool:- return 200 <= self.status_code < 300---class APNsProviderTokenCache:- def __init__(self, config: APNsConfig) -> None:- self.config = config- self._private_key: ec.EllipticCurvePrivateKey | None = None- self._token: str | None = None- self._refresh_at = 0-- def token(self) -> str:- now = int(time.time())- if self._token and now < self._refresh_at:- return self._token-- private_key = self._load_private_key()- self._token = make_provider_token(self.config, issued_at=now, private_key=private_key)- self._refresh_at = now + APNS_JWT_REFRESH_SECONDS- return self._token-- def _load_private_key(self) -> ec.EllipticCurvePrivateKey:- if self._private_key is not None:- return self._private_key-- private_key = serialization.load_pem_private_key(- self.config.auth_key_path.read_bytes(),- password=None,- )-- if not isinstance(private_key, ec.EllipticCurvePrivateKey):- raise APNsConfigError("APNs auth key must be an EC private key")-- self._private_key = private_key- return private_key---class APNsClient:- def __init__(- self,- config: APNsConfig,- *,- client: httpx.AsyncClient | None = None,- timeout: float = 10.0,- ) -> None:- self.config = config- self._token_cache = APNsProviderTokenCache(config)- self._owns_client = client is None- self._client = client or httpx.AsyncClient(- http2=True,- timeout=httpx.Timeout(timeout),- limits=httpx.Limits(max_connections=1000, max_keepalive_connections=250),- )-- async def __aenter__(self) -> "APNsClient":- return self-- async def __aexit__(self, *_: object) -> None:- await self.aclose()-- async def aclose(self) -> None:- if self._owns_client:- await self._client.aclose()-- async def send(- self,- device_token: str,- payload: dict[str, Any],- *,- headers: dict[str, str] | None = None,- ) -> APNsResponse:- token = device_token.strip()- if not token:- raise ValueError("Missing device token")-- request_headers = {- "authorization": f"bearer {self._token_cache.token()}",- "apns-topic": self.config.bundle_id,- "apns-push-type": "background",- "apns-priority": "5",- }- if headers:- request_headers.update({key: str(value) for key, value in headers.items() if value is not None})-- url = f"https://{self.config.host}/3/device/{token}"- response = await self._client.post(url, headers=request_headers, json=payload)-- try:- body: dict[str, Any] | str = response.json()- except json.JSONDecodeError:- body = response.text-- return APNsResponse(- status_code=response.status_code,- apns_id=response.headers.get("apns-id"),- body=body,- )---def validate_leds_text(leds_text: str) -> None:- if not leds_text.strip():- raise LEDPayloadError("LEDS.LED payload is empty")-- byte_count = len(leds_text.encode("utf-8"))- if byte_count > MAX_LEDS_BYTES:- raise LEDPayloadError(f"LEDS.LED payload is {byte_count} bytes; max is {MAX_LEDS_BYTES}")-- line_count = len(leds_text.splitlines()) or 1- if line_count > MAX_LEDS_LINES:- raise LEDPayloadError(f"LEDS.LED payload has {line_count} lines; max is {MAX_LEDS_LINES}")---def normalize_leds_text(leds_text: str) -> str:- return decode_simple_escapes(leds_text)---def decode_simple_escapes(text: str) -> str:- output: list[str] = []- index = 0- while index < len(text):- char = text[index]- if char != "\\" or index + 1 >= len(text):- output.append(char)- index += 1- continue-- next_char = text[index + 1]- if next_char == "n":- output.append("\n")- index += 2- elif next_char == "r":- output.append("\r")- index += 2- elif next_char == "t":- output.append("\t")- index += 2- elif next_char == "\\":- output.append("\\")- index += 2- else:- output.append(char)- index += 1- return "".join(output)---def make_provider_token(- config: APNsConfig,- issued_at: int | None = None,- *,- private_key: ec.EllipticCurvePrivateKey | None = None,-) -> str:- issued_at = issued_at or int(time.time())- private_key = private_key or serialization.load_pem_private_key(- config.auth_key_path.read_bytes(),- password=None,- )-- if not isinstance(private_key, ec.EllipticCurvePrivateKey):- raise APNsConfigError("APNs auth key must be an EC private key")-- header = {"alg": "ES256", "kid": config.key_id}- claims = {"iss": config.team_id, "iat": issued_at}- signing_input = b".".join(- [- _b64url_json(header),- _b64url_json(claims),- ]- )- der_signature = private_key.sign(signing_input, ec.ECDSA(hashes.SHA256()))- r_value, s_value = utils.decode_dss_signature(der_signature)- raw_signature = r_value.to_bytes(32, "big") + s_value.to_bytes(32, "big")- return signing_input.decode("ascii") + "." + _b64url(raw_signature).decode("ascii")---async def send_leds_push(- config: APNsConfig,- device_token: str,- leds_text: str,- *,- alert: str | None = None,-) -> APNsResponse:- leds_text = normalize_leds_text(leds_text)- validate_leds_text(leds_text)-- push_type = "alert" if alert else "background"- priority = "10" if alert else "5"- aps: dict[str, Any] = {"content-available": 1}- if alert:- aps["alert"] = {"title": "SidePulse", "body": alert}- aps["sound"] = "default"-- payload = {- "aps": aps,- "leds": leds_text,- }- headers = {- "apns-push-type": push_type,- "apns-priority": priority,- }-- async with APNsClient(config) as client:- return await client.send(device_token, payload, headers=headers)---def _b64url_json(value: dict[str, Any]) -> bytes:- return _b64url(json.dumps(value, separators=(",", ":")).encode("utf-8"))---def _b64url(value: bytes) -> bytes:- return base64.urlsafe_b64encode(value).rstrip(b"=")diff --git a/ios/SidePulse/tools/patterns.py b/ios/SidePulse/tools/patterns.pydeleted file mode 100644index 41e05b1..0000000--- a/ios/SidePulse/tools/patterns.py+++ /dev/null@@ -1,70 +0,0 @@-from __future__ import annotations--from dataclasses import dataclass, asdict---@dataclass(frozen=True)-class LEDPattern:- name: str- display_name: str- detail: str- leds: str-- @property- def byte_count(self) -> int:- return len(self.leds.encode("utf-8"))-- def as_public_dict(self) -> dict[str, object]:- payload = asdict(self)- payload["byte_count"] = self.byte_count- return payload---PATTERNS: dict[str, LEDPattern] = {- "off": LEDPattern(- name="off",- display_name="Off",- detail="Clear the LEDs",- leds="off\n",- ),- "green_pulse_2": LEDPattern(- name="green_pulse_2",- display_name="Two Green Pulses",- detail="Two quick confirmation pulses",- leds="#00ff00 280ms pulse\noff 160ms none\n#00ff00 280ms pulse\noff 320ms none\n",- ),- "success": LEDPattern(- name="success",- display_name="Success",- detail="Soft green success glow",- leds="#00ff66 450ms cosine\noff 160ms none\n",- ),- "error": LEDPattern(- name="error",- display_name="Error",- detail="Red attention blink",- leds="#ff1f3d 120ms none\noff 120ms none\nrepeat 3\n",- ),- "working": LEDPattern(- name="working",- display_name="Working",- detail="Blue activity pulse",- leds="#0066ff 900ms pulse\n#00ccff 900ms pulse\nrepeat\n",- ),- "waiting": LEDPattern(- name="waiting",- display_name="Waiting",- detail="Amber waiting breath",- leds="#ffaa00 1.2s pulse\noff 500ms none\nrepeat\n",- ),- "white_breathe": LEDPattern(- name="white_breathe",- display_name="White Breathe",- detail="Soft neutral breathing",- leds="#404040 1.4s pulse\noff 400ms none\nrepeat\n",- ),-}---def pattern_names() -> list[str]:- return list(PATTERNS)diff --git a/ios/SidePulse/tools/requirements.txt b/ios/SidePulse/tools/requirements.txtdeleted file mode 100644index ba1e45a..0000000--- a/ios/SidePulse/tools/requirements.txt+++ /dev/null@@ -1,4 +0,0 @@-cryptography>=42.0-fastapi>=0.115-httpx[http2]>=0.27-uvicorn[standard]>=0.30diff --git a/ios/SidePulse/tools/send_push.py b/ios/SidePulse/tools/send_push.pydeleted file mode 100644index 8ef7bfb..0000000--- a/ios/SidePulse/tools/send_push.py+++ /dev/null@@ -1,70 +0,0 @@-#!/usr/bin/env python3-from __future__ import annotations--import argparse-import json-import os-import sys-from pathlib import Path-from urllib.error import HTTPError, URLError-from urllib.request import Request, urlopen---def main() -> int:- parser = argparse.ArgumentParser(description="Send a SidePulse push through the local push server.")- parser.add_argument("--server", default=os.environ.get("SIDEPULSE_SERVER_URL", "http://127.0.0.1:8787"))- parser.add_argument("--secret", default=os.environ.get("SIDEPULSE_SHARED_SECRET"))- parser.add_argument("--device-token", default=os.environ.get("SIDEPULSE_DEVICE_TOKEN"))- parser.add_argument("--pattern", default="green_pulse_2")- parser.add_argument("--leds", help="Inline LEDS.LED text. If set, this wins over pattern in the app.")- parser.add_argument("--file", type=Path, help="Path to a LEDS.LED file.")- parser.add_argument("--payload", help="Extra JSON object merged into the APNs payload.")- parser.add_argument("--alert", help="Optional visible notification body.")- args = parser.parse_args()-- if args.leds and args.file:- parser.error("Use either --leds or --file, not both")-- payload: dict[str, object] = {}- if args.payload:- loaded = json.loads(args.payload)- if not isinstance(loaded, dict):- parser.error("--payload must be a JSON object")- payload = loaded-- body: dict[str, object] = {- "pattern": args.pattern,- }- if args.device_token:- body["device_token"] = args.device_token- if args.alert:- body["alert"] = args.alert- if payload:- body["payload"] = payload-- if args.leds is not None:- body["leds"] = args.leds- elif args.file:- body["leds"] = args.file.read_text(encoding="utf-8")-- url = args.server.rstrip("/") + "/v1/push"- headers = {"content-type": "application/json"}- if args.secret:- headers["authorization"] = f"Bearer {args.secret}"-- request = Request(url, data=json.dumps(body).encode("utf-8"), headers=headers, method="POST")-- try:- with urlopen(request, timeout=20) as response:- print(response.read().decode("utf-8"))- return 0- except HTTPError as exc:- print(exc.read().decode("utf-8"), file=sys.stderr)- return 1- except URLError as exc:- print(f"error: {exc.reason}", file=sys.stderr)- return 2---if __name__ == "__main__":- raise SystemExit(main())diff --git a/ios/SidePulse/tools/server.py b/ios/SidePulse/tools/server.pydeleted file mode 100644index da5c3c7..0000000--- a/ios/SidePulse/tools/server.py+++ /dev/null@@ -1,395 +0,0 @@-#!/usr/bin/env python3-from __future__ import annotations--import copy-import html-import json-import os-from typing import Any-from urllib.parse import parse_qs--import uvicorn-from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request-from fastapi.responses import HTMLResponse--from apns_client import (- APNsClient,- APNsConfig,- APNsConfigError,- APNsResponse,- LEDPayloadError,- normalize_leds_text,- validate_leds_text,-)-from patterns import PATTERNS, pattern_names---DEFAULT_PORT = 8787-APNS_HEADER_ALIASES = {- "push_type": "apns-push-type",- "priority": "apns-priority",- "collapse_id": "apns-collapse-id",- "expiration": "apns-expiration",- "topic": "apns-topic",-}-RESERVED_ENVELOPE_KEYS = {- "device_token",- "pattern",- "leds",- "LEDS.LED",- "LEDS.led",- "text",- "payload",- "apns",- "alert",-}---app = FastAPI(title="SidePulse Push Server", version="1.0")---async def require_bearer_auth(authorization: str | None = Header(default=None)) -> None:- shared_secret = shared_secret_from_env()- if not shared_secret:- return-- if authorization == f"Bearer {shared_secret}":- return-- raise HTTPException(status_code=401, detail="Unauthorized")--[email protected]_event("shutdown")-async def shutdown() -> None:- client = getattr(app.state, "apns_client", None)- if client is not None and hasattr(client, "aclose"):- await client.aclose()--[email protected]("/health")-async def health() -> dict[str, Any]:- return {"ok": True, "service": "sidepulse-push"}--[email protected]("/v1/patterns")-async def patterns() -> dict[str, Any]:- return {- "patterns": [PATTERNS[name].as_public_dict() for name in pattern_names()],- }--[email protected]("/", response_class=HTMLResponse)-async def index() -> str:- return index_html()--[email protected]("/v1/push")-async def push(- request: Request,- _: None = Depends(require_bearer_auth),-) -> dict[str, Any]:- envelope = await read_json_object(request)- device_token = resolve_device_token(envelope.get("device_token"))- if not device_token:- raise HTTPException(status_code=400, detail="Missing device token")-- payload = build_friendly_payload(envelope)- headers = apns_headers_from_options(envelope.get("apns"), payload)- response = await send_apns(device_token, payload, headers)-- pattern = envelope.get("pattern")- return response_payload(- response,- extra={- "pattern": pattern if isinstance(pattern, str) else None,- "known_pattern": isinstance(pattern, str) and pattern in PATTERNS,- },- )--[email protected]("/v1/push/raw")-async def push_raw(- request: Request,- device_token: str | None = Query(default=None),- _: None = Depends(require_bearer_auth),-) -> dict[str, Any]:- payload = await read_json_object(request)- token = resolve_device_token(device_token or request.headers.get("x-side-device-token"))- if not token:- raise HTTPException(status_code=400, detail="Missing device token")-- headers = apns_headers_from_request(request, payload)- response = await send_apns(token, payload, headers)- return response_payload(response)--[email protected]("/push")-async def legacy_push(- request: Request,- device_token: str | None = Query(default=None),- key: str | None = Query(default=None),-) -> dict[str, Any]:- require_legacy_auth(key, request.headers.get("authorization"))- envelope = await read_legacy_body(request)- if device_token:- envelope["device_token"] = device_token- if "key" in envelope:- envelope.pop("key", None)-- token = resolve_device_token(envelope.get("device_token"))- if not token:- raise HTTPException(status_code=400, detail="Missing device token")-- payload = build_friendly_payload(envelope)- headers = apns_headers_from_options(envelope.get("apns"), payload)- response = await send_apns(token, payload, headers)- return response_payload(response, extra={"legacy": True})---def require_legacy_auth(key: str | None, authorization: str | None) -> None:- shared_secret = shared_secret_from_env()- if not shared_secret:- return-- if authorization == f"Bearer {shared_secret}" or key == shared_secret:- return-- raise HTTPException(status_code=401, detail="Unauthorized")---def shared_secret_from_env() -> str:- return os.environ.get("SIDEPULSE_SHARED_SECRET", "")---def resolve_device_token(value: Any) -> str | None:- if isinstance(value, str) and value.strip():- return value.strip()- return os.environ.get("SIDEPULSE_DEVICE_TOKEN")---async def read_json_object(request: Request) -> dict[str, Any]:- try:- loaded = await request.json()- except json.JSONDecodeError as exc:- raise HTTPException(status_code=400, detail=f"Invalid JSON: {exc}") from exc-- if not isinstance(loaded, dict):- raise HTTPException(status_code=400, detail="JSON body must be an object")- return loaded---async def read_legacy_body(request: Request) -> dict[str, Any]:- content_type = request.headers.get("content-type", "")- if "application/json" in content_type:- return await read_json_object(request)-- body = await request.body()- if not body:- return {}-- if "application/x-www-form-urlencoded" in content_type:- parsed = parse_qs(body.decode("utf-8"), keep_blank_values=True)- return {key: values[-1] for key, values in parsed.items()}-- return {"leds": body.decode("utf-8")}---def build_friendly_payload(envelope: dict[str, Any]) -> dict[str, Any]:- payload = envelope.get("payload")- if payload is None:- payload = {}- if not isinstance(payload, dict):- raise HTTPException(status_code=400, detail="payload must be an object")-- apns_payload = copy.deepcopy(payload)- for key, value in envelope.items():- if key not in RESERVED_ENVELOPE_KEYS:- apns_payload.setdefault(key, value)-- aps = apns_payload.get("aps")- if aps is None:- aps = {}- if not isinstance(aps, dict):- raise HTTPException(status_code=400, detail="payload.aps must be an object")-- alert = envelope.get("alert")- if isinstance(alert, str) and alert:- aps["alert"] = {"title": "SidePulse", "body": alert}- aps["sound"] = "default"- else:- aps.setdefault("content-available", 1)-- apns_payload["aps"] = aps-- led_text = first_led_text(envelope)- if led_text is not None:- led_text = normalize_leds_text(led_text)- try:- validate_leds_text(led_text)- except LEDPayloadError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc- apns_payload["leds"] = led_text-- pattern = envelope.get("pattern")- if isinstance(pattern, str) and pattern:- apns_payload["pattern"] = pattern-- data = envelope.get("data")- if isinstance(data, dict):- apns_payload.setdefault("data", data)-- return apns_payload---def first_led_text(envelope: dict[str, Any]) -> str | None:- for key in ("leds", "LEDS.LED", "LEDS.led", "text"):- value = envelope.get(key)- if isinstance(value, str):- return value- return None---def apns_headers_from_options(options: Any, payload: dict[str, Any]) -> dict[str, str]:- if options is None:- options = {}- if not isinstance(options, dict):- raise HTTPException(status_code=400, detail="apns must be an object")-- headers: dict[str, str] = {}- for key, value in options.items():- if value is None:- continue- header_name = APNS_HEADER_ALIASES.get(key, key)- if header_name.startswith("apns-"):- headers[header_name] = str(value)-- headers.setdefault("apns-push-type", default_push_type(payload))- headers.setdefault("apns-priority", "10" if headers["apns-push-type"] == "alert" else "5")- return headers---def apns_headers_from_request(request: Request, payload: dict[str, Any]) -> dict[str, str]:- headers: dict[str, str] = {}- for header_name in ("apns-push-type", "apns-priority", "apns-collapse-id", "apns-expiration", "apns-topic"):- value = request.headers.get(header_name) or request.headers.get("x-" + header_name)- if value:- headers[header_name] = value-- for option_name, header_name in APNS_HEADER_ALIASES.items():- value = request.query_params.get(option_name) or request.query_params.get(header_name)- if value:- headers[header_name] = value-- headers.setdefault("apns-push-type", default_push_type(payload))- headers.setdefault("apns-priority", "10" if headers["apns-push-type"] == "alert" else "5")- return headers---def default_push_type(payload: dict[str, Any]) -> str:- aps = payload.get("aps")- if isinstance(aps, dict) and "alert" in aps:- return "alert"- return "background"---async def send_apns(device_token: str, payload: dict[str, Any], headers: dict[str, str]) -> APNsResponse:- client = await get_apns_client()- try:- return await client.send(device_token, payload, headers=headers)- except (APNsConfigError, OSError, ValueError) as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc---async def get_apns_client() -> APNsClient:- client = getattr(app.state, "apns_client", None)- if client is not None:- return client-- client = APNsClient(APNsConfig.from_env())- app.state.apns_client = client- return client---def response_payload(response: APNsResponse, *, extra: dict[str, Any] | None = None) -> dict[str, Any]:- payload: dict[str, Any] = {- "ok": response.ok,- "status_code": response.status_code,- "apns_id": response.apns_id,- "response": response.body,- }- if extra:- payload.update(extra)-- if not response.ok:- raise HTTPException(status_code=502, detail=payload)-- return payload---def index_html() -> str:- default_token = html.escape(os.environ.get("SIDEPULSE_DEVICE_TOKEN", ""))- default_secret = html.escape(shared_secret_from_env())- options = "\n".join(- f'<option value="{html.escape(name)}">{html.escape(name)}</option>' for name in pattern_names()- )- return f"""<!doctype html>-<html lang="en">-<head>- <meta charset="utf-8">- <meta name="viewport" content="width=device-width, initial-scale=1">- <title>SidePulse Push Server</title>- <style>- body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; margin: 2rem; max-width: 760px; color: #111827; }}- label {{ display: block; font-weight: 650; margin-top: 1rem; }}- input, select, textarea {{ box-sizing: border-box; border: 1px solid #cbd5e1; border-radius: 6px; font: inherit; padding: 0.55rem; width: 100%; }}- textarea {{ min-height: 150px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }}- button {{ background: #111827; border: 0; border-radius: 6px; color: white; font: inherit; font-weight: 700; margin-top: 1rem; padding: 0.65rem 0.9rem; }}- pre {{ background: #f1f5f9; border-radius: 6px; overflow: auto; padding: 0.8rem; }}- </style>-</head>-<body>- <h1>SidePulse Push Server</h1>- <label>Device token</label>- <input id="deviceToken" value="{default_token}" autocomplete="off">- <label>Bearer secret</label>- <input id="secret" value="{default_secret}" autocomplete="off">- <label>Pattern</label>- <select id="pattern">{options}</select>- <label>Optional raw LEDS.LED</label>- <textarea id="leds" placeholder="#00ff00 250ms pulse off 150ms none"></textarea>- <button id="send">Send Push</button>- <pre id="result">Ready</pre>- <script>- document.getElementById("send").addEventListener("click", async () => {{- const body = {{- device_token: document.getElementById("deviceToken").value,- pattern: document.getElementById("pattern").value,- }};- const leds = document.getElementById("leds").value;- if (leds.trim()) body.leds = leds;- const secret = document.getElementById("secret").value;- const response = await fetch("/v1/push", {{- method: "POST",- headers: {{- "content-type": "application/json",- ...(secret ? {{ "authorization": "Bearer " + secret }} : {{}})- }},- body: JSON.stringify(body)- }});- document.getElementById("result").textContent = JSON.stringify(await response.json(), null, 2);- }});- </script>-</body>-</html>"""---def main() -> int:- host = os.environ.get("SIDEPULSE_SERVER_HOST", "127.0.0.1")- port = int(os.environ.get("SIDEPULSE_SERVER_PORT", str(DEFAULT_PORT)))- print(f"Serving SidePulse push server at http://{host}:{port}")- uvicorn.run("server:app", host=host, port=port, log_level=os.environ.get("SIDEPULSE_LOG_LEVEL", "info"))- return 0---if __name__ == "__main__":- raise SystemExit(main())diff --git a/ios/SidePulse/tools/sidepulse.env.example b/ios/SidePulse/tools/sidepulse.env.exampledeleted file mode 100644index f4e6cc8..0000000--- a/ios/SidePulse/tools/sidepulse.env.example+++ /dev/null@@ -1,9 +0,0 @@-export APNS_TEAM_ID="YOUR_TEAM_ID"-export APNS_KEY_ID="YOUR_KEY_ID"-export APNS_AUTH_KEY="/path/to/AuthKey_YOUR_KEY_ID.p8"-export APNS_BUNDLE_ID="io.sidepulse.app"-export APNS_ENV="sandbox"-export SIDEPULSE_DEVICE_TOKEN="paste-device-token-from-app"-export SIDEPULSE_SHARED_SECRET="choose-a-local-testing-secret"-export SIDEPULSE_SERVER_HOST="127.0.0.1"-export SIDEPULSE_SERVER_PORT="8787"diff --git a/ios/SidePulse/tools/tests/test_server.py b/ios/SidePulse/tools/tests/test_server.pydeleted file mode 100644index c6e1021..0000000--- a/ios/SidePulse/tools/tests/test_server.py+++ /dev/null@@ -1,234 +0,0 @@-from __future__ import annotations--import asyncio-import copy-import os-import sys-import unittest-from pathlib import Path-from unittest.mock import patch--import httpx-from fastapi.testclient import TestClient--TOOLS_DIR = Path(__file__).resolve().parents[1]-sys.path.insert(0, str(TOOLS_DIR))--from apns_client import APNsResponse # noqa: E402-from server import app # noqa: E402---class FakeAPNsClient:- def __init__(self) -> None:- self.calls: list[dict[str, object]] = []-- async def send(- self,- device_token: str,- payload: dict[str, object],- *,- headers: dict[str, str] | None = None,- ) -> APNsResponse:- await asyncio.sleep(0)- self.calls.append(- {- "device_token": device_token,- "payload": copy.deepcopy(payload),- "headers": dict(headers or {}),- }- )- return APNsResponse(status_code=200, apns_id="test-apns-id", body={"sent": True})-- async def aclose(self) -> None:- pass---class ServerTestCase(unittest.TestCase):- def setUp(self) -> None:- self.fake = FakeAPNsClient()- app.state.apns_client = self.fake- self.env = patch.dict(- os.environ,- {- "SIDEPULSE_SHARED_SECRET": "secret",- "SIDEPULSE_DEVICE_TOKEN": "env-device-token",- },- clear=False,- )- self.env.start()-- def tearDown(self) -> None:- self.env.stop()- if hasattr(app.state, "apns_client"):- delattr(app.state, "apns_client")-- def test_requires_bearer_auth(self) -> None:- with TestClient(app) as client:- response = client.post("/v1/push", json={"pattern": "green_pulse_2"})-- self.assertEqual(response.status_code, 401)- self.assertEqual(self.fake.calls, [])-- def test_friendly_pattern_envelope(self) -> None:- with TestClient(app) as client:- response = client.post(- "/v1/push",- headers={"authorization": "Bearer secret"},- json={"pattern": "green_pulse_2"},- )-- self.assertEqual(response.status_code, 200)- self.assertTrue(response.json()["known_pattern"])- self.assertEqual(len(self.fake.calls), 1)- call = self.fake.calls[0]- self.assertEqual(call["device_token"], "env-device-token")- self.assertEqual(call["payload"]["pattern"], "green_pulse_2")- self.assertEqual(call["payload"]["aps"], {"content-available": 1})- self.assertEqual(call["headers"]["apns-push-type"], "background")- self.assertEqual(call["headers"]["apns-priority"], "5")-- def test_apns_header_mapping(self) -> None:- with TestClient(app) as client:- response = client.post(- "/v1/push",- headers={"authorization": "Bearer secret"},- json={- "device_token": "explicit-token",- "pattern": "success",- "apns": {- "push_type": "alert",- "priority": 10,- "collapse_id": "pulse-status",- "expiration": "0",- },- },- )-- self.assertEqual(response.status_code, 200)- call = self.fake.calls[0]- self.assertEqual(call["device_token"], "explicit-token")- self.assertEqual(call["headers"]["apns-push-type"], "alert")- self.assertEqual(call["headers"]["apns-priority"], "10")- self.assertEqual(call["headers"]["apns-collapse-id"], "pulse-status")- self.assertEqual(call["headers"]["apns-expiration"], "0")-- def test_leds_led_payload_alias(self) -> None:- with TestClient(app) as client:- response = client.post(- "/v1/push",- headers={"authorization": "Bearer secret"},- json={"LEDS.LED": "#00ff00 280ms pulse\n"},- )-- self.assertEqual(response.status_code, 200)- self.assertEqual(self.fake.calls[0]["payload"]["leds"], "#00ff00 280ms pulse\n")-- def test_friendly_led_payload_decodes_escaped_newlines(self) -> None:- with TestClient(app) as client:- response = client.post(- "/v1/push",- headers={"authorization": "Bearer secret"},- json={"leds": r"off\n#00ff00 280ms pulse\n"},- )-- self.assertEqual(response.status_code, 200)- self.assertEqual(self.fake.calls[0]["payload"]["leds"], "off\n#00ff00 280ms pulse\n")-- def test_friendly_led_payload_line_limit_uses_decoded_newlines(self) -> None:- with TestClient(app) as client:- response = client.post(- "/v1/push",- headers={"authorization": "Bearer secret"},- json={"leds": r"\n".join(["off"] * 21)},- )-- self.assertEqual(response.status_code, 400)- self.assertIn("max is 20", response.text)- self.assertEqual(self.fake.calls, [])-- def test_old_leds_txt_key_is_not_promoted_to_led_text(self) -> None:- with TestClient(app) as client:- response = client.post(- "/v1/push",- headers={"authorization": "Bearer secret"},- json={"LEDS.TXT": "#00ff00 280ms pulse\n"},- )-- self.assertEqual(response.status_code, 200)- payload = self.fake.calls[0]["payload"]- self.assertNotIn("leds", payload)- self.assertEqual(payload["LEDS.TXT"], "#00ff00 280ms pulse\n")-- def test_friendly_led_payload_validates_line_limit(self) -> None:- with TestClient(app) as client:- response = client.post(- "/v1/push",- headers={"authorization": "Bearer secret"},- json={"leds": "\n".join(["off"] * 21)},- )-- self.assertEqual(response.status_code, 400)- self.assertIn("max is 20", response.text)- self.assertEqual(self.fake.calls, [])-- def test_raw_payload_passthrough(self) -> None:- raw_payload = {- "aps": {"content-available": 1},- "custom": {"nested": [1, 2, 3]},- "pattern": "working",- }-- with TestClient(app) as client:- response = client.post(- "/v1/push/raw?device_token=query-token",- headers={- "authorization": "Bearer secret",- "x-apns-push-type": "background",- "x-apns-priority": "5",- },- json=raw_payload,- )-- self.assertEqual(response.status_code, 200)- call = self.fake.calls[0]- self.assertEqual(call["device_token"], "query-token")- self.assertEqual(call["payload"], raw_payload)- self.assertEqual(call["headers"]["apns-push-type"], "background")- self.assertEqual(call["headers"]["apns-priority"], "5")---class ConcurrentServerTestCase(unittest.IsolatedAsyncioTestCase):- async def asyncSetUp(self) -> None:- self.fake = FakeAPNsClient()- app.state.apns_client = self.fake- self.env = patch.dict(- os.environ,- {- "SIDEPULSE_SHARED_SECRET": "secret",- "SIDEPULSE_DEVICE_TOKEN": "env-device-token",- },- clear=False,- )- self.env.start()-- async def asyncTearDown(self) -> None:- self.env.stop()- if hasattr(app.state, "apns_client"):- delattr(app.state, "apns_client")-- async def test_mocked_concurrent_sends(self) -> None:- transport = httpx.ASGITransport(app=app)- async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:- responses = await asyncio.gather(- *[- client.post(- "/v1/push",- headers={"authorization": "Bearer secret"},- json={"pattern": "green_pulse_2"},- )- for _ in range(40)- ]- )-- self.assertTrue(all(response.status_code == 200 for response in responses))- self.assertEqual(len(self.fake.calls), 40)