Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

Add Phase 0 specs: ADRs, protocol v0, core API, capability matrix

Beeea14fe13bb5f
diff --git a/docs/adr/0001-record-architecture-decisions.md b/docs/adr/0001-record-architecture-decisions.md
new file mode 100644
index 0000000..d943eef
--- /dev/null
+++ b/docs/adr/0001-record-architecture-decisions.md
@@ -0,0 +1,17 @@
+# ADR 0001: Record architecture decisions
+
+- **Status:** Accepted
+- **Date:** 2026-10-05
+
+## Context
+
+We need a lightweight, durable record of why big decisions were made, so contributors don't re-litigate them and we can revisit them deliberately.
+
+## Decision
+
+Use Architecture Decision Records (ADRs) in `docs/adr/`, one numbered Markdown file per decision, with the sections Context, Decision, Consequences. Superseded ADRs stay in place and link to their replacement.
+
+## Consequences
+
+- Decisions are discoverable next to the code.
+- Changing a decision means writing a new ADR, not editing history.
diff --git a/docs/adr/0002-shared-rust-core.md b/docs/adr/0002-shared-rust-core.md
new file mode 100644
index 0000000..95c4622
--- /dev/null
+++ b/docs/adr/0002-shared-rust-core.md
@@ -0,0 +1,18 @@
+# ADR 0002: Shared Rust core for both apps
+
+- **Status:** Accepted
+- **Date:** 2026-10-05
+
+## Context
+
+Competitors that implement the protocol twice (e.g. KDE Connect's separate desktop and Android code) suffer interop bugs. We need one implementation of networking, pairing, transfers and storage, that is fast, memory-safe for parsing untrusted input, and portable to Windows, Android and later macOS.
+
+## Decision
+
+All protocol, pairing, session, transfer and storage logic lives in Rust crates under `core/`. The Windows app links them directly; the Android app uses them via UniFFI bindings.
+
+## Consequences
+
+- One source of truth; interop bugs between our own apps are impossible by construction.
+- Android APK grows by ~5–8 MB per ABI (ship arm64 primarily).
+- Contributors need Rust; Rust compile times are slower.
diff --git a/docs/adr/0003-iroh-transport.md b/docs/adr/0003-iroh-transport.md
new file mode 100644
index 0000000..fe82767
--- /dev/null
+++ b/docs/adr/0003-iroh-transport.md
@@ -0,0 +1,19 @@
+# ADR 0003: iroh (QUIC) as the transport
+
+- **Status:** Accepted
+- **Date:** 2026-10-05
+
+## Context
+
+Connection reliability is the #1 complaint across Phone Link, KDE Connect and LocalSend: discovery failures, firewalls, AP isolation, same-network-only. Hand-rolling discovery, NAT traversal and multiplexing is where competitors break.
+
+## Decision
+
+Use iroh 1.x: devices are dialed by Ed25519 public key over QUIC, with LAN discovery, hole punching, relay fallback (over HTTPS), multipath and many streams per connection. Wrap it behind our own `Connection` abstraction.
+
+## Consequences
+
+- E2E encryption and mutual key authentication by default.
+- Away-from-home works without port forwarding (relays opt-in, self-hostable).
+- Young library (1.0 in June 2026); the abstraction keeps it swappable.
+- USB path relies on iroh's custom transports (currently unstable) or a TCP-framed fallback.
diff --git a/docs/adr/0004-cbor-wire-format.md b/docs/adr/0004-cbor-wire-format.md
new file mode 100644
index 0000000..136cf8c
--- /dev/null
+++ b/docs/adr/0004-cbor-wire-format.md
@@ -0,0 +1,18 @@
+# ADR 0004: CBOR as the wire format
+
+- **Status:** Accepted
+- **Date:** 2026-10-05
+
+## Context
+
+Messages must be compact, forward-compatible (old and new app versions talk to each other) and implementable by third parties, without forcing a code-generation toolchain into every build.
+
+## Decision
+
+Encode messages as CBOR (RFC 8949) via serde. Unknown fields are ignored, unknown message types get an `Unsupported` reply. The schema is documented in `docs/protocol/`.
+
+## Consequences
+
+- No protoc/codegen step.
+- Self-describing payloads are easy to debug.
+- Schema discipline is manual: every change goes through the protocol spec and compatibility tests.
diff --git a/docs/adr/0005-qt-quick-desktop-ui.md b/docs/adr/0005-qt-quick-desktop-ui.md
new file mode 100644
index 0000000..e5f9190
--- /dev/null
+++ b/docs/adr/0005-qt-quick-desktop-ui.md
@@ -0,0 +1,19 @@
+# ADR 0005: Qt Quick (QML) + Rust for the Windows app
+
+- **Status:** Accepted
+- **Date:** 2026-10-05
+
+## Context
+
+The desktop app runs all day, is video-heavy (mirroring, one window per phone app) and needs a very high visual bar. The maintainer ruled out web stacks (RAM) and Flutter. We scored Tauri+React (pure and hybrid), Qt Quick + Rust and Slint (see PLAN.md §5.1).
+
+## Decision
+
+Build the desktop UI in Qt Quick (QML) with all logic in Rust, bridged by cxx-qt through a single crate (`nectarlink-qt`). Mirrored video is decoded with Media Foundation into D3D11 textures shown directly in Qt's scene graph.
+
+## Consequences
+
+- Visual ceiling equal to web (blur, shaders, fluid motion) at a fraction of the RAM.
+- Heavier build: Qt toolchain, a little C++, pre-1.0 cxx-qt.
+- Rules: QML is presentation only; use only LGPL Qt modules; track the latest Qt 6 minor release.
+- Fallback if the Phase 0 proof fails: web UI (Tauri) with native Rust video windows.
diff --git a/docs/adr/0006-kotlin-compose-android.md b/docs/adr/0006-kotlin-compose-android.md
new file mode 100644
index 0000000..c0a3548
--- /dev/null
+++ b/docs/adr/0006-kotlin-compose-android.md
@@ -0,0 +1,17 @@
+# ADR 0006: Kotlin + Jetpack Compose for the Android app
+
+- **Status:** Accepted
+- **Date:** 2026-10-05
+
+## Context
+
+Nearly every feature depends on deep Android APIs (notification listener, telephony, Companion Device Manager, MediaProjection, CameraX, QS tiles, widgets).
+
+## Decision
+
+Write the Android app in Kotlin with Jetpack Compose and Material 3 Expressive, calling the Rust core through UniFFI.
+
+## Consequences
+
+- First-class access to every system API, best battery behavior.
+- Two UI codebases (QML and Compose), unified by a shared design language rather than shared code.
diff --git a/docs/adr/0007-licensing.md b/docs/adr/0007-licensing.md
new file mode 100644
index 0000000..0b3ac07
--- /dev/null
+++ b/docs/adr/0007-licensing.md
@@ -0,0 +1,18 @@
+# ADR 0007: Licensing
+
+- **Status:** Accepted
+- **Date:** 2026-10-05
+
+## Context
+
+We want forks of the apps to stay open, the protocol and core to be easy to adopt, and a future App Store release to be possible.
+
+## Decision
+
+Apps: GPL-3.0-or-later with an app-store additional permission. Core libraries: MPL-2.0. Docs and protocol spec: CC BY 4.0. Name and logo: trademark policy. Contributions: DCO sign-off.
+
+## Consequences
+
+- The app-store permission must exist from the first commit to cover all contributions.
+- GPL-only Qt modules must be avoided (see ADR 0005).
+- The exception text needs legal review before the first public release.
diff --git a/docs/adr/0008-platforms-and-distribution.md b/docs/adr/0008-platforms-and-distribution.md
new file mode 100644
index 0000000..bfc4bb2
--- /dev/null
+++ b/docs/adr/0008-platforms-and-distribution.md
@@ -0,0 +1,18 @@
+# ADR 0008: Platforms and distribution
+
+- **Status:** Accepted
+- **Date:** 2026-10-05
+
+## Context
+
+Focus beats breadth. Windows 10 is out of support, and store policies (Play) restrict SMS, accessibility and file access.
+
+## Decision
+
+Windows 11 only (x64 + ARM64) and Android 8+. Distribute GitHub-first: GitHub Releases + winget on Windows, GitHub Releases + Obtainium (later IzzyOnDroid) on Android. Stores and macOS come later.
+
+## Consequences
+
+- Free to use Win11 APIs (Mica, virtual camera, Win11 context menu).
+- No Play policy constraints in the `full` flavor; a `play` flavor seam is kept.
+- Android developer verification must be completed before global enforcement (2027).
diff --git a/docs/adr/README.md b/docs/adr/README.md
new file mode 100644
index 0000000..6e5b326
--- /dev/null
+++ b/docs/adr/README.md
@@ -0,0 +1,12 @@
+# Architecture Decision Records
+
+| # | Decision | Status |
+|---|---|---|
+| 0001 | [Record architecture decisions](0001-record-architecture-decisions.md) | Accepted |
+| 0002 | [Shared Rust core for both apps](0002-shared-rust-core.md) | Accepted |
+| 0003 | [iroh (QUIC) as the transport](0003-iroh-transport.md) | Accepted |
+| 0004 | [CBOR as the wire format](0004-cbor-wire-format.md) | Accepted |
+| 0005 | [Qt Quick (QML) + Rust for the Windows app](0005-qt-quick-desktop-ui.md) | Accepted |
+| 0006 | [Kotlin + Jetpack Compose for the Android app](0006-kotlin-compose-android.md) | Accepted |
+| 0007 | [Licensing](0007-licensing.md) | Accepted |
+| 0008 | [Platforms and distribution](0008-platforms-and-distribution.md) | Accepted |
diff --git a/docs/architecture/capabilities.md b/docs/architecture/capabilities.md
new file mode 100644
index 0000000..93d3aa4
--- /dev/null
+++ b/docs/architecture/capabilities.md
@@ -0,0 +1,113 @@
+# Capability matrix
+
+The capability matrix decides, for every feature and every paired device,
+whether the feature is **Available**, **Partial**, **Locked** or
+**Unsupported**, and what the user can do about it. Both apps render their UI
+from the same matrix, computed by `nectarlink-core`, so the phone and PC can
+never disagree about what works.
+
+## Inputs
+
+| Input | Source |
+|---|---|
+| Peer capabilities | The peer's `hello.caps` (protocol §6) |
+| Local capabilities | This device's own state (permissions, add-ons, OS version) |
+| Power level | The phone's `hello.power` |
+| Connection paths | Which paths are active (LAN, USB, relay) |
+| Per-device permissions | The user's toggles for this paired device |
+| Feature registry | Static definitions compiled into the core (below) |
+
+The matrix is recomputed whenever any input changes and is pushed to the UI
+as an event.
+
+## Feature definitions
+
+Each feature is declared once, in Rust, in `nectarlink-core::features`:
+
+```rust
+pub struct FeatureDef {
+ pub id: FeatureId, // e.g. "clipboard.auto_phone_to_pc"
+ pub group: FeatureGroup, // Notifications, Clipboard, Files, Mirroring…
+ /// Every requirement must hold for the feature to be Available.
+ pub requires: &'static [Requirement],
+ /// If `requires` fails, this weaker set may still give a Partial state.
+ pub partial: Option<PartialDef>,
+}
+
+pub enum Requirement {
+ PeerCap(&'static str), // peer offers a capability ID
+ LocalCap(&'static str), // this device offers a capability ID
+ PowerAtLeast(PowerLevel), // Basic < Assist < Elevated < Root
+ AndroidApiAtLeast(u32),
+ WindowsBuildAtLeast(u32),
+ Path(ConnectionPath), // e.g. Usb, Relay
+ DeviceToggle(&'static str), // per-device user permission
+ Addon(&'static str), // e.g. "vcam", "explorer", "hfp"
+}
+
+pub struct PartialDef {
+ pub requires: &'static [Requirement],
+ pub limit: &'static str, // translation key, e.g. "clip.partial.manual"
+}
+```
+
+## States
+
+```rust
+pub enum FeatureState {
+ Available,
+ /// Works, with a limitation shown inline, plus how to remove it.
+ Partial { limit: MessageKey, upgrade: Option<Upgrade> },
+ /// Doesn't work yet, but the user can unlock it.
+ Locked { upgrade: Upgrade },
+ /// Can't work on this device combination; explained, not actionable.
+ Unsupported { reason: MessageKey },
+}
+
+pub struct Upgrade {
+ pub action: UpgradeAction, // which setup sheet to open
+ pub effort: Effort, // e.g. Minutes(2), Instant
+}
+
+pub enum UpgradeAction {
+ RaisePower(PowerLevel), // open "Choose your power" at that level
+ GrantPermission(Permission), // e.g. notification access
+ EnableAddon(&'static str), // e.g. install the virtual camera
+ EnablePath(ConnectionPath), // e.g. turn on Away mode
+ EnableDeviceToggle(&'static str), // flip a per-device permission
+ UpdateApp(DeviceSide), // peer or local app too old
+}
+```
+
+### How a state is chosen
+
+1. If any requirement is impossible on this device pair (OS version too old,
+ hardware missing), the state is **Unsupported**.
+2. Else, if all `requires` hold: **Available**.
+3. Else, if a `partial` set holds: **Partial**, with an `upgrade` pointing at
+ the first unmet requirement of the full set.
+4. Else: **Locked**, with an `upgrade` for the first unmet requirement. When
+ several requirements are unmet, the one with the lowest effort is offered
+ first.
+
+## Examples
+
+| Feature | Requires | Partial | Typical state at Basic |
+|---|---|---|---|
+| `clipboard.pc_to_phone` | `PeerCap("clip.write")` | – | Available |
+| `clipboard.auto_phone_to_pc` | `PeerCap("clip.read.auto")` (needs Elevated) | `PeerCap("clip.share")` → "Manual: tap to send" | Partial, upgrade → Elevated · ~2 min |
+| `notifications.sensitive` | `PeerCap("notify.sensitive")` | – | Locked, upgrade → Elevated · ~2 min |
+| `mirroring.app_windows` | `PeerCap("mirror.virtual_display")`, `PowerAtLeast(Elevated)` | – | Locked |
+| `mirroring.control` | `PeerCap("mirror.input")` | – | Locked → Assist · ~1 min (or Elevated) |
+| `camera.webcam` | `PeerCap("camera.stream")`, `Addon("vcam")`, `WindowsBuildAtLeast(22000)` | – | Locked → install virtual camera |
+
+## UI contract
+
+- Both UIs receive `CapabilityMatrix { device_id, features: Map<FeatureId, FeatureState> }`.
+- **Available:** normal control.
+- **Partial:** normal control plus an inline hint (`limit`) and, if present, an
+ "Unlock" affordance.
+- **Locked:** greyed control with a chip showing the level and effort (e.g.
+ "Elevated · ~2 min"). Tapping it opens the setup sheet for `upgrade.action`,
+ and on success returns to the feature.
+- **Unsupported:** hidden in compact views, shown with the reason in settings.
diff --git a/docs/architecture/core-api.md b/docs/architecture/core-api.md
new file mode 100644
index 0000000..7379b99
--- /dev/null
+++ b/docs/architecture/core-api.md
@@ -0,0 +1,140 @@
+# `nectarlink-core` public interface (Phase 0 draft)
+
+This is the boundary between the shared Rust core and the two apps. The
+desktop app calls it directly from Rust (and exposes it to QML through
+`nectarlink-qt`); the Android app calls it through UniFFI-generated Kotlin.
+
+Design rules:
+
+- **One entry point**, `Node`, owning its own async runtime. Apps never touch
+ tokio or iroh directly.
+- **Commands are async methods; state changes are events.** UIs subscribe to a
+ single event stream and render from it. No polling.
+- **FFI-friendly types only** at the boundary: plain structs and enums, owned
+ strings, byte vectors, no lifetimes or generics. That keeps the UniFFI and
+ cxx-qt layers thin.
+- **Platform features are injected**, not called directly: the core defines
+ traits (battery source, notification sink…) that each app implements.
+
+## Types (sketch)
+
+```rust
+pub struct NodeConfig {
+ pub data_dir: PathBuf, // keys, trust store, SQLite database
+ pub device: DeviceInfo,
+ pub away_mode: bool, // allow relays
+ pub relay_urls: Vec<String>, // empty = defaults
+}
+
+pub struct DeviceId(pub [u8; 32]); // displayed as z-base-32
+
+pub struct PairedDevice {
+ pub id: DeviceId,
+ pub info: DeviceInfo,
+ pub paired_at: i64, // unix seconds
+ pub link: LinkState,
+}
+
+pub enum LinkState {
+ Offline { last_seen: Option<i64> },
+ Connecting,
+ Online { path: ConnectionPath, rtt_ms: u32 },
+}
+
+pub enum ConnectionPath { Lan, Usb, Relay }
+
+pub enum PairingEvent {
+ QrReady { uri: String, expires_at: i64 },
+ SasCode { code: String }, // nearby flow: show and ask to confirm
+ Paired { device: PairedDevice },
+ Failed { reason: PairingError },
+}
+
+pub enum NodeEvent {
+ DeviceAdded(PairedDevice),
+ DeviceRemoved(DeviceId),
+ LinkChanged { device: DeviceId, link: LinkState },
+ PeerInfoChanged { device: DeviceId, info: DeviceInfo },
+ Battery { device: DeviceId, level: u8, charging: bool },
+ Capabilities(CapabilityMatrix), // see capabilities.md
+ Ring { device: DeviceId, on: bool },
+ Pairing(PairingEvent),
+}
+```
+
+## `Node`
+
+```rust
+impl Node {
+ /// Loads or creates the device key and trust store, starts networking.
+ pub async fn start(config: NodeConfig, platform: Arc<dyn Platform>) -> Result<Node>;
+ pub async fn shutdown(&self);
+
+ pub fn device_id(&self) -> DeviceId;
+ pub fn events(&self) -> EventReceiver; // one stream per subscriber
+
+ // Pairing
+ pub async fn pairing_start_qr(&self) -> Result<PairingSession>; // PC side
+ pub async fn pairing_scan_qr(&self, uri: String) -> Result<PairingSession>; // phone side
+ pub async fn pairing_start_nearby(&self, peer: DiscoveredDevice) -> Result<PairingSession>;
+ pub fn discovered_devices(&self) -> Vec<DiscoveredDevice>;
+
+ // Devices
+ pub fn paired_devices(&self) -> Vec<PairedDevice>;
+ pub async fn unpair(&self, id: DeviceId) -> Result<()>;
+ pub async fn ring(&self, id: DeviceId, on: bool) -> Result<()>;
+ pub async fn set_device_toggle(&self, id: DeviceId, toggle: String, on: bool) -> Result<()>;
+
+ // Local state the app reports to the core
+ pub fn update_local_info(&self, info: DeviceInfo);
+ pub fn update_power_level(&self, level: PowerLevel);
+ pub fn update_local_capabilities(&self, caps: Vec<String>);
+ pub fn set_away_mode(&self, enabled: bool);
+}
+
+impl PairingSession {
+ pub async fn confirm_sas(&self, matches: bool) -> Result<()>;
+ pub async fn cancel(&self);
+}
+```
+
+## Platform trait (implemented by each app)
+
+```rust
+pub trait Platform: Send + Sync {
+ fn battery(&self) -> Option<BatteryState>;
+ fn start_ringing(&self);
+ fn stop_ringing(&self);
+ /// Called when the core needs a user decision while the app is in the
+ /// background (e.g. an incoming nearby pairing request).
+ fn notify_user(&self, request: UserPrompt);
+}
+```
+
+Later services add more injected traits (notification source and sink,
+clipboard, media session, file access…), each in its own module, so the
+platform surface grows feature by feature.
+
+## Threading
+
+- `Node` runs on its own multi-threaded tokio runtime, created in `start`.
+- Methods are safe to call from any thread.
+- **Desktop:** `nectarlink-qt` reads `events()` on a background task and hands
+ each event to the Qt GUI thread through cxx-qt's thread queue. This is the
+ only place core events cross into Qt.
+- **Android:** UniFFI exposes `events()` as a callback interface; the Kotlin
+ side converts it into a `Flow` collected by view-models.
+
+## Errors
+
+A single `Error` enum crosses the boundary, with variants that the UI can
+act on (`NotPaired`, `Offline`, `Denied`, `VersionTooOld { side }`,
+`Unsupported`, `Io(String)`, `Internal(String)`). Internal error details are
+logged without personal content.
+
+## Storage
+
+- `data_dir/identity.key`: the device key, encrypted with the platform key
+ store.
+- `data_dir/nectarlink.db`: SQLite with the trust store, per-device settings
+ and caches. Schema migrations run in `Node::start`.
diff --git a/docs/foundations/phase-0.md b/docs/foundations/phase-0.md
new file mode 100644
index 0000000..09e9c8d
--- /dev/null
+++ b/docs/foundations/phase-0.md
@@ -0,0 +1,100 @@
+# Phase 0: Foundations — execution plan
+
+Goal: prove the risky parts early and build the skeleton every later feature
+plugs into. Phase 0 ends when the exit criteria at the bottom are met.
+
+## 1. Workstreams and order
+
+```
+ W1 Design ───────────► directions picked ──► hi-fi mockups ─────────────┐
+ W2 Repo & CI ──► scaffold ──► CI green │
+ W3 Core ─────────────► identity ► pairing ► session ► events ──┐ │
+ S1 Qt + Rust proof (the gate) ──────────────────────► pass? ───┼──► W4 Desktop shell
+ S2–S7 other spikes (parallel, timeboxed) ──────────────────────┘ W5 Android shell
+```
+
+1. **W2 Repo & CI** and **W1 Design directions** start together.
+2. **S1 Qt + Rust proof** starts right after the scaffold, because it decides
+ the desktop stack.
+3. **W3 Core** proceeds in parallel; it doesn't depend on the UI choice.
+4. **W4/W5 shells** start once S1 passes and a design direction is picked.
+5. **S2–S7** run alongside, each timeboxed. A failed spike changes the plan,
+ it doesn't block Phase 0.
+
+## 2. Repository scaffold (W2)
+
+```
+nectarlink/
+ Cargo.toml Rust workspace (core + desktop crates)
+ rust-toolchain.toml pinned stable toolchain
+ core/
+ nectarlink-protocol/ message types, framing, CBOR codec (MPL-2.0)
+ nectarlink-core/ Node, identity, pairing, sessions, store (MPL-2.0)
+ nectarlink-ffi/ UniFFI bindings (MPL-2.0)
+ nectarlink-cli/ dev/debug CLI: pair, ping, status (GPL)
+ desktop/
+ app/ Rust binary: startup, tray, windows (GPL)
+ nectarlink-qt/ cxx-qt bridge (view-models) (GPL)
+ qml/ design system + screens (GPL)
+ android/ Gradle project (app module) (GPL)
+ spikes/ throwaway experiments, one folder each
+ docs/
+ scripts/ build helpers (PowerShell + bash)
+```
+
+**CI (GitHub Actions, runs once we push; until then the same scripts run
+locally):**
+
+| Job | Runs on | Does |
+|---|---|---|
+| `core` | windows-latest, ubuntu-latest | `cargo fmt --check`, `clippy -D warnings`, `cargo test`, fuzz smoke test |
+| `desktop` | windows-latest | Install Qt 6.12 (aqtinstall, cached), build x64 + ARM64, run QML tests |
+| `android` | ubuntu-latest | `cargo ndk` build of `nectarlink-ffi`, Gradle build, unit tests |
+| `licenses` | ubuntu-latest | SPDX header check, dependency license audit (`cargo deny`) |
+
+Local equivalent: `scripts/check.ps1` runs the same steps on this machine.
+
+## 3. Core milestones (W3)
+
+| # | Milestone | Done when |
+|---|---|---|
+| C1 | Protocol crate | Framing + envelope encode/decode with unit tests and a fuzz target; rejects oversized frames |
+| C2 | Identity & store | Device key created/loaded and encrypted at rest; SQLite trust store with migrations |
+| C3 | Pairing | QR flow and nearby (SAS) flow per protocol §9, with tests including a simulated man-in-the-middle that must fail |
+| C4 | Sessions | Paired devices connect over iroh, `hello` exchange, version negotiation, `ping`/`pong`, reconnect with backoff |
+| C5 | Events & capabilities | Battery and device events, capability matrix computed and emitted |
+| C6 | CLI | `nectarlink-cli pair`, `status`, `ping`, `ring` work between two machines (or two processes) |
+
+## 4. Spikes
+
+Each spike gets a folder in `spikes/`, a short README with results, and a
+verdict. Spike code is throwaway; what we keep is the knowledge.
+
+| # | Spike | Question | Pass criteria | If it fails |
+|---|---|---|---|---|
+| **S1** | **Qt + Rust proof** (gate) | Can Qt Quick + cxx-qt deliver the design at our budgets? | Home screen, notification card, Deck grid, one hero transition and a live video window built from the mockups; 120 fps on a mid-range laptop; RAM < 60 MB tray / < 120 MB window; cold start < 500 ms; D3D11 video in the scene graph without copies; Mica works; 10k core→UI events/s without UI stutter; CI builds x64 + ARM64 | Fall back to web UI (Tauri) with native Rust video windows (ADR 0005) |
+| S2 | Mirror latency | Phone encoder → QUIC → MF decode → screen | ≤ 50 ms glass-to-glass at 1080p60 on LAN, measured with a high-speed camera or on-screen timestamps | Tune encoder/transport; dedicated swapchain for video |
+| S3 | Bluetooth calling | Can a third-party app act as an HFP hands-free device on Windows 11 24H2/25H2? | Answer a real call and hear audio on the PC, with package identity | Calls stay "alert + control", audio on the phone |
+| S4 | iroh on Android | Battery cost and reconnect behavior | < 2 %/day idle while connected; reconnect < 3 s after Wi-Fi switch, screen off, Doze | Tune keep-alives; lean on CDM wake |
+| S5 | USB transport | iroh custom transport (or TCP tunnel) over ADB | Session runs over USB with Wi-Fi off; ≥ 30 MB/s file throughput | TCP-framed tunnel fallback |
+| S6 | Toasts & identity | Sparse package identity + toasts with inline reply from an unpackaged installer | Toast with image, buttons and a reply box; reply text reaches the app, also when it was not running | Simpler toasts; reply opens the app |
+| S7 | Elevated self-pairing | Phone-only wireless-debugging pairing and re-arm after reboot | Pair from a notification on Android 11–16 (Pixel, Samsung, Xiaomi); helper process starts as `shell`; re-arm works where the OEM allows | Rely on PC-side re-arm and Shizuku |
+
+## 5. Design (W1)
+
+1. Three visual directions (`docs/design/directions/`): pick one, or mix.
+2. Design tokens: color (light and dark), type scale, spacing, radii,
+ elevation, motion curves (springs).
+3. Hi-fi mockups of Home, Onboarding, Choose-your-power, Notifications,
+ Messages, Mirror window and Deck, for both apps.
+4. The ~30-component inventory for QML and Compose.
+
+## 6. Exit criteria
+
+- [ ] Phone and PC pair by QR in under 60 seconds.
+- [ ] They show each other live (name, battery) and survive PC sleep/wake and
+ Wi-Fi changes.
+- [ ] S1 passed (or the fallback was chosen and documented as an ADR).
+- [ ] Every other spike has a written verdict.
+- [ ] Design direction chosen, tokens and core mockups approved.
+- [ ] `scripts/check.ps1` is green locally.
diff --git a/docs/protocol/v0.md b/docs/protocol/v0.md
new file mode 100644
index 0000000..26c6fdd
--- /dev/null
+++ b/docs/protocol/v0.md
@@ -0,0 +1,321 @@
+# Nectarlink Protocol — version 0 (draft)
+
+> Status: **draft for Phase 0.** Breaking changes are allowed until v1.
+> License: CC BY 4.0. Anyone may implement this protocol.
+
+This document specifies how two Nectarlink devices find each other, pair,
+connect and exchange messages. Version 0 covers the Phase 0 scope: identity,
+pairing, the session handshake, capabilities, heartbeat and the first events
+(device info, battery, ping). Feature services (notifications, files,
+clipboard, mirroring…) are specified in separate documents that build on this
+one.
+
+Key words **MUST**, **SHOULD** and **MAY** are used as in RFC 2119.
+
+---
+
+## 1. Concepts
+
+| Term | Meaning |
+|---|---|
+| **Device** | One installation of Nectarlink (a phone, a PC). |
+| **Device key** | An Ed25519 key pair generated on first launch. Never leaves the device. |
+| **Device ID** | The Ed25519 public key (32 bytes). Equal to the iroh `EndpointId`. Displayed as lowercase z-base-32. |
+| **Pairing** | A one-time ceremony after which each device stores the other's Device ID as trusted. |
+| **Session** | One authenticated QUIC connection between two paired devices. |
+| **Service** | A feature area (e.g. `notifications`, `transfer`) that owns its own streams and messages. |
+
+## 2. Transport
+
+- All traffic runs over **QUIC via iroh**. TLS 1.3 with raw public keys
+ authenticates both ends by Device ID. There is no other encryption layer and
+ no unencrypted mode.
+- Two **ALPN** values are defined:
+
+ | ALPN | Purpose | Who may connect |
+ |---|---|---|
+ | `nectarlink/0` | Normal sessions | Paired devices only |
+ | `nectarlink-pair/0` | Pairing ceremony | Anyone, but only while the receiving device is in pairing mode |
+
+- A device **MUST** close a `nectarlink/0` connection immediately (application
+ error `UNPAIRED`, see §8) if the peer's Device ID is not in its trust store.
+- A device **MUST** reject `nectarlink-pair/0` connections when it is not in
+ pairing mode, and **MUST** leave pairing mode after a successful pairing or a
+ timeout (default 5 minutes).
+
+### 2.1 Address discovery
+
+Devices locate each other by Device ID. Implementations use, in order of
+preference (iroh races them):
+
+1. Local-network discovery (mDNS address lookup).
+2. Last known direct addresses, cached per paired device.
+3. A small UDP beacon on the LAN as a fallback where mDNS is filtered
+ (format to be specified in v0.1).
+4. Relay servers, only if the user enabled "away from home".
+
+## 3. Framing
+
+Every QUIC stream carries a sequence of **frames**:
+
+```
+frame = length (unsigned LEB128, 1–4 bytes) || payload (CBOR, `length` bytes)
+```
+
+- `length` **MUST NOT** exceed 1 MiB (1,048,576) for control and RPC streams.
+ Receivers close the stream with `FRAME_TOO_LARGE` otherwise.
+- Bulk data (file contents, video) does **not** use frames. After its header
+ frame, a bulk stream switches to raw bytes as defined by its service.
+- All CBOR payloads are maps. Unknown keys **MUST** be ignored.
+
+### 3.1 Message envelope
+
+Every frame payload is an envelope:
+
+| Key | Type | Required | Meaning |
+|---|---|---|---|
+| `t` | text | yes | Message type, e.g. `hello`, `event.battery` |
+| `id` | uint | no | Request ID, unique per stream direction, for messages expecting a reply |
+| `re` | uint | no | The `id` this message replies to |
+| `b` | map | no | Message body (type-specific) |
+
+A receiver that gets an unknown `t` carrying an `id` **MUST** reply with
+`error` code `UNSUPPORTED`. Unknown `t` without an `id` is silently ignored.
+
+## 4. Streams
+
+| Stream | Opened by | Kind | Lifetime |
+|---|---|---|---|
+| **Control** | The dialing device | Bidirectional | The whole session. Must be the first stream opened |
+| **RPC / service** | Either device | Bidirectional | One operation (a request and its response, or a service sub-session) |
+| **Bulk** | Either device | Uni- or bidirectional | One transfer or media session |
+| **Datagrams** | Either device | QUIC datagrams | Loss-tolerant, latency-critical data (pointer motion, input) |
+
+Every non-control stream starts with a **stream header** frame:
+
+```
+t = "stream"
+b = { svc: text, op: text, v: uint }
+```
+
+`svc` names the service, `op` the operation, `v` the operation's version. If
+the receiver doesn't support it, it replies `error UNSUPPORTED` and closes the
+stream.
+
+Datagrams start with a one-byte channel tag (assigned per service in the
+service specs), followed by service-defined bytes.
+
+## 5. Session handshake
+
+After the QUIC handshake, the dialer opens the control stream and sends
+`hello`. The listener replies with its own `hello`. The session is
+**established** once both `hello`s are exchanged and the version check passes.
+
+```
+t = "hello"
+b = {
+ proto: uint, // protocol version spoken (0 for this document)
+ min: uint, // oldest protocol version this device still accepts
+ app: text, // app version, e.g. "0.1.0"
+ device: DeviceInfo,
+ caps: [text], // capability IDs this device offers (see §6)
+ power: text, // "basic" | "assist" | "elevated" | "root" | "n/a" (desktop)
+}
+
+DeviceInfo = {
+ name: text, // user-visible name, e.g. "Pixel 9"
+ kind: text, // "phone" | "tablet" | "desktop" | "laptop"
+ os: text, // "android" | "windows" | "macos"
+ os_ver: text, // "16" / "10.0.26200"
+ model: text?, // e.g. "Google Pixel 9"
+ accent: uint?, // optional ARGB seed color (Material You sync)
+}
+```
+
+**Version negotiation:** the session uses `min(proto_a, proto_b)`. If that is
+below either side's `min`, the side that detects it sends `error
+VERSION_TOO_OLD` and closes the connection, and both UIs tell the user which
+side needs an update.
+
+Either device may send an updated `hello.update` on the control stream at any
+time (for example when the power level or capabilities change):
+
+```
+t = "hello.update"
+b = { caps: [text]?, power: text?, device: DeviceInfo? }
+```
+
+## 6. Capabilities
+
+A capability ID is a dotted string naming something a device *can offer*,
+for example:
+
+| Capability | Offered by | Meaning |
+|---|---|---|
+| `core.ping` | both | Responds to ping |
+| `device.battery` | both | Sends battery events |
+| `notify.mirror` | phone | Can forward notifications |
+| `notify.sensitive` | phone | Can forward sensitive (OTP) notifications |
+| `clip.read.auto` | phone | Can read the clipboard in the background |
+| `mirror.elevated` | phone | Prompt-free mirroring with full control |
+
+Capabilities describe **what the device can do right now** given its power
+level, OS version, permissions and add-ons. Each app combines both devices'
+capabilities with its own local state to compute the **capability matrix**
+that drives the UI (see `docs/architecture/capabilities.md`). The full
+registry of capability IDs lives in `docs/protocol/capabilities.md` and grows
+with each service.
+
+## 7. Messages in v0
+
+### 7.1 Heartbeat
+
+QUIC keep-alives keep NAT bindings open. In addition, either side **MAY** send
+on the control stream:
+
+```
+t = "ping" id = n b = { ts: uint } // sender's monotonic ms
+t = "pong" re = n b = { ts: uint } // echoes ts
+```
+
+A session with no traffic for 45 s **SHOULD** send a `ping`. Implementations
+measure round-trip time from `ping`/`pong` for the connection-health indicator.
+
+### 7.2 Events
+
+Events are one-way notifications on the control stream. Their type starts
+with `event.`.
+
+```
+t = "event.battery"
+b = { level: uint (0–100), charging: bool, plugged: text? ("ac"|"usb"|"wireless") }
+
+t = "event.device"
+b = DeviceInfo // name or accent changed
+```
+
+### 7.3 Find my device
+
+```
+t = "device.ring" id = n b = { on: bool } // start or stop ringing
+t = "ok" re = n
+```
+
+### 7.4 Errors
+
+```
+t = "error" re = n? b = { code: text, msg: text? }
+```
+
+## 8. Error codes
+
+| Code | Meaning |
+|---|---|
+| `UNSUPPORTED` | Unknown message type, service or operation version |
+| `UNPAIRED` | Peer is not in the trust store (also used as the QUIC close reason) |
+| `VERSION_TOO_OLD` | Protocol version below the receiver's minimum |
+| `FRAME_TOO_LARGE` | Frame exceeds the size limit |
+| `BAD_MESSAGE` | Malformed CBOR or missing required fields |
+| `DENIED` | The user or a per-device permission denied the operation |
+| `BUSY` | Temporarily unable; retry later |
+| `INTERNAL` | Unexpected failure on the receiver |
+
+## 9. Pairing (`nectarlink-pair/0`)
+
+Pairing establishes mutual trust between two Device IDs. Two flows are
+defined. Both run over a `nectarlink-pair/0` QUIC connection, so the TLS layer
+already authenticates the raw public keys; the ceremony proves that the
+**human** intended *this* peer.
+
+### 9.1 QR flow (primary)
+
+1. The PC enters pairing mode, generates a random 128-bit **pairing secret**
+ `S`, and shows a QR code containing a pairing URI:
+
+ ```
+ nectarlink://pair?v=0&id=<pc device id, z-base-32>&s=<S, base64url>&n=<pc name, percent-encoded>[&a=<ip:port>,...]
+ ```
+
+2. The phone scans it and dials the PC's Device ID with ALPN
+ `nectarlink-pair/0`.
+3. The phone sends:
+
+ ```
+ t = "pair.request" id = 1
+ b = { device: DeviceInfo,
+ proof: bytes } // HMAC-SHA256(S, "nectarlink-pair-v0" || phone_id || pc_id)
+ ```
+
+4. The PC verifies `proof` against the phone's TLS-authenticated Device ID. On
+ success it stores the phone as trusted and replies:
+
+ ```
+ t = "pair.accept" re = 1 b = { device: DeviceInfo }
+ ```
+
+ On failure it replies `error DENIED` and leaves pairing mode after 5 failed
+ attempts.
+5. The phone stores the PC as trusted. Both devices close the pairing
+ connection and open a normal `nectarlink/0` session.
+
+Because the phone learned the PC's Device ID from the QR code and the PC
+verifies knowledge of `S`, both directions are authenticated with no codes to
+compare.
+
+### 9.2 Nearby flow (numeric comparison)
+
+Used when the user picks a discovered device instead of scanning. The
+initiator is **A**, the responder **B**.
+
+1. A → B: `pair.commit { device, c }` where `c = SHA-256(nA)` and `nA` is a
+ random 16-byte nonce.
+2. B → A: `pair.nonce { device, nB }` with a random 16-byte nonce `nB`.
+3. A → B: `pair.reveal { nA }`. B checks `SHA-256(nA) == c`.
+4. Both compute the **short authentication string**:
+
+ ```
+ sas = uint32(HMAC-SHA256(nA || nB, "nectarlink-sas-v0" || idA || idB)[0..4]) mod 1,000,000
+ ```
+
+ shown as a 6-digit code on both screens.
+5. The user confirms the codes match on **both** devices. Each sends
+ `pair.confirm`. Only after receiving the peer's `pair.confirm` and
+ confirming locally does each device store the other as trusted.
+
+The commitment in step 1 prevents an attacker from choosing a nonce to force a
+matching code; a man-in-the-middle would have different Device IDs on each
+side and therefore different codes.
+
+### 9.3 USB flow
+
+When an ADB connection exists, the PC can exchange Device IDs with the phone
+app over ADB directly. Specified in v0.1 together with the ADB integration.
+
+### 9.4 Unpairing
+
+Either device may send `pair.revoke` on an established session, then deletes
+the trust entry. A device receiving it deletes its entry too. Unpairing
+locally without notifying the peer is always allowed; the peer will then be
+rejected with `UNPAIRED` on its next connection attempt.
+
+## 10. Compatibility rules
+
+1. Adding a message type, a field, a capability or a service is **not** a
+ breaking change.
+2. Removing or changing the meaning of a field, message or operation **is**
+ breaking: it requires a new operation version (`v`) or a new protocol
+ version.
+3. Every app version **MUST** keep accepting the previous two protocol
+ versions once v1 ships.
+4. CI runs the current build against the previous two releases in both
+ directions.
+
+## 11. Security notes
+
+- Device keys are stored encrypted at rest (DPAPI on Windows, Android Keystore
+ wrapping on Android).
+- The pairing secret is single-use, kept only in memory, and expires with
+ pairing mode.
+- Implementations **MUST NOT** log message bodies of notification, message,
+ clipboard or file-name content.
+- Frame and message decoders are fuzzed in CI.