From 6c9fd00b8a001cb1b9458436ce19dc939d8bba70 Mon Sep 17 00:00:00 2001 From: sirius Date: Sat, 12 Sep 2026 17:57:15 -0400 Subject: [PATCH 1/8] =?UTF-8?q?ci(release):=20manual,=20batched=20releases?= =?UTF-8?q?=20=E2=80=94=20no=20release=20on=20merge?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Drop `push: branches: [main]` from both release workflows. release.yml now runs only via workflow_dispatch, with bump (default minor), version, tag and dry_run inputs; contradictory input is rejected instead of guessed at. android-release.yml keeps the Android assets on the same tag by subscribing to `push: tags: v*.*.*`: creating a tag over the API sends the same push notification a git push does, so the core's tag wakes it. No workflow_call — this Forgejo is 10.0.3, where reusable workflows are not supported. docs/RELEASING.md is the policy and procedure. --- .forgejo/workflows/android-release.yml | 18 ++-- .forgejo/workflows/release.yml | 77 +++++++++++---- README.md | 36 ++++--- docs/README.md | 2 + docs/RELEASING.md | 130 +++++++++++++++++++++++++ 5 files changed, 225 insertions(+), 38 deletions(-) create mode 100644 docs/RELEASING.md diff --git a/.forgejo/workflows/android-release.yml b/.forgejo/workflows/android-release.yml index ce98027..0307826 100644 --- a/.forgejo/workflows/android-release.yml +++ b/.forgejo/workflows/android-release.yml @@ -14,19 +14,17 @@ name: android-release # First automated version with zero tags: v0.1.0. Afterwards, patch+1 from the # latest v*.*.* tag UNLESS that tag's release is missing the Android assets — # then join it (core owns tag creation). Never move or delete a tag. +# +# No `push: branches: [main]` trigger: a merged android PR does not publish an +# APK. This workflow is woken by the tag release.yml creates for a manual, +# batched release — creating a tag over the API sends the same push +# notification a `git push` does, so the tag ref matches this filter. +# See docs/RELEASING.md. on: push: - branches: [main] - paths: - - "android/app/**" - - "android/sdk/**" - - "android/*.gradle.kts" - - "android/gradle/**" - - "android/gradle.properties" - - "android/settings.gradle.kts" - - "scripts/build-android-local.sh" - - ".forgejo/workflows/android-release.yml" + tags: + - "v*.*.*" workflow_dispatch: inputs: tag: diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml index b510a80..613c54d 100644 --- a/.forgejo/workflows/release.yml +++ b/.forgejo/workflows/release.yml @@ -1,23 +1,32 @@ name: release -# Auto-tag and publish both Linux binaries when core paths land on main. -# Tag-push is intentionally NOT a trigger: this workflow creates the tag via -# the API, and a tag-push hook would start a second run of the same release. -# Rebuild an existing tag (or dry-run a build) with workflow_dispatch. -# Version: latest v*.*.* tag → patch+1; zero tags → v0.1.0. +# Manual, batched releases. There is deliberately NO push trigger: a merged +# PR does not mint a release. A maintainer dispatches this at a stopping point +# (a batch of work has landed and CI is green on main) — see docs/RELEASING.md. +# Tag-push is intentionally NOT a trigger here: this workflow creates the tag +# via the API, and a tag-push hook would start a second run of the same +# release. Creating the tag *does* fire android-release.yml's `push: tags` +# trigger, which is how the APK + AAR join the same release. +# Version: explicit `version`, else `bump` off the newest v*.*.* tag +# (default minor — a batched release is usually a feature set); zero tags → v0.1.0. on: - push: - branches: [main] - paths: - - "src/**" - - "crates/**" - - "Cargo.toml" - - "Cargo.lock" - - "scripts/release-body.md" workflow_dispatch: inputs: + bump: + description: Bump off the newest v*.*.* tag (ignored when version or tag is set) + required: false + type: choice + options: + - minor + - patch + - major + default: minor + version: + description: Explicit version MAJOR.MINOR.PATCH (or vMAJOR.MINOR.PATCH); overrides bump + required: false + type: string tag: - description: Existing tag to (re)build and publish (empty = next version) + description: Existing tag to (re)build and publish (empty = create the next version) required: false type: string dry_run: @@ -57,6 +66,8 @@ jobs: REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }} EVENT_NAME: ${{ github.event_name }} EVENT_SHA: ${{ github.sha }} + INPUT_BUMP: ${{ github.event.inputs.bump }} + INPUT_VERSION: ${{ github.event.inputs.version }} INPUT_TAG: ${{ github.event.inputs.tag }} INPUT_DRY_RUN: ${{ github.event.inputs.dry_run }} run: | @@ -69,7 +80,7 @@ jobs: true|True|TRUE|1|yes|YES) dry_run=true ;; esac fi - echo "event=$EVENT_NAME sha=$EVENT_SHA input_tag=${INPUT_TAG-} input_dry_run=${INPUT_DRY_RUN-} dry_run=$dry_run" + echo "event=$EVENT_NAME sha=$EVENT_SHA input_version=${INPUT_VERSION-} input_tag=${INPUT_TAG-} input_bump=${INPUT_BUMP-} input_dry_run=${INPUT_DRY_RUN-} dry_run=$dry_run" api_curl() { curl -sS --http1.1 --retry 5 --retry-all-errors --retry-delay 3 \ @@ -78,6 +89,13 @@ jobs: } input_tag="${INPUT_TAG:-}" + version_input="${INPUT_VERSION:-}" + bump="${INPUT_BUMP:-minor}" + # Contradictory input is rejected, never guessed at. + if [ -n "$input_tag" ] && [ -n "$version_input" ]; then + echo "got both tag='$input_tag' and version='$version_input': tag rebuilds an existing tag, version mints a new one — pass one" >&2 + exit 1 + fi if [ -n "$input_tag" ]; then code=$(api_curl -o /tmp/tag.json -w '%{http_code}' \ "$REPO_API/tags/$input_tag") @@ -91,8 +109,33 @@ jobs: created=false echo "re-publish existing tag $tag at $sha (dry_run=$dry_run)" else - api_curl "$REPO_API/tags?limit=50" -o /tmp/tags.json - tag=$(python3 -c "import json,re; tags=json.load(open('/tmp/tags.json')); assert isinstance(tags, list), tags; semver=[]; [semver.append((int(m[1]), int(m[2]), int(m[3]))) for t in tags for m in [re.fullmatch(r'v([0-9]+)\.([0-9]+)\.([0-9]+)', t.get('name') or '')] if m]; print('v0.1.0' if not semver else 'v%d.%d.%d' % (max(semver)[0], max(semver)[1], max(semver)[2] + 1))") + if [ -n "$version_input" ]; then + tag=$(python3 -c "import re,sys; m=re.fullmatch(r'v?([0-9]+)\.([0-9]+)\.([0-9]+)', sys.argv[1].strip()); print('v' + '.'.join(m.groups()) if m else '')" "$version_input") + if [ -z "$tag" ]; then + echo "version must be MAJOR.MINOR.PATCH or vMAJOR.MINOR.PATCH, got '$version_input'" >&2 + exit 1 + fi + else + case "$bump" in + patch|minor|major) ;; + *) echo "bump must be patch|minor|major, got '$bump'" >&2; exit 1 ;; + esac + api_curl "$REPO_API/tags?limit=50" -o /tmp/tags.json + latest=$(python3 -c "import json,re; tags=json.load(open('/tmp/tags.json')); assert isinstance(tags, list), tags; s=[tuple(int(x) for x in m.groups()) for t in tags for m in [re.fullmatch(r'v([0-9]+)\.([0-9]+)\.([0-9]+)', t.get('name') or '')] if m]; print('%d.%d.%d' % max(s) if s else '')") + if [ -z "$latest" ]; then + tag="v0.1.0" + else + major="${latest%%.*}" + rest="${latest#*.}" + minor="${rest%%.*}" + patch="${rest#*.}" + case "$bump" in + major) tag="v$((major + 1)).0.0" ;; + minor) tag="v$major.$((minor + 1)).0" ;; + patch) tag="v$major.$minor.$((patch + 1))" ;; + esac + fi + fi sha="$EVENT_SHA" created=false if [ "$dry_run" = "true" ]; then diff --git a/README.md b/README.md index 82aeb2c..1dd232b 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ Arti onion services are still **experimental**. If the hidden service cannot com ### Option A — download a release binary -CI (`.forgejo/workflows/release.yml`) tags and publishes both Linux binaries on every `main` push that touches the core (`src/`, `crates/`, `Cargo.toml`, `Cargo.lock`, or `scripts/release-body.md`). Workflow-only edits do not mint a release — validate those with Actions → release → `dry_run=true`. aarch64 builds on the Pi runner; x86_64 builds on the amd64 runner. Both attach to the same [Forgejo release](https://forgejo.siriusdevops.com/sirius/onionwire/releases). `scripts/build-release-local.sh` remains the offline x86_64 fallback. This Forgejo does not serve `/releases/latest/download/…` (404); pin the tag. +CI (`.forgejo/workflows/release.yml`) does **not** release on a merge. Releases are manual and batched: a maintainer runs the workflow at a stopping point (Actions → release → Run workflow, `dry_run=true` first), which tags the next `v*.*.*` version and publishes both Linux binaries — aarch64 on the Pi runner, x86_64 on the amd64 runner — to one [Forgejo release](https://forgejo.siriusdevops.com/sirius/onionwire/releases), with the Android APK + AAR attached to that same tag. Policy and inputs: [docs/RELEASING.md](docs/RELEASING.md). `scripts/build-release-local.sh` remains the offline x86_64 fallback. This Forgejo does not serve `/releases/latest/download/…` (404); pin the tag. **x86_64 (most PCs / VMs):** @@ -269,20 +269,34 @@ rationale, the 16 KB page-size check and the signing story are in ## Releases (maintainers) -A core change on `main` is enough. The release workflow computes the next -`v*.*.*` tag (patch+1, or `v0.1.0` if there are no tags), creates it via the -API, builds aarch64 on the Pi runner and x86_64 on the amd64 runner, and -publishes all four assets (`onionwire-` + `.sha256`) to one release. -Do not push tags by hand — a tag-push trigger would start a second run. +Releases are **manual and batched**: no merge publishes anything, and neither +does a tag push. Cut one when a batch of work has reached a stopping point — +CI green on `main`, the feature set landed, no half-merged stack. Full policy +and procedure: [`docs/RELEASING.md`](docs/RELEASING.md). + +Actions → release → Run workflow: + +| Input | Meaning | +|---|---| +| `dry_run` | build + checksum both Linux binaries, no tag, no publish. Run this first. | +| `bump` | `patch` / `minor` / `major` off the newest `v*.*.*` tag. Default `minor`. | +| `version` | explicit `X.Y.Z` (or `vX.Y.Z`) — overrides `bump`. | +| `tag` | rebuild / re-publish an existing tag instead of minting one. | + +Pass `tag` **or** `version`, not both; an unparseable version is rejected +rather than guessed at. The workflow computes the version, creates the tag over +the API (refusing to move an existing tag), builds aarch64 on the Pi runner and +x86_64 on the amd64 runner, and publishes all four assets (`onionwire-` ++ `.sha256`) to one release. Creating that tag fires `android-release.yml`, +which builds the APK + AAR and joins the same release. If a build or the +publish fails, the run deletes the tag it created. Do not push tags by hand — +`release.yml` has no tag-push trigger, so a hand-pushed tag would build +nothing. ```bash # optional: keep Cargo.toml in sync with the tag the workflow will mint # (the workflow does not edit Cargo.toml) -# rebuild / re-publish an existing tag, or dry-run a build with no tag: -# Actions → release → Run workflow → tag=vX.Y.Z and/or dry_run=true -# (dry_run is how you test release.yml without cutting a user-facing release) - # offline x86_64 fallback (idempotent — safe to re-run) FORGEJO_TOKEN= scripts/build-release-local.sh vX.Y.Z ``` @@ -290,7 +304,7 @@ FORGEJO_TOKEN= scripts/build-release-local.sh vX.Y.Z Workflows (Forgejo Actions, `.forgejo/workflows/`): - [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite. Pi runner, `docker` label. -- [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — on core paths to `main` (`src/`, `crates/`, `Cargo.toml`, `Cargo.lock`, `scripts/release-body.md`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release. `workflow_dispatch` rebuilds a tag or `dry_run`s. Concurrency group `onionwire-ci-pi` (same as `ci.yml`, `cancel-in-progress: false`) so cargo jobs do not overlap on the Pi. Amd64 dind is serialized by runner `capacity=1`. +- [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — manual, batched release (`workflow_dispatch` only: `dry_run`, `bump`, `version`, `tag`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release, fail-closed tag delete on failure. The tag it creates fires [`android-release.yml`](.forgejo/workflows/android-release.yml) (`push: tags: v*.*.*`), which joins the same release with the APK + AAR. Concurrency group `onionwire-ci-pi` (same as `ci.yml`, `cancel-in-progress: false`) so cargo jobs do not overlap on the Pi. Amd64 dind is serialized by runner `capacity=1`. Scripts: diff --git a/docs/README.md b/docs/README.md index f18339a..f6ce9ab 100644 --- a/docs/README.md +++ b/docs/README.md @@ -12,3 +12,5 @@ Read these in order if you are evaluating the protocol without the Rust: Operator / product docs stay in the [root README](../README.md). Android build notes: [android/README.md](../android/README.md). SDK: [crates/onionwire-sdk/README.md](../crates/onionwire-sdk/README.md). +Maintainers cutting a release: [RELEASING.md](RELEASING.md) — manual, batched +releases, not one per merge. diff --git a/docs/RELEASING.md b/docs/RELEASING.md new file mode 100644 index 0000000..f605b04 --- /dev/null +++ b/docs/RELEASING.md @@ -0,0 +1,130 @@ +# Releasing OnionWire + +Policy and procedure for cutting a release. Read +[`README.md`](../README.md#releases-maintainers) for the short version. + +## Policy: manual, batched releases + +A merge does **not** publish anything. Neither does a tag push. + +A release happens when a **batch of work has reached a stopping point**, chosen +by hand: + +- CI is green on `main` (the `ci` workflow passed for the last push), and +- the feature set you mean to ship has landed — not a half-merged stack, + not a branch you are about to rewrite, and +- you are ready to answer user reports against the version you are about to + stamp. + +Everything else about the pipeline is unchanged: both architectures, one +tagged release, `.sha256` for every asset, the fail-closed "delete the tag we +created if the build or publish fails", and the dry-run path. + +## Procedure + +1. **Confirm the stopping point.** `main` is the commit you want to release, + its CI run is green, and nothing you intend to include is still in an open + PR. The release workflow packages whatever `main`'s head is when the tag is + created. +2. **Dry-run it.** Actions → **release** → *Run workflow*, `dry_run=true`. + That builds and checksums both Linux binaries with no tag and no publish, + so it proves the pipeline without stamping a version. (A dry run does not + build the Android APK — there is no tag, so nothing wakes + `android-release`.) +3. **Cut the release.** Actions → **release** → *Run workflow* with + `dry_run=false` (the default) and the bump you want. The version must not + already be tagged. +4. **Watch it.** The run name is `release`; `scripts/watch-release-run.sh` + reports job status (it reads `action_run`/`action_run_job` on the Pi's + database, so it works for dispatched runs as well as any other). +5. **Check the assets.** Open the release page (or + `GET /api/v1/repos/sirius/onionwire/releases/tags/`) and require a + non-zero `size` for every asset: the two Linux binaries + `.sha256`, the + APK + `.sha256`, the AAR + `.sha256`. A green run is not proof — the Pi + runner hairpins through Cloudflare and has uploaded 0-byte assets before. + +## Inputs + +| Input | Default | Meaning | +|---|---|---| +| `dry_run` | `false` | Build + checksum only. No tag, no publish. | +| `bump` | `minor` | `patch` / `minor` / `major` off the newest `v*.*.*` tag. | +| `version` | — | Explicit `X.Y.Z` or `vX.Y.Z`; overrides `bump`. | +| `tag` | — | Rebuild / re-publish an existing tag instead of minting a new one. | + +Contradictory input is rejected, never guessed at: + +- `tag` **and** `version` together → the run fails in the `version` job. +- `version` that is not `MAJOR.MINOR.PATCH` (optionally `v`-prefixed) → fails. +- `bump` outside `patch|minor|major` → fails. + +## What the run does + +`version` job (Pi runner): + +1. Resolves the tag: the `tag` input, else the `version` input, else `bump` + applied to the newest `v*.*.*` tag (`v0.1.0` when the repo has no tags). +2. When minting a new version, creates the tag over the Forgejo API. If the + tag already exists on a different commit, the run **refuses to move it** + and fails. `201` means created; `409` means it was created concurrently and + this run joins it. + +`aarch64` (Pi runner) and `x86_64` (amd64 runner) jobs build the binary in a +`rust:*-bookworm` container, strip it, refuse an empty binary, write the +`.sha256`, and upload it as an artifact. + +`publish` job (Pi runner) downloads both artifacts, refuses any empty file, +and calls `scripts/publish-release.sh` to create-or-update the release with all +four Linux assets. If this job fails and the tag was created by *this* run, the +final step deletes the incomplete release and the tag. A failed `aarch64` or +`x86_64` job always fails `publish`, so nothing is published half-built. + +## Android (APK + AAR) on the same tag + +Creating the tag sends the same push notification a `git push` would, and +[`android-release.yml`](../.forgejo/workflows/android-release.yml) is +subscribed to `push: tags: v*.*.*`. The core workflow therefore does not call +it, and no `main`-push trigger exists on either file. + +That run builds the signed APK and the SDK AAR on the **amd64** runner (the Pi +is aarch64 and cannot produce an APK), then a second job on the Pi attaches the +APK + AAR + `.sha256` to the same tag. If the release does not exist yet it is +created; if it exists it is joined (`publish-release.sh` is create-or-update). +Android assets land on the release a while after the Linux ones — the Android +build is the long pole. + +The workflow also has `workflow_dispatch` with the same `tag` / `dry_run` +inputs, which is how you repair or re-attach the Android assets by hand. + +## Rebuilding an existing tag + +- **Both** Linux binaries: dispatch `release` with `tag=vX.Y.Z`. The tag's own + commit is built, its existing assets are replaced, and no new tag is created. +- **Android only**: dispatch `android-release` with `tag=vX.Y.Z`. +- The local `FORGEJO_TOKEN= scripts/build-release-local.sh vX.Y.Z` + fallback does the x86_64 build without CI. + +Never move or delete a published `v*.*.*` tag by hand, and never create one by +hand: a hand-pushed tag starts nothing (`release.yml` has no tag-push trigger), +and `release.yml` will refuse to move a tag that exists on another commit. + +## Version policy + +`MAJOR.MINOR.PATCH` on the tag (`v`-prefixed). The default bump is `minor`: a +batched release is usually a feature set, and `patch`-incrementing it would +mislabel it. Use `patch` for a fix-only batch, `major` for a breaking wire or +store change. The tag is the version users see; `Cargo.toml` is **not** edited +by the workflow — keep it in sync by hand if the crate version matters to you. +The Android `versionCode` is derived by the Android workflow from +`major*10000 + minor*100 + patch`. + +## What the workflows do not gate on + +- **No "CI must be green" check inside the release job.** The operator checks + that by hand before dispatching. A release dispatched while CI is red will + build and publish anyway. +- No changelog generation: `scripts/release-body.md` is the template, with + `@TAG@` substituted. +- No approval gate, no environment protection, no automatic rollback beyond + the fail-closed tag delete described above. +- No notification on success: read the run and the release page. From 381f4247339be5d1e26ee7bf2c8f08213f085497 Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 12 Sep 2026 18:16:21 -0400 Subject: [PATCH 2/8] fix(sdk): surface Sent/Queued on send(), and build the SDK in CI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Node::send() became Result in the local-outbox work, which broke crates/onionwire-sdk — and nothing noticed, because the SDK is a separate cargo workspace that root CI never compiles. - Wire::send() returns WResult (Sent | Queued) - ChatMessage.delivery for outgoing rows - New sdk job in ci.yml (own target volume; rustls workspace) - Refresh SDK Cargo.lock + README (SQLCipher / outbox facts) Rebased onto main after #50/#54: no src/node.rs changes (WAL checkpoint lives in Store now). README at-rest claims kept from #55. --- .forgejo/workflows/ci.yml | 46 +++++++++++ README.md | 2 +- crates/onionwire-sdk/Cargo.lock | 25 ++++++ crates/onionwire-sdk/README.md | 20 +++-- crates/onionwire-sdk/src/lib.rs | 141 +++++++++++++++++++++++++++----- 5 files changed, 207 insertions(+), 27 deletions(-) diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml index 4c7b8aa..d922dfe 100644 --- a/.forgejo/workflows/ci.yml +++ b/.forgejo/workflows/ci.yml @@ -39,6 +39,11 @@ env: CARGO_REGISTRY_VOLUME: onionwire-cargo-registry CARGO_TARGET_VOLUME: onionwire-target-ci BUILD_CONTAINER: onionwire-ci-${{ github.run_id }} + # The SDK job gets its own target volume: it resolves the root crate with + # `rustls` instead of `native-tls`, so sharing a target dir would thrash both + # jobs' feature-unified artifacts. + SDK_CARGO_TARGET_VOLUME: onionwire-target-ci-sdk + SDK_BUILD_CONTAINER: onionwire-ci-sdk-${{ github.run_id }} jobs: test: @@ -73,3 +78,44 @@ jobs: tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees . \ | docker start -a -i "$BUILD_CONTAINER" docker rm -f "$BUILD_CONTAINER" > /dev/null + + # `crates/onionwire-sdk` is a SEPARATE cargo workspace: its own Cargo.lock and + # a path dependency on the root crate, resolved with `rustls` instead of + # `native-tls`. The `test` job above therefore never compiles it, so a + # root-crate signature change (`Node::send` gaining the outbox result, the + # SQLCipher passphrase entry points) breaks the Android SDK — and the tagged + # release AAR, since android-release.yml only builds on `v*.*.*` — while both + # the root suites and local `cargo test` stay green. Build it here. + sdk: + runs-on: docker + timeout-minutes: 120 + steps: + - name: Checkout + uses: https://code.forgejo.org/actions/checkout@v4 + + - name: cargo test + clippy for crates/onionwire-sdk on aarch64 + run: | + set -euo pipefail + cd "${GITHUB_WORKSPACE}" + echo "workspace: $GITHUB_WORKSPACE" + docker volume create "$CARGO_REGISTRY_VOLUME" > /dev/null + docker volume create "$SDK_CARGO_TARGET_VOLUME" > /dev/null + docker rm -f "$SDK_BUILD_CONTAINER" > /dev/null 2>&1 || true + docker create --name "$SDK_BUILD_CONTAINER" -i \ + -e CARGO_TARGET_DIR=/target \ + -e CARGO_BUILD_JOBS=2 \ + -e CARGO_TERM_COLOR=never \ + -v "$CARGO_REGISTRY_VOLUME":/usr/local/cargo/registry \ + -v "$SDK_CARGO_TARGET_VOLUME":/target \ + -w /src \ + "$RUST_IMAGE" \ + sh -euxc 'mkdir -p /src && tar xzf - -C /src && cd /src/crates/onionwire-sdk \ + && apt-get update \ + && apt-get install -y --no-install-recommends pkg-config libssl-dev \ + && rustup component add clippy \ + && cargo test --locked \ + && cargo clippy --locked --all-targets -- -D warnings' + tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees \ + --exclude=./crates/onionwire-sdk/target . \ + | docker start -a -i "$SDK_BUILD_CONTAINER" + docker rm -f "$SDK_BUILD_CONTAINER" > /dev/null diff --git a/README.md b/README.md index 5ae0162..4f0458f 100644 --- a/README.md +++ b/README.md @@ -286,7 +286,7 @@ FORGEJO_TOKEN= scripts/build-release-local.sh vX.Y.Z Workflows (Forgejo Actions, `.forgejo/workflows/`): -- [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite. Pi runner, `docker` label. +- [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — two jobs on the Pi runner (`docker` label), serialized by `onionwire-ci-pi`. `test`: `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` at the repo root. `sdk`: the same for `crates/onionwire-sdk` (separate cargo workspace — own `Cargo.lock`, root crate by path, `rustls` instead of `native-tls` — so a root signature change cannot silently break the Android SDK). Both run on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite. - [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — on core paths to `main` (`src/`, `crates/`, `Cargo.toml`, `Cargo.lock`, `scripts/release-body.md`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release. `workflow_dispatch` rebuilds a tag or `dry_run`s. Concurrency group `onionwire-ci-pi` (same as `ci.yml`, `cancel-in-progress: false`) so cargo jobs do not overlap on the Pi. Amd64 dind is serialized by runner `capacity=1`. Scripts: diff --git a/crates/onionwire-sdk/Cargo.lock b/crates/onionwire-sdk/Cargo.lock index 0422aac..62079af 100644 --- a/crates/onionwire-sdk/Cargo.lock +++ b/crates/onionwire-sdk/Cargo.lock @@ -2443,6 +2443,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91632f3b4fb6bd1d72aa3d78f41ffecfcf2b1a6648d8c241dbe7dbfaf4875e15" dependencies = [ "cc", + "openssl-sys", "pkg-config", "vcpkg", ] @@ -2774,6 +2775,7 @@ dependencies = [ "rusqlite", "safelog", "serde_json", + "sha2", "sha3 0.10.9", "snow", "tokio", @@ -2781,6 +2783,7 @@ dependencies = [ "tor-hsservice", "tor-rtcompat", "x25519-dalek", + "zeroize", ] [[package]] @@ -2801,6 +2804,28 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" +[[package]] +name = "openssl-src" +version = "300.6.1+3.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846" +dependencies = [ + "cc", +] + +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +dependencies = [ + "cc", + "libc", + "openssl-src", + "pkg-config", + "vcpkg", +] + [[package]] name = "option-ext" version = "0.2.0" diff --git a/crates/onionwire-sdk/README.md b/crates/onionwire-sdk/README.md index 36e25a5..9072542 100644 --- a/crates/onionwire-sdk/README.md +++ b/crates/onionwire-sdk/README.md @@ -18,8 +18,8 @@ onions directly. There is no `tor` binary, no torrc, no Orbot as the pipe. | Onion | A **locator**, not an identity. It rotates. | | Invite | `onionwire:v1:k=…:o=…:spk=…:sig=…` | | Crypto | Noise IK (`Noise_IK_25519_ChaChaPoly_BLAKE2s`). `spk` is x25519. | -| Fail closed | Peer onion down → the send fails. No outbox, no spool in v1. | -| At rest | Chat bodies encrypted (Argon2id wrap + ChaCha20-Poly1305). Identity keys in sqlite are plaintext — that is honest, not an oversight. | +| Chat send | Unreachable peer onion → the message goes to the **local outbox** and is retried with backoff. `send()` returns `SendState.Sent` or `SendState.Queued`. File transfer and payments stay fail-closed. | +| At rest | The whole sqlite file is SQLCipher (key = Argon2id of the store passphrase), and chat bodies carry a second per-row ChaCha20-Poly1305 layer with row-bound AAD. Identity keys live in that same encrypted file. | ### Invite string @@ -66,8 +66,10 @@ Requirements: ## Kotlin surface -Everything is a `suspend fun` — Arti bootstrap and onion publish take minutes, -and a send retries the peer for up to 3 minutes before failing. +Everything is a `suspend fun` — Arti bootstrap and onion publish take minutes. +A send that cannot reach the peer comes back immediately as `QUEUED` (it is not +a long retry inside the call): the message is stored locally and a background +worker in the core keeps retrying it. ```kotlin import uniffi.onionwire_sdk.* @@ -88,8 +90,16 @@ val friend: FriendInfo = wire.addFriend(pasted) // 4. Roster and chat. val roster: List = wire.friends() wire.setPetname(friend.pubkeyHex, "ada") -wire.send(friend.pubkeyHex, "hello wire") +when (wire.send(friend.pubkeyHex, "hello wire")) { + SendState.SENT -> { /* the peer's onion took the frame */ } + SendState.QUEUED -> { /* unreachable: stored in the local outbox and + retried in the background. Show it as pending — + it is local-only until a circuit takes it. */ } +} val msgs: List = wire.messages(friend.pubkeyHex) +// msgs[i].direction == "out" -> msgs[i].delivery is "sent" | "queued" | +// "sending" | "failed: "; null for incoming messages. Render the +// queued and failed states distinctly from sent. // 5. Locator rotation. Do NOT wire this to a single tap — the app that embeds // the SDK owns the typed confirmation. diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index 90e5b55..5657948 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -11,7 +11,10 @@ //! the friend. //! * Transport is in-process Arti. There is no `tor` binary, no torrc, no //! Orbot pipe. If the onion service cannot publish, this fails closed. -//! * Chat bodies are encrypted at rest. Identity keys in sqlite are not. +//! * Chat bodies are encrypted at rest, and the whole sqlite file is +//! SQLCipher on top of that (see the root crate). +//! * A chat send that cannot reach the peer's onion is queued in a local +//! outbox and retried — see [`SendState`]. Nothing leaves the device. //! //! Lifecycle: a node is started by [`open_wire`] and stopped by //! [`Wire::shutdown`]. Between those, [`Wire::tor_state`] is the observable @@ -27,7 +30,7 @@ use std::sync::{Arc, Mutex, OnceLock}; use onionwire::hs::TorState as CoreTorState; use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node}; -use onionwire::qr; +use onionwire::outbox::OutboxStatus;use onionwire::qr; uniffi::setup_scaffolding!(); @@ -98,11 +101,34 @@ pub struct FriendInfo { pub last_connect_ok: bool, } +/// What `send()` did with the message. +/// +/// The core has a local outbox: when a friend's onion is unreachable the +/// message is written to the local sqlite store and a background worker +/// retries it with backoff. Nothing is handed to a third party — every attempt +/// is a fresh handshake straight to that friend's onion — but until a circuit +/// takes it the message exists only on this device. A consumer must not render +/// `Queued` as delivered. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum SendState { + /// The frame reached the peer's onion service during this call. + Sent, + /// The peer's onion was unreachable: the message is in the local outbox, + /// local-only until the retry worker delivers it (or it ends `Failed`). + Queued, +} + #[derive(Debug, Clone, uniffi::Record)] pub struct ChatMessage { /// "in" or "out". pub direction: String, pub body: String, + /// Outgoing messages only: `"sent"`, `"queued"`, `"sending"` or + /// `"failed: "`. `None` for incoming messages. An outgoing row with + /// no outbox row is one the peer accepted on the first attempt, so it reads + /// `"sent"` — never treat a missing value as "delivered" on the app side, + /// read this field. + pub delivery: Option, } #[derive(Debug, Clone, uniffi::Record)] @@ -332,34 +358,44 @@ impl Wire { .map_err(WireError::new) } - /// Send one message. Returns once the outcome is known: delivered now, or - /// queued for retry because the peer's onion is unreachable. A protocol - /// error (bad signature, bad frame) still fails immediately and is never - /// queued. Use [`flush`](Self::flush) to retry the queue on demand. - pub async fn send(&self, pubkey_hex: String, body: String) -> WResult<()> { + /// Send one chat message. + /// + /// Returns [`SendState::Sent`] when the frame reached the peer's onion + /// service during this call, and [`SendState::Queued`] when it did not: the + /// message is then in the local outbox and a background worker retries it + /// with exponential backoff (30s doubling, capped at 30 min, 8 attempts) + /// until it lands or ends terminally failed. A queued send is local-only — + /// show it as pending, not delivered. + /// + /// A protocol error (signature mismatch, malformed or oversize frame) is + /// not retryable and still fails here; nothing is queued in that case. + pub async fn send(&self, pubkey_hex: String, body: String) -> WResult { let pk = unhex(&pubkey_hex)?; - self.node()? + let status = self + .node()? .send(&pk, body.as_bytes()) .await .map_err(WireError::new)?; - Ok(()) - } + Ok(send_state(status)) } /// Chat history for a friend, oldest first. Bodies are decrypted here; - /// they are stored encrypted at rest. + /// they are stored encrypted at rest. Outgoing rows carry their delivery + /// state in [`ChatMessage::delivery`]. pub async fn messages(&self, pubkey_hex: String) -> WResult> { let pk = unhex(&pubkey_hex)?; - let rows = self - .node()? - .list_messages(&pk) - .map_err(WireError::new)?; - Ok(rows - .into_iter() - .map(|m| ChatMessage { + let rows = self.node()?.list_messages(&pk).map_err(WireError::new)?; + let mut out = Vec::with_capacity(rows.len()); + for m in rows { + let status = self + .node()? + .outbox_status_of_message(m.id) + .map_err(WireError::new)?; + out.push(ChatMessage { body: String::from_utf8_lossy(&m.plaintext).into_owned(), + delivery: delivery_of(&m.dir, status), direction: m.dir, - body: String::from_utf8_lossy(&m.plaintext).into_owned(), - }) - .collect()) + }); + } + Ok(out) } /// Delete every message body. Identity and friends survive. @@ -415,6 +451,30 @@ fn unhex(s: &str) -> WResult> { .collect() } +/// `Node::send` only ever yields `Sent` or `Queued`; `Sending`/`Failed` exist +/// only on stored outbox rows. Everything that is not a completed send maps to +/// `Queued`, so a status this build does not know about is never reported as +/// delivered — the fail-safe direction for a caller that hides its retry UI. +fn send_state(status: OutboxStatus) -> SendState { + match status { + OutboxStatus::Sent => SendState::Sent, + _ => SendState::Queued, + } +} + +/// Delivery string for one stored chat row. `None` for incoming rows. An +/// outgoing row with no outbox row was accepted on the first attempt, so it is +/// reported as `"sent"` rather than left blank. +fn delivery_of(dir: &str, status: Option) -> Option { + if dir != "out" { + return None; + } + Some(match status { + None | Some(OutboxStatus::Sent) => "sent".to_string(), + Some(other) => other.to_string(), + }) +} + #[cfg(test)] mod tests { //! No Tor here on purpose: these exercise the *lifecycle* contract of the @@ -422,6 +482,7 @@ mod tests { //! node is exactly the state `shutdown()` leaves behind. use super::*; + use onionwire::outbox::OutboxStatus; fn stopped_wire() -> Wire { Wire { @@ -482,4 +543,42 @@ mod tests { ); assert_eq!(TorState::from(CoreTorState::Stopped), TorState::Stopped); } + +#[test] + fn sent_is_sent_everything_else_is_queued() { + assert_eq!(send_state(OutboxStatus::Sent), SendState::Sent); + assert_eq!(send_state(OutboxStatus::Queued), SendState::Queued); + // `Node::send` never returns these today, but they exist on stored + // rows. Unknown states map to `Queued` — the safe direction: never + // report a send as delivered unless the core says `Sent`. + assert_eq!(send_state(OutboxStatus::Sending), SendState::Queued); + assert_eq!( + send_state(OutboxStatus::Failed("no route".into())), + SendState::Queued + ); + } + + #[test] + fn delivery_is_reported_for_outgoing_rows_only() { + assert_eq!(delivery_of("in", Some(OutboxStatus::Queued)), None); + // Outgoing row with no outbox row: delivered on the first attempt. + assert_eq!(delivery_of("out", None).as_deref(), Some("sent")); + assert_eq!( + delivery_of("out", Some(OutboxStatus::Sent)).as_deref(), + Some("sent") + ); + assert_eq!( + delivery_of("out", Some(OutboxStatus::Queued)).as_deref(), + Some("queued") + ); + assert_eq!( + delivery_of("out", Some(OutboxStatus::Sending)).as_deref(), + Some("sending") + ); + assert_eq!( + delivery_of("out", Some(OutboxStatus::Failed("no route".into()))).as_deref(), + Some("failed: no route") + ); + } } + From 92d921e7599e22c663f800d44fdb7a2f4e65f937 Mon Sep 17 00:00:00 2001 From: Hermes apk-dev Date: Sat, 12 Sep 2026 15:47:14 -0400 Subject: [PATCH 3/8] fix(android): surface the outbox send state instead of denying it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The SDK has returned `SendState` and a per-row `ChatMessage.delivery` since the local outbox landed, but the app still said "there is no outbox in v1" and threw the state away. - `WireViewModel.send()` returns `SendState`; `ChatScreen` no longer discards it. A `QUEUED` send raises a "local-only until the retry worker gets a circuit through" hint instead of pretending success. - Outgoing rows render the TUI's delivery markers from `ChatMessage.delivery` (`✓` / `◷ queued` / `» sending` / `✗ failed: `), plus the TUI's `{n} queued` footer while the outbox still owns rows. Incoming rows stay unmarked; an unreadable state renders no marker rather than a tick. - The empty-chat copy describes the outbox (8 attempts, backoff capped at 30 min, local-only until it lands) instead of denying it exists. - New pure `Delivery.kt` so the vocabulary is unit-testable without a device. Verified: `./gradlew :app:assembleDebug :app:testDebugUnitTest` → BUILD SUCCESSFUL, 15 tests / 0 failures (10 new), APK contains the new copy and no longer the "There is no outbox" string. Stacked on the SDK fix (PR #51). --- .../siriusdevops/onionwire/WireViewModel.kt | 11 +- .../siriusdevops/onionwire/ui/ChatScreen.kt | 116 +++++++++++++++--- .../com/siriusdevops/onionwire/ui/Delivery.kt | 78 ++++++++++++ .../onionwire/ui/DeliveryMarkerTest.kt | 85 +++++++++++++ 4 files changed, 271 insertions(+), 19 deletions(-) create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/Delivery.kt create mode 100644 android/app/src/test/java/com/siriusdevops/onionwire/ui/DeliveryMarkerTest.kt diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index 579de57..6b72d75 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -21,6 +21,7 @@ import uniffi.onionwire_sdk.ChatMessage import uniffi.onionwire_sdk.FriendInfo import uniffi.onionwire_sdk.InviteInfo import uniffi.onionwire_sdk.RotateOutcome +import uniffi.onionwire_sdk.SendState import uniffi.onionwire_sdk.Wire import uniffi.onionwire_sdk.decodeInvite import java.io.File @@ -361,7 +362,15 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { suspend fun messages(pubkeyHex: String): List = requireWire().messages(pubkeyHex) - suspend fun send(pubkeyHex: String, body: String) = + /** + * Hands the body to the node and reports what happened to it. + * + * `SENT` means the peer's onion took the frame during this call. `QUEUED` + * means it did not: the message is in the local outbox, local-only until + * the retry worker gets a circuit through. The caller must not render + * `QUEUED` as delivered. + */ + suspend fun send(pubkeyHex: String, body: String): SendState = requireWire().send(pubkeyHex, body) suspend fun wipeMessages() { diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt index fbfa709..9bffca7 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt @@ -37,6 +37,12 @@ import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.dp import kotlinx.coroutines.delay import uniffi.onionwire_sdk.ChatMessage +import uniffi.onionwire_sdk.SendState + +/** Shown after a `Queued` send — the TUI's composer keeps `{n} queued`. */ +private const val QUEUED_HINT = + "Queued: their onion is unreachable. The message is local-only in this " + + "device's outbox until the retry worker gets a circuit through." @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -45,13 +51,14 @@ fun ChatScreen( fingerprint: String, onion: String, loadMessages: suspend () -> List, - onSend: suspend (String) -> Unit, + onSend: suspend (String) -> SendState, onBack: () -> Unit, ) { var messages by remember { mutableStateOf?>(null) } var draft by remember { mutableStateOf("") } var pending by remember { mutableStateOf(null) } var error by remember { mutableStateOf(null) } + var hint by remember { mutableStateOf(null) } val listState = rememberLazyListState() // Poll: the node appends inbound messages in the background; there is no @@ -65,16 +72,32 @@ fun ChatScreen( } } - // Fail-closed send. `send` retries the peer's onion for up to 3 minutes and - // then errors — nothing is spooled, so a failure is a real failure. + // Fail closed — but not fail lost. `send` returns `Queued` when the peer's + // onion is unreachable: the body is in this device's local outbox and the + // retry worker keeps trying. It only surfaces as a hard error when the + // node itself refuses the write. LaunchedEffect(pending) { val body = pending ?: return@LaunchedEffect error = null + hint = null runCatching { onSend(body) } + .onSuccess { state -> + // Never dress a queued send up as delivered. + hint = if (state == SendState.QUEUED) QUEUED_HINT else null + } .onFailure { error = it.message ?: it.toString() } pending = null } + // The hint is a toast, not a log line: the row marker and the `N queued` + // footer are what stay on screen. + LaunchedEffect(hint) { + if (hint != null) { + delay(6_000) + hint = null + } + } + LaunchedEffect(messages?.size) { val n = messages?.size ?: 0 if (n > 0) listState.animateScrollToItem(n - 1) @@ -127,8 +150,13 @@ fun ChatScreen( Text("No messages", style = MaterialTheme.typography.titleSmall) Spacer(Modifier.height(6.dp)) Text( - "Sends fail closed: if their onion is down the message is " + - "not spooled anywhere. There is no outbox in v1.", + "Sends fail closed — nothing goes to a third party. If their " + + "onion is unreachable the message is queued in this " + + "device's outbox instead of being dropped: it stays " + + "local-only until the retry worker gets a circuit " + + "through (8 attempts, backoff capped at 30 min), then it " + + "lands. \u2713 means delivered, \u25f7 queued, " + + "\u2717 failed.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -149,25 +177,77 @@ fun ChatScreen( horizontalArrangement = if (mine) Arrangement.End else Arrangement.Start, ) { - Text( - m.body, - style = MaterialTheme.typography.bodyMedium, - color = if (mine) MaterialTheme.colorScheme.onPrimary - else MaterialTheme.colorScheme.onSurface, - modifier = Modifier - .background( - if (mine) MaterialTheme.colorScheme.primary - else MaterialTheme.colorScheme.surfaceVariant, - RoundedCornerShape(10.dp), - ) - .padding(horizontal = 10.dp, vertical = 8.dp), - ) + Column( + horizontalAlignment = + if (mine) Alignment.End else Alignment.Start, + ) { + Text( + m.body, + style = MaterialTheme.typography.bodyMedium, + color = if (mine) MaterialTheme.colorScheme.onPrimary + else MaterialTheme.colorScheme.onSurface, + modifier = Modifier + .background( + if (mine) MaterialTheme.colorScheme.primary + else MaterialTheme.colorScheme.surfaceVariant, + RoundedCornerShape(10.dp), + ) + .padding(horizontal = 10.dp, vertical = 8.dp), + ) + // Outgoing rows only: the SDK reports `null` for + // inbound, and an outgoing row with no outbox + // entry reads "sent". + if (mine) { + deliveryMarker(m.delivery)?.let { marker -> + Text( + marker.text, + style = MaterialTheme.typography.labelSmall, + fontFamily = FontFamily.Monospace, + color = when (marker.tone) { + DeliveryTone.SENT -> + MaterialTheme.colorScheme.onSurfaceVariant + + DeliveryTone.PENDING -> + MaterialTheme.colorScheme.tertiary + + DeliveryTone.FAILED -> + MaterialTheme.colorScheme.error + }, + modifier = Modifier.padding( + top = 2.dp, + end = 2.dp, + ), + ) + } + } + } } } } } } + // TUI footer: `{n} queued` while the outbox still owns rows. + val queued = list?.count { it.direction == "out" && isOutboxPending(it.delivery) } ?: 0 + if (queued > 0) { + Text( + "$queued queued", + style = MaterialTheme.typography.labelSmall, + fontFamily = FontFamily.Monospace, + color = MaterialTheme.colorScheme.tertiary, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) + } + + hint?.let { + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.tertiary, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) + } + error?.let { Text( it, diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/Delivery.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/Delivery.kt new file mode 100644 index 0000000..a26766d --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/Delivery.kt @@ -0,0 +1,78 @@ +package com.siriusdevops.onionwire.ui + +/** + * Per-row delivery markers for outgoing chat messages. + * + * The vocabulary is the TUI's (`docs/TUI.md` → "Delivery state (outbox)"), so + * both clients read the same: + * + * ``` + * ✓ delivered — the peer's onion took the frame + * ◷ queued in this device's local outbox, waiting for a circuit + * » sending the retry worker has it in flight + * ✗ failed: … terminally failed (8 attempts, backoff capped at 30 min) + * ``` + * + * The string comes from `ChatMessage.delivery` and is produced by the store's + * own outbox status — `"sent"` / `"queued"` / `"sending"` / + * `"failed: "` for outgoing rows, `null` for incoming ones. An outgoing + * row with no outbox row was accepted on the first attempt and reads `"sent"`. + * + * Nothing here guesses: a delivery string this build does not recognise renders + * no marker rather than a tick, because a missing marker never claims delivery + * while a wrong tick does. + */ + +/** Which colour the marker is drawn in. */ +internal enum class DeliveryTone { + /** Delivered to the peer's onion. */ + SENT, + + /** Still local-only: queued, or being retried right now. */ + PENDING, + + /** Out of attempts — the message never left this device. */ + FAILED, +} + +internal data class DeliveryMarker(val text: String, val tone: DeliveryTone) + +/** + * Longest `failed: ` tail we render before eliding. The TUI caps the + * same reason at 24 cells for its 80-column row; a phone bubble wraps, so this + * only exists to stop a pathological Tor error from filling the screen. + */ +private const val MAX_REASON_CHARS = 48 + +/** Marker for one outgoing row, or `null` when there is nothing to say. */ +internal fun deliveryMarker(delivery: String?): DeliveryMarker? { + val state = delivery?.trim().orEmpty() + if (state.isEmpty()) return null + return when { + state == "sent" -> DeliveryMarker("\u2713", DeliveryTone.SENT) + state == "queued" -> DeliveryMarker("\u25f7 queued", DeliveryTone.PENDING) + state == "sending" -> DeliveryMarker("\u00bb sending", DeliveryTone.PENDING) + state.startsWith("failed") -> { + val reason = shortReason(state.substringAfter(':', "").trim()) + DeliveryMarker( + if (reason.isEmpty()) "\u2717 failed" else "\u2717 failed: $reason", + DeliveryTone.FAILED, + ) + } + // Unknown state: never render a tick for something we cannot read. + else -> null + } +} + +/** True while the outbox still owns the row — the TUI's `{n} queued` footer. */ +internal fun isOutboxPending(delivery: String?): Boolean { + val state = delivery?.trim().orEmpty() + return state == "queued" || state == "sending" +} + +private fun shortReason(reason: String): String = + if (reason.length <= MAX_REASON_CHARS) { + reason + } else { + reason.take(MAX_REASON_CHARS - 1).trimEnd() + "\u2026" + } diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/DeliveryMarkerTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/DeliveryMarkerTest.kt new file mode 100644 index 0000000..6340190 --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/DeliveryMarkerTest.kt @@ -0,0 +1,85 @@ +package com.siriusdevops.onionwire.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The delivery vocabulary is shared with the TUI (`docs/TUI.md` → "Delivery + * state (outbox)"). These strings are the SDK's contract + * (`crates/onionwire-sdk/src/lib.rs`), so a drift here is a client that lies + * about a message having landed. + */ +class DeliveryMarkerTest { + + @Test + fun delivered_row_gets_a_tick() { + val m = deliveryMarker("sent") + assertEquals(DeliveryMarker("\u2713", DeliveryTone.SENT), m) + } + + @Test + fun queued_row_says_queued_not_delivered() { + val m = deliveryMarker("queued") + assertEquals(DeliveryMarker("\u25f7 queued", DeliveryTone.PENDING), m) + } + + @Test + fun sending_row_is_pending() { + val m = deliveryMarker("sending") + assertEquals(DeliveryMarker("\u00bb sending", DeliveryTone.PENDING), m) + } + + @Test + fun failed_row_carries_the_reason() { + val m = deliveryMarker("failed: connection timed out") + assertEquals(DeliveryMarker("\u2717 failed: connection timed out", DeliveryTone.FAILED), m) + } + + @Test + fun failed_row_without_a_reason_still_reads_failed() { + assertEquals( + DeliveryMarker("\u2717 failed", DeliveryTone.FAILED), + deliveryMarker("failed"), + ) + } + + @Test + fun a_long_reason_is_elided() { + val m = deliveryMarker("failed: " + "x".repeat(200)) + val text = m?.text.orEmpty() + assertTrue(text.startsWith("\u2717 failed: xxx")) + assertTrue(text.endsWith("\u2026")) + assertTrue("marker grew to ${text.length} chars", text.length <= 48 + "\u2717 failed: ".length) + } + + @Test + fun incoming_row_has_no_marker() { + assertNull(deliveryMarker(null)) + assertNull(deliveryMarker("")) + assertNull(deliveryMarker(" ")) + } + + @Test + fun unknown_state_never_claims_delivery() { + // Fail-safe: an unreadable state renders nothing rather than a tick. + assertNull(deliveryMarker("scheduled")) + assertNull(deliveryMarker("SENT")) + } + + @Test + fun surrounding_whitespace_is_tolerated() { + assertEquals(DeliveryTone.SENT, deliveryMarker(" sent ")?.tone) + } + + @Test + fun pending_counts_only_queued_and_sending() { + assertTrue(isOutboxPending("queued")) + assertTrue(isOutboxPending("sending")) + assertFalse(isOutboxPending("sent")) + assertFalse(isOutboxPending("failed: no route")) + assertFalse(isOutboxPending(null)) + } +} From 7435ce42f55a736e352e24b8be3a756925fcc0c4 Mon Sep 17 00:00:00 2001 From: sirius Date: Sat, 12 Sep 2026 18:48:57 -0400 Subject: [PATCH 4/8] ci(release): create the release tag with git push so the Android job fires POST /tags sends no push event on this Forgejo (the v0.2.0 tag it created produced no android-release run), so the tag is now created locally and pushed, which does fire android-release.yml's `push: tags` trigger. --- .forgejo/workflows/release.yml | 40 +++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml index 613c54d..c6a7803 100644 --- a/.forgejo/workflows/release.yml +++ b/.forgejo/workflows/release.yml @@ -4,9 +4,10 @@ name: release # PR does not mint a release. A maintainer dispatches this at a stopping point # (a batch of work has landed and CI is green on main) — see docs/RELEASING.md. # Tag-push is intentionally NOT a trigger here: this workflow creates the tag -# via the API, and a tag-push hook would start a second run of the same -# release. Creating the tag *does* fire android-release.yml's `push: tags` -# trigger, which is how the APK + AAR join the same release. +# itself and a tag-push hook would start a second run of the same release. +# The tag is created with a real `git push` (not POST /tags) precisely so that +# android-release.yml's `push: tags` trigger fires and the APK + AAR join the +# same release — an API-created tag sends no push event on this Forgejo. # Version: explicit `version`, else `bump` off the newest v*.*.* tag # (default minor — a batched release is usually a feature set); zero tags → v0.1.0. on: @@ -59,11 +60,15 @@ jobs: dry_run: ${{ steps.plan.outputs.dry_run }} created_tag: ${{ steps.plan.outputs.created_tag }} steps: + - name: Checkout source (needed to create the tag) + uses: https://code.forgejo.org/actions/checkout@v4 + - name: Plan version, create tag unless dry_run id: plan env: FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }} REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }} + GIT_URL: ${{ github.server_url }}/${{ github.repository }}.git EVENT_NAME: ${{ github.event_name }} EVENT_SHA: ${{ github.sha }} INPUT_BUMP: ${{ github.event.inputs.bump }} @@ -151,23 +156,22 @@ jobs: fi echo "tag $tag already exists on $sha — joining" elif [ "$code" = "404" ]; then - python3 -c "import json,sys; json.dump({'tag_name':sys.argv[1],'target':sys.argv[2],'message':'OnionWire '+sys.argv[1]}, sys.stdout)" \ - "$tag" "$sha" > /tmp/tag-create.json - echo "tag-create payload $(wc -c < /tmp/tag-create.json) bytes" - create_code=$(api_curl -o /tmp/tag-created.json -w '%{http_code}' \ - -X POST -H "Content-Type: application/json" \ - --data-binary @/tmp/tag-create.json \ - "$REPO_API/tags") - if [ "$create_code" = "201" ]; then - created=true - echo "created tag $tag on $sha" - elif [ "$create_code" = "409" ]; then - echo "tag $tag created concurrently — joining" - else - echo "creating tag $tag failed HTTP $create_code" >&2 - cat /tmp/tag-created.json >&2 || true + # Create the tag with a real `git push`, not POST /tags. + # A tag pushed by git fires the `push: tags: v*.*.*` trigger + # that android-release.yml listens on; a tag created through + # the API does not (verified on this instance: the v0.2.0 tag + # created by POST /tags produced no android-release run). + git config user.name "onionwire-ci" + git config user.email "onionwire-ci@localhost" + git tag -a "$tag" "$sha" -m "OnionWire $tag" + push_url="https://sirius:${FORGEJO_TOKEN}@${GIT_URL#https://}" + if ! git push "$push_url" "refs/tags/$tag" 2>&1 \ + | sed "s|${FORGEJO_TOKEN}|***|g"; then + echo "creating tag $tag on $sha failed" >&2 exit 1 fi + created=true + echo "created tag $tag on $sha (git push)" else echo "GET tags/$tag failed HTTP $code" >&2 cat /tmp/tag.json >&2 || true From 2cf055c1e8eef3fa34053ee9f824f011a550c24a Mon Sep 17 00:00:00 2001 From: sirius Date: Sat, 12 Sep 2026 18:55:58 -0400 Subject: [PATCH 5/8] ci(release): android-release is dispatch-only; a CI-created tag cannot wake it Neither decoupled trigger fires on Forgejo 10.0.3: a tag created by the CI (API or git push) is an Actions-user push and is not dispatched back into Actions, and reusable workflows need Forgejo >= 12. The release procedure is therefore two dispatches: release.yml, then android-release with that tag. --- .forgejo/workflows/android-release.yml | 20 +++++++----- .forgejo/workflows/release.yml | 41 +++++++++++------------- README.md | 14 +++++--- docs/RELEASING.md | 44 ++++++++++++++++++-------- 4 files changed, 71 insertions(+), 48 deletions(-) diff --git a/.forgejo/workflows/android-release.yml b/.forgejo/workflows/android-release.yml index 0307826..8b93cd0 100644 --- a/.forgejo/workflows/android-release.yml +++ b/.forgejo/workflows/android-release.yml @@ -15,16 +15,20 @@ name: android-release # latest v*.*.* tag UNLESS that tag's release is missing the Android assets — # then join it (core owns tag creation). Never move or delete a tag. # -# No `push: branches: [main]` trigger: a merged android PR does not publish an -# APK. This workflow is woken by the tag release.yml creates for a manual, -# batched release — creating a tag over the API sends the same push -# notification a `git push` does, so the tag ref matches this filter. -# See docs/RELEASING.md. +# No automatic trigger, on purpose. Two candidate decoupled triggers were +# tried and both dead-end on Forgejo 10.0.3 (see docs/RELEASING.md): +# - `push: tags: ['v*.*.*']` — a tag created by release.yml (API or git push) +# does not fire it: pushes made with the CI's token are Actions-user events +# and Forgejo deliberately does not dispatch those back into Actions. +# Verified: the v0.2.0 and v0.2.1 tags produced no run, while hand-pushed +# tags did historically. +# - `workflow_call` from release.yml — reusable workflows only exist from +# Forgejo 12; this instance is 10.0.3. +# So a release is two dispatches: release.yml, then this one with `tag=`. The core's run leaves the tag; this attaches +# the APK + AAR to it. on: - push: - tags: - - "v*.*.*" workflow_dispatch: inputs: tag: diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml index c6a7803..c4b13d0 100644 --- a/.forgejo/workflows/release.yml +++ b/.forgejo/workflows/release.yml @@ -4,10 +4,10 @@ name: release # PR does not mint a release. A maintainer dispatches this at a stopping point # (a batch of work has landed and CI is green on main) — see docs/RELEASING.md. # Tag-push is intentionally NOT a trigger here: this workflow creates the tag -# itself and a tag-push hook would start a second run of the same release. -# The tag is created with a real `git push` (not POST /tags) precisely so that -# android-release.yml's `push: tags` trigger fires and the APK + AAR join the -# same release — an API-created tag sends no push event on this Forgejo. +# via the API, and a tag-push hook would start a second run of the same release. +# (A tag this workflow creates does not wake android-release.yml either — see +# docs/RELEASING.md: on this Forgejo, pushes made with the CI token are +# Actions-user events and are not dispatched back into Actions.) # Version: explicit `version`, else `bump` off the newest v*.*.* tag # (default minor — a batched release is usually a feature set); zero tags → v0.1.0. on: @@ -60,15 +60,11 @@ jobs: dry_run: ${{ steps.plan.outputs.dry_run }} created_tag: ${{ steps.plan.outputs.created_tag }} steps: - - name: Checkout source (needed to create the tag) - uses: https://code.forgejo.org/actions/checkout@v4 - - name: Plan version, create tag unless dry_run id: plan env: FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }} REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }} - GIT_URL: ${{ github.server_url }}/${{ github.repository }}.git EVENT_NAME: ${{ github.event_name }} EVENT_SHA: ${{ github.sha }} INPUT_BUMP: ${{ github.event.inputs.bump }} @@ -156,22 +152,23 @@ jobs: fi echo "tag $tag already exists on $sha — joining" elif [ "$code" = "404" ]; then - # Create the tag with a real `git push`, not POST /tags. - # A tag pushed by git fires the `push: tags: v*.*.*` trigger - # that android-release.yml listens on; a tag created through - # the API does not (verified on this instance: the v0.2.0 tag - # created by POST /tags produced no android-release run). - git config user.name "onionwire-ci" - git config user.email "onionwire-ci@localhost" - git tag -a "$tag" "$sha" -m "OnionWire $tag" - push_url="https://sirius:${FORGEJO_TOKEN}@${GIT_URL#https://}" - if ! git push "$push_url" "refs/tags/$tag" 2>&1 \ - | sed "s|${FORGEJO_TOKEN}|***|g"; then - echo "creating tag $tag on $sha failed" >&2 + python3 -c "import json,sys; json.dump({'tag_name':sys.argv[1],'target':sys.argv[2],'message':'OnionWire '+sys.argv[1]}, sys.stdout)" \ + "$tag" "$sha" > /tmp/tag-create.json + echo "tag-create payload $(wc -c < /tmp/tag-create.json) bytes" + create_code=$(api_curl -o /tmp/tag-created.json -w '%{http_code}' \ + -X POST -H "Content-Type: application/json" \ + --data-binary @/tmp/tag-create.json \ + "$REPO_API/tags") + if [ "$create_code" = "201" ]; then + created=true + echo "created tag $tag on $sha" + elif [ "$create_code" = "409" ]; then + echo "tag $tag created concurrently — joining" + else + echo "creating tag $tag failed HTTP $create_code" >&2 + cat /tmp/tag-created.json >&2 || true exit 1 fi - created=true - echo "created tag $tag on $sha (git push)" else echo "GET tags/$tag failed HTTP $code" >&2 cat /tmp/tag.json >&2 || true diff --git a/README.md b/README.md index 9e33521..c873d2e 100644 --- a/README.md +++ b/README.md @@ -269,7 +269,10 @@ rationale, the 16 KB page-size check and the signing story are in Releases are **manual and batched**: no merge publishes anything, and neither does a tag push. Cut one when a batch of work has reached a stopping point — CI green on `main`, the feature set landed, no half-merged stack. Full policy -and procedure: [`docs/RELEASING.md`](docs/RELEASING.md). +and procedure: [`docs/RELEASING.md`](docs/RELEASING.md) — it is two dispatches, +`release` (tag + Linux binaries) then `android-release` with that tag (APK + +AAR): on this Forgejo neither a tag push nor `workflow_call` can wake the +Android job. Actions → release → Run workflow: @@ -284,9 +287,10 @@ Pass `tag` **or** `version`, not both; an unparseable version is rejected rather than guessed at. The workflow computes the version, creates the tag over the API (refusing to move an existing tag), builds aarch64 on the Pi runner and x86_64 on the amd64 runner, and publishes all four assets (`onionwire-` -+ `.sha256`) to one release. Creating that tag fires `android-release.yml`, -which builds the APK + AAR and joins the same release. If a build or the -publish fails, the run deletes the tag it created. Do not push tags by hand — ++ `.sha256`) to one release. Then dispatch `android-release` with that tag to +attach the APK + AAR to the same release (it has no automatic trigger on this +Forgejo — see `docs/RELEASING.md`). If a build or the publish fails, the core +run deletes the tag it created. Do not push tags by hand — `release.yml` has no tag-push trigger, so a hand-pushed tag would build nothing. @@ -301,7 +305,7 @@ FORGEJO_TOKEN= scripts/build-release-local.sh vX.Y.Z Workflows (Forgejo Actions, `.forgejo/workflows/`): - [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite. Pi runner, `docker` label. -- [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — manual, batched release (`workflow_dispatch` only: `dry_run`, `bump`, `version`, `tag`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release, fail-closed tag delete on failure. The tag it creates fires [`android-release.yml`](.forgejo/workflows/android-release.yml) (`push: tags: v*.*.*`), which joins the same release with the APK + AAR. Concurrency group `onionwire-ci-pi` (same as `ci.yml`, `cancel-in-progress: false`) so cargo jobs do not overlap on the Pi. Amd64 dind is serialized by runner `capacity=1`. +- [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — manual, batched release (`workflow_dispatch` only: `dry_run`, `bump`, `version`, `tag`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release, fail-closed tag delete on failure. Dispatch [`android-release.yml`](.forgejo/workflows/android-release.yml) with that tag to add the APK + AAR (no automatic trigger fires on this Forgejo; it is `workflow_dispatch` only). Concurrency group `onionwire-ci-pi` (same as `ci.yml`, `cancel-in-progress: false`) so cargo jobs do not overlap on the Pi. Amd64 dind is serialized by runner `capacity=1`. Scripts: diff --git a/docs/RELEASING.md b/docs/RELEASING.md index f605b04..a4ccc3b 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -37,7 +37,10 @@ created if the build or publish fails", and the dry-run path. 4. **Watch it.** The run name is `release`; `scripts/watch-release-run.sh` reports job status (it reads `action_run`/`action_run_job` on the Pi's database, so it works for dispatched runs as well as any other). -5. **Check the assets.** Open the release page (or +5. **Attach the Android assets.** Dispatch `android-release` with the tag the + core run just created — see [Android](#android-apk--aar-on-the-same-tag). + The Linux binaries land first; the APK build is the long pole. +6. **Check the assets.** Open the release page (or `GET /api/v1/repos/sirius/onionwire/releases/tags/`) and require a non-zero `size` for every asset: the two Linux binaries + `.sha256`, the APK + `.sha256`, the AAR + `.sha256`. A green run is not proof — the Pi @@ -81,20 +84,35 @@ final step deletes the incomplete release and the tag. A failed `aarch64` or ## Android (APK + AAR) on the same tag -Creating the tag sends the same push notification a `git push` would, and -[`android-release.yml`](../.forgejo/workflows/android-release.yml) is -subscribed to `push: tags: v*.*.*`. The core workflow therefore does not call -it, and no `main`-push trigger exists on either file. +A release is **two dispatches**. After the core run has created the tag and +published the Linux binaries: -That run builds the signed APK and the SDK AAR on the **amd64** runner (the Pi -is aarch64 and cannot produce an APK), then a second job on the Pi attaches the -APK + AAR + `.sha256` to the same tag. If the release does not exist yet it is -created; if it exists it is joined (`publish-release.sh` is create-or-update). -Android assets land on the release a while after the Linux ones — the Android -build is the long pole. +1. Actions → **android-release** → *Run workflow*, `tag=vX.Y.Z` (the tag the + core just created; leave `dry_run` false). +2. Check the release again — the APK + AAR + `.sha256` are attached to the + **same** tag. If the release did not exist yet it is created; if it exists + it is joined (`publish-release.sh` is create-or-update). -The workflow also has `workflow_dispatch` with the same `tag` / `dry_run` -inputs, which is how you repair or re-attach the Android assets by hand. +`android-release.yml` has no automatic trigger, and that is deliberate. Both +candidate decoupled triggers were tried on this instance and neither fires: + +- **A tag created by `release.yml` does not wake `push: tags: ['v*.*.*']`.** + Tried both ways — the tag created through `POST /tags`, and the tag created + by a real `git push` from the version job. Neither produced an + `android-release` run: pushes made with the CI's token are Actions-user + events, and Forgejo deliberately does not dispatch those back into Actions + (`services/actions/notifier_helper.go`: a doer that `IsActions()` is ignored). + Historically, *hand-pushed* tags did fire tag-filtered workflows, which is why + the trigger looked plausible. +- **`workflow_call` is unavailable.** Reusable workflows only appear in the + Forgejo docs from v12 onward; this instance reports + `10.0.3+gitea-1.22.0` (`GET /api/v1/version`), so a caller job with + `uses: ./.forgejo/workflows/android-release.yml` would never run. The + `workflow_call` block is left declared for the day the instance is upgraded. + +The Android build runs on the **amd64** runner (the Pi is aarch64 and cannot +produce an APK), then a second job on the Pi attaches the assets. It is the +long pole of a release — the Linux binaries land first. ## Rebuilding an existing tag From e30c9f169988e02ac6499cdeb786ea42ccbc8ef4 Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 12 Sep 2026 18:16:21 -0400 Subject: [PATCH 6/8] fix(sdk): surface Sent/Queued on send(), and build the SDK in CI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Node::send() became Result in the local-outbox work, which broke crates/onionwire-sdk — and nothing noticed, because the SDK is a separate cargo workspace that root CI never compiles. - Wire::send() returns WResult (Sent | Queued) - ChatMessage.delivery for outgoing rows - New sdk job in ci.yml (own target volume; rustls workspace) - Refresh SDK Cargo.lock + README (SQLCipher / outbox facts) Rebased onto main after #50/#54: no src/node.rs changes (WAL checkpoint lives in Store now). README at-rest claims kept from #55. --- .forgejo/workflows/ci.yml | 46 +++++++++++ README.md | 4 +- crates/onionwire-sdk/Cargo.lock | 25 ++++++ crates/onionwire-sdk/README.md | 20 +++-- crates/onionwire-sdk/src/lib.rs | 141 +++++++++++++++++++++++++++----- 5 files changed, 208 insertions(+), 28 deletions(-) diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml index 4c7b8aa..d922dfe 100644 --- a/.forgejo/workflows/ci.yml +++ b/.forgejo/workflows/ci.yml @@ -39,6 +39,11 @@ env: CARGO_REGISTRY_VOLUME: onionwire-cargo-registry CARGO_TARGET_VOLUME: onionwire-target-ci BUILD_CONTAINER: onionwire-ci-${{ github.run_id }} + # The SDK job gets its own target volume: it resolves the root crate with + # `rustls` instead of `native-tls`, so sharing a target dir would thrash both + # jobs' feature-unified artifacts. + SDK_CARGO_TARGET_VOLUME: onionwire-target-ci-sdk + SDK_BUILD_CONTAINER: onionwire-ci-sdk-${{ github.run_id }} jobs: test: @@ -73,3 +78,44 @@ jobs: tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees . \ | docker start -a -i "$BUILD_CONTAINER" docker rm -f "$BUILD_CONTAINER" > /dev/null + + # `crates/onionwire-sdk` is a SEPARATE cargo workspace: its own Cargo.lock and + # a path dependency on the root crate, resolved with `rustls` instead of + # `native-tls`. The `test` job above therefore never compiles it, so a + # root-crate signature change (`Node::send` gaining the outbox result, the + # SQLCipher passphrase entry points) breaks the Android SDK — and the tagged + # release AAR, since android-release.yml only builds on `v*.*.*` — while both + # the root suites and local `cargo test` stay green. Build it here. + sdk: + runs-on: docker + timeout-minutes: 120 + steps: + - name: Checkout + uses: https://code.forgejo.org/actions/checkout@v4 + + - name: cargo test + clippy for crates/onionwire-sdk on aarch64 + run: | + set -euo pipefail + cd "${GITHUB_WORKSPACE}" + echo "workspace: $GITHUB_WORKSPACE" + docker volume create "$CARGO_REGISTRY_VOLUME" > /dev/null + docker volume create "$SDK_CARGO_TARGET_VOLUME" > /dev/null + docker rm -f "$SDK_BUILD_CONTAINER" > /dev/null 2>&1 || true + docker create --name "$SDK_BUILD_CONTAINER" -i \ + -e CARGO_TARGET_DIR=/target \ + -e CARGO_BUILD_JOBS=2 \ + -e CARGO_TERM_COLOR=never \ + -v "$CARGO_REGISTRY_VOLUME":/usr/local/cargo/registry \ + -v "$SDK_CARGO_TARGET_VOLUME":/target \ + -w /src \ + "$RUST_IMAGE" \ + sh -euxc 'mkdir -p /src && tar xzf - -C /src && cd /src/crates/onionwire-sdk \ + && apt-get update \ + && apt-get install -y --no-install-recommends pkg-config libssl-dev \ + && rustup component add clippy \ + && cargo test --locked \ + && cargo clippy --locked --all-targets -- -D warnings' + tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees \ + --exclude=./crates/onionwire-sdk/target . \ + | docker start -a -i "$SDK_BUILD_CONTAINER" + docker rm -f "$SDK_BUILD_CONTAINER" > /dev/null diff --git a/README.md b/README.md index c873d2e..83fe649 100644 --- a/README.md +++ b/README.md @@ -304,8 +304,8 @@ FORGEJO_TOKEN= scripts/build-release-local.sh vX.Y.Z Workflows (Forgejo Actions, `.forgejo/workflows/`): -- [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite. Pi runner, `docker` label. -- [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — manual, batched release (`workflow_dispatch` only: `dry_run`, `bump`, `version`, `tag`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release, fail-closed tag delete on failure. Dispatch [`android-release.yml`](.forgejo/workflows/android-release.yml) with that tag to add the APK + AAR (no automatic trigger fires on this Forgejo; it is `workflow_dispatch` only). Concurrency group `onionwire-ci-pi` (same as `ci.yml`, `cancel-in-progress: false`) so cargo jobs do not overlap on the Pi. Amd64 dind is serialized by runner `capacity=1`. +- [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — two jobs on the Pi runner (`docker` label), serialized by `onionwire-ci-pi`. `test`: `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` at the repo root. `sdk`: the same for `crates/onionwire-sdk` (separate cargo workspace — own `Cargo.lock`, root crate by path, `rustls` instead of `native-tls` — so a root signature change cannot silently break the Android SDK). Both run on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite. +- [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — on core paths to `main` (`src/`, `crates/`, `Cargo.toml`, `Cargo.lock`, `scripts/release-body.md`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release. `workflow_dispatch` rebuilds a tag or `dry_run`s. Concurrency group `onionwire-ci-pi` (same as `ci.yml`, `cancel-in-progress: false`) so cargo jobs do not overlap on the Pi. Amd64 dind is serialized by runner `capacity=1`. Scripts: diff --git a/crates/onionwire-sdk/Cargo.lock b/crates/onionwire-sdk/Cargo.lock index 0422aac..62079af 100644 --- a/crates/onionwire-sdk/Cargo.lock +++ b/crates/onionwire-sdk/Cargo.lock @@ -2443,6 +2443,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91632f3b4fb6bd1d72aa3d78f41ffecfcf2b1a6648d8c241dbe7dbfaf4875e15" dependencies = [ "cc", + "openssl-sys", "pkg-config", "vcpkg", ] @@ -2774,6 +2775,7 @@ dependencies = [ "rusqlite", "safelog", "serde_json", + "sha2", "sha3 0.10.9", "snow", "tokio", @@ -2781,6 +2783,7 @@ dependencies = [ "tor-hsservice", "tor-rtcompat", "x25519-dalek", + "zeroize", ] [[package]] @@ -2801,6 +2804,28 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" +[[package]] +name = "openssl-src" +version = "300.6.1+3.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846" +dependencies = [ + "cc", +] + +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +dependencies = [ + "cc", + "libc", + "openssl-src", + "pkg-config", + "vcpkg", +] + [[package]] name = "option-ext" version = "0.2.0" diff --git a/crates/onionwire-sdk/README.md b/crates/onionwire-sdk/README.md index 36e25a5..9072542 100644 --- a/crates/onionwire-sdk/README.md +++ b/crates/onionwire-sdk/README.md @@ -18,8 +18,8 @@ onions directly. There is no `tor` binary, no torrc, no Orbot as the pipe. | Onion | A **locator**, not an identity. It rotates. | | Invite | `onionwire:v1:k=…:o=…:spk=…:sig=…` | | Crypto | Noise IK (`Noise_IK_25519_ChaChaPoly_BLAKE2s`). `spk` is x25519. | -| Fail closed | Peer onion down → the send fails. No outbox, no spool in v1. | -| At rest | Chat bodies encrypted (Argon2id wrap + ChaCha20-Poly1305). Identity keys in sqlite are plaintext — that is honest, not an oversight. | +| Chat send | Unreachable peer onion → the message goes to the **local outbox** and is retried with backoff. `send()` returns `SendState.Sent` or `SendState.Queued`. File transfer and payments stay fail-closed. | +| At rest | The whole sqlite file is SQLCipher (key = Argon2id of the store passphrase), and chat bodies carry a second per-row ChaCha20-Poly1305 layer with row-bound AAD. Identity keys live in that same encrypted file. | ### Invite string @@ -66,8 +66,10 @@ Requirements: ## Kotlin surface -Everything is a `suspend fun` — Arti bootstrap and onion publish take minutes, -and a send retries the peer for up to 3 minutes before failing. +Everything is a `suspend fun` — Arti bootstrap and onion publish take minutes. +A send that cannot reach the peer comes back immediately as `QUEUED` (it is not +a long retry inside the call): the message is stored locally and a background +worker in the core keeps retrying it. ```kotlin import uniffi.onionwire_sdk.* @@ -88,8 +90,16 @@ val friend: FriendInfo = wire.addFriend(pasted) // 4. Roster and chat. val roster: List = wire.friends() wire.setPetname(friend.pubkeyHex, "ada") -wire.send(friend.pubkeyHex, "hello wire") +when (wire.send(friend.pubkeyHex, "hello wire")) { + SendState.SENT -> { /* the peer's onion took the frame */ } + SendState.QUEUED -> { /* unreachable: stored in the local outbox and + retried in the background. Show it as pending — + it is local-only until a circuit takes it. */ } +} val msgs: List = wire.messages(friend.pubkeyHex) +// msgs[i].direction == "out" -> msgs[i].delivery is "sent" | "queued" | +// "sending" | "failed: "; null for incoming messages. Render the +// queued and failed states distinctly from sent. // 5. Locator rotation. Do NOT wire this to a single tap — the app that embeds // the SDK owns the typed confirmation. diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index 90e5b55..5657948 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -11,7 +11,10 @@ //! the friend. //! * Transport is in-process Arti. There is no `tor` binary, no torrc, no //! Orbot pipe. If the onion service cannot publish, this fails closed. -//! * Chat bodies are encrypted at rest. Identity keys in sqlite are not. +//! * Chat bodies are encrypted at rest, and the whole sqlite file is +//! SQLCipher on top of that (see the root crate). +//! * A chat send that cannot reach the peer's onion is queued in a local +//! outbox and retried — see [`SendState`]. Nothing leaves the device. //! //! Lifecycle: a node is started by [`open_wire`] and stopped by //! [`Wire::shutdown`]. Between those, [`Wire::tor_state`] is the observable @@ -27,7 +30,7 @@ use std::sync::{Arc, Mutex, OnceLock}; use onionwire::hs::TorState as CoreTorState; use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node}; -use onionwire::qr; +use onionwire::outbox::OutboxStatus;use onionwire::qr; uniffi::setup_scaffolding!(); @@ -98,11 +101,34 @@ pub struct FriendInfo { pub last_connect_ok: bool, } +/// What `send()` did with the message. +/// +/// The core has a local outbox: when a friend's onion is unreachable the +/// message is written to the local sqlite store and a background worker +/// retries it with backoff. Nothing is handed to a third party — every attempt +/// is a fresh handshake straight to that friend's onion — but until a circuit +/// takes it the message exists only on this device. A consumer must not render +/// `Queued` as delivered. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum SendState { + /// The frame reached the peer's onion service during this call. + Sent, + /// The peer's onion was unreachable: the message is in the local outbox, + /// local-only until the retry worker delivers it (or it ends `Failed`). + Queued, +} + #[derive(Debug, Clone, uniffi::Record)] pub struct ChatMessage { /// "in" or "out". pub direction: String, pub body: String, + /// Outgoing messages only: `"sent"`, `"queued"`, `"sending"` or + /// `"failed: "`. `None` for incoming messages. An outgoing row with + /// no outbox row is one the peer accepted on the first attempt, so it reads + /// `"sent"` — never treat a missing value as "delivered" on the app side, + /// read this field. + pub delivery: Option, } #[derive(Debug, Clone, uniffi::Record)] @@ -332,34 +358,44 @@ impl Wire { .map_err(WireError::new) } - /// Send one message. Returns once the outcome is known: delivered now, or - /// queued for retry because the peer's onion is unreachable. A protocol - /// error (bad signature, bad frame) still fails immediately and is never - /// queued. Use [`flush`](Self::flush) to retry the queue on demand. - pub async fn send(&self, pubkey_hex: String, body: String) -> WResult<()> { + /// Send one chat message. + /// + /// Returns [`SendState::Sent`] when the frame reached the peer's onion + /// service during this call, and [`SendState::Queued`] when it did not: the + /// message is then in the local outbox and a background worker retries it + /// with exponential backoff (30s doubling, capped at 30 min, 8 attempts) + /// until it lands or ends terminally failed. A queued send is local-only — + /// show it as pending, not delivered. + /// + /// A protocol error (signature mismatch, malformed or oversize frame) is + /// not retryable and still fails here; nothing is queued in that case. + pub async fn send(&self, pubkey_hex: String, body: String) -> WResult { let pk = unhex(&pubkey_hex)?; - self.node()? + let status = self + .node()? .send(&pk, body.as_bytes()) .await .map_err(WireError::new)?; - Ok(()) - } + Ok(send_state(status)) } /// Chat history for a friend, oldest first. Bodies are decrypted here; - /// they are stored encrypted at rest. + /// they are stored encrypted at rest. Outgoing rows carry their delivery + /// state in [`ChatMessage::delivery`]. pub async fn messages(&self, pubkey_hex: String) -> WResult> { let pk = unhex(&pubkey_hex)?; - let rows = self - .node()? - .list_messages(&pk) - .map_err(WireError::new)?; - Ok(rows - .into_iter() - .map(|m| ChatMessage { + let rows = self.node()?.list_messages(&pk).map_err(WireError::new)?; + let mut out = Vec::with_capacity(rows.len()); + for m in rows { + let status = self + .node()? + .outbox_status_of_message(m.id) + .map_err(WireError::new)?; + out.push(ChatMessage { body: String::from_utf8_lossy(&m.plaintext).into_owned(), + delivery: delivery_of(&m.dir, status), direction: m.dir, - body: String::from_utf8_lossy(&m.plaintext).into_owned(), - }) - .collect()) + }); + } + Ok(out) } /// Delete every message body. Identity and friends survive. @@ -415,6 +451,30 @@ fn unhex(s: &str) -> WResult> { .collect() } +/// `Node::send` only ever yields `Sent` or `Queued`; `Sending`/`Failed` exist +/// only on stored outbox rows. Everything that is not a completed send maps to +/// `Queued`, so a status this build does not know about is never reported as +/// delivered — the fail-safe direction for a caller that hides its retry UI. +fn send_state(status: OutboxStatus) -> SendState { + match status { + OutboxStatus::Sent => SendState::Sent, + _ => SendState::Queued, + } +} + +/// Delivery string for one stored chat row. `None` for incoming rows. An +/// outgoing row with no outbox row was accepted on the first attempt, so it is +/// reported as `"sent"` rather than left blank. +fn delivery_of(dir: &str, status: Option) -> Option { + if dir != "out" { + return None; + } + Some(match status { + None | Some(OutboxStatus::Sent) => "sent".to_string(), + Some(other) => other.to_string(), + }) +} + #[cfg(test)] mod tests { //! No Tor here on purpose: these exercise the *lifecycle* contract of the @@ -422,6 +482,7 @@ mod tests { //! node is exactly the state `shutdown()` leaves behind. use super::*; + use onionwire::outbox::OutboxStatus; fn stopped_wire() -> Wire { Wire { @@ -482,4 +543,42 @@ mod tests { ); assert_eq!(TorState::from(CoreTorState::Stopped), TorState::Stopped); } + +#[test] + fn sent_is_sent_everything_else_is_queued() { + assert_eq!(send_state(OutboxStatus::Sent), SendState::Sent); + assert_eq!(send_state(OutboxStatus::Queued), SendState::Queued); + // `Node::send` never returns these today, but they exist on stored + // rows. Unknown states map to `Queued` — the safe direction: never + // report a send as delivered unless the core says `Sent`. + assert_eq!(send_state(OutboxStatus::Sending), SendState::Queued); + assert_eq!( + send_state(OutboxStatus::Failed("no route".into())), + SendState::Queued + ); + } + + #[test] + fn delivery_is_reported_for_outgoing_rows_only() { + assert_eq!(delivery_of("in", Some(OutboxStatus::Queued)), None); + // Outgoing row with no outbox row: delivered on the first attempt. + assert_eq!(delivery_of("out", None).as_deref(), Some("sent")); + assert_eq!( + delivery_of("out", Some(OutboxStatus::Sent)).as_deref(), + Some("sent") + ); + assert_eq!( + delivery_of("out", Some(OutboxStatus::Queued)).as_deref(), + Some("queued") + ); + assert_eq!( + delivery_of("out", Some(OutboxStatus::Sending)).as_deref(), + Some("sending") + ); + assert_eq!( + delivery_of("out", Some(OutboxStatus::Failed("no route".into()))).as_deref(), + Some("failed: no route") + ); + } } + From 2e738e2e99107c67573779be578fee9d4f45a23b Mon Sep 17 00:00:00 2001 From: Hermes apk-dev Date: Sat, 12 Sep 2026 15:47:14 -0400 Subject: [PATCH 7/8] fix(android): surface the outbox send state instead of denying it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The SDK has returned `SendState` and a per-row `ChatMessage.delivery` since the local outbox landed, but the app still said "there is no outbox in v1" and threw the state away. - `WireViewModel.send()` returns `SendState`; `ChatScreen` no longer discards it. A `QUEUED` send raises a "local-only until the retry worker gets a circuit through" hint instead of pretending success. - Outgoing rows render the TUI's delivery markers from `ChatMessage.delivery` (`✓` / `◷ queued` / `» sending` / `✗ failed: `), plus the TUI's `{n} queued` footer while the outbox still owns rows. Incoming rows stay unmarked; an unreadable state renders no marker rather than a tick. - The empty-chat copy describes the outbox (8 attempts, backoff capped at 30 min, local-only until it lands) instead of denying it exists. - New pure `Delivery.kt` so the vocabulary is unit-testable without a device. Verified: `./gradlew :app:assembleDebug :app:testDebugUnitTest` → BUILD SUCCESSFUL, 15 tests / 0 failures (10 new), APK contains the new copy and no longer the "There is no outbox" string. Stacked on the SDK fix (PR #51). --- .../siriusdevops/onionwire/WireViewModel.kt | 11 +- .../siriusdevops/onionwire/ui/ChatScreen.kt | 116 +++++++++++++++--- .../com/siriusdevops/onionwire/ui/Delivery.kt | 78 ++++++++++++ .../onionwire/ui/DeliveryMarkerTest.kt | 85 +++++++++++++ 4 files changed, 271 insertions(+), 19 deletions(-) create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/Delivery.kt create mode 100644 android/app/src/test/java/com/siriusdevops/onionwire/ui/DeliveryMarkerTest.kt diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index 579de57..6b72d75 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -21,6 +21,7 @@ import uniffi.onionwire_sdk.ChatMessage import uniffi.onionwire_sdk.FriendInfo import uniffi.onionwire_sdk.InviteInfo import uniffi.onionwire_sdk.RotateOutcome +import uniffi.onionwire_sdk.SendState import uniffi.onionwire_sdk.Wire import uniffi.onionwire_sdk.decodeInvite import java.io.File @@ -361,7 +362,15 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { suspend fun messages(pubkeyHex: String): List = requireWire().messages(pubkeyHex) - suspend fun send(pubkeyHex: String, body: String) = + /** + * Hands the body to the node and reports what happened to it. + * + * `SENT` means the peer's onion took the frame during this call. `QUEUED` + * means it did not: the message is in the local outbox, local-only until + * the retry worker gets a circuit through. The caller must not render + * `QUEUED` as delivered. + */ + suspend fun send(pubkeyHex: String, body: String): SendState = requireWire().send(pubkeyHex, body) suspend fun wipeMessages() { diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt index fbfa709..9bffca7 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt @@ -37,6 +37,12 @@ import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.dp import kotlinx.coroutines.delay import uniffi.onionwire_sdk.ChatMessage +import uniffi.onionwire_sdk.SendState + +/** Shown after a `Queued` send — the TUI's composer keeps `{n} queued`. */ +private const val QUEUED_HINT = + "Queued: their onion is unreachable. The message is local-only in this " + + "device's outbox until the retry worker gets a circuit through." @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -45,13 +51,14 @@ fun ChatScreen( fingerprint: String, onion: String, loadMessages: suspend () -> List, - onSend: suspend (String) -> Unit, + onSend: suspend (String) -> SendState, onBack: () -> Unit, ) { var messages by remember { mutableStateOf?>(null) } var draft by remember { mutableStateOf("") } var pending by remember { mutableStateOf(null) } var error by remember { mutableStateOf(null) } + var hint by remember { mutableStateOf(null) } val listState = rememberLazyListState() // Poll: the node appends inbound messages in the background; there is no @@ -65,16 +72,32 @@ fun ChatScreen( } } - // Fail-closed send. `send` retries the peer's onion for up to 3 minutes and - // then errors — nothing is spooled, so a failure is a real failure. + // Fail closed — but not fail lost. `send` returns `Queued` when the peer's + // onion is unreachable: the body is in this device's local outbox and the + // retry worker keeps trying. It only surfaces as a hard error when the + // node itself refuses the write. LaunchedEffect(pending) { val body = pending ?: return@LaunchedEffect error = null + hint = null runCatching { onSend(body) } + .onSuccess { state -> + // Never dress a queued send up as delivered. + hint = if (state == SendState.QUEUED) QUEUED_HINT else null + } .onFailure { error = it.message ?: it.toString() } pending = null } + // The hint is a toast, not a log line: the row marker and the `N queued` + // footer are what stay on screen. + LaunchedEffect(hint) { + if (hint != null) { + delay(6_000) + hint = null + } + } + LaunchedEffect(messages?.size) { val n = messages?.size ?: 0 if (n > 0) listState.animateScrollToItem(n - 1) @@ -127,8 +150,13 @@ fun ChatScreen( Text("No messages", style = MaterialTheme.typography.titleSmall) Spacer(Modifier.height(6.dp)) Text( - "Sends fail closed: if their onion is down the message is " + - "not spooled anywhere. There is no outbox in v1.", + "Sends fail closed — nothing goes to a third party. If their " + + "onion is unreachable the message is queued in this " + + "device's outbox instead of being dropped: it stays " + + "local-only until the retry worker gets a circuit " + + "through (8 attempts, backoff capped at 30 min), then it " + + "lands. \u2713 means delivered, \u25f7 queued, " + + "\u2717 failed.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -149,25 +177,77 @@ fun ChatScreen( horizontalArrangement = if (mine) Arrangement.End else Arrangement.Start, ) { - Text( - m.body, - style = MaterialTheme.typography.bodyMedium, - color = if (mine) MaterialTheme.colorScheme.onPrimary - else MaterialTheme.colorScheme.onSurface, - modifier = Modifier - .background( - if (mine) MaterialTheme.colorScheme.primary - else MaterialTheme.colorScheme.surfaceVariant, - RoundedCornerShape(10.dp), - ) - .padding(horizontal = 10.dp, vertical = 8.dp), - ) + Column( + horizontalAlignment = + if (mine) Alignment.End else Alignment.Start, + ) { + Text( + m.body, + style = MaterialTheme.typography.bodyMedium, + color = if (mine) MaterialTheme.colorScheme.onPrimary + else MaterialTheme.colorScheme.onSurface, + modifier = Modifier + .background( + if (mine) MaterialTheme.colorScheme.primary + else MaterialTheme.colorScheme.surfaceVariant, + RoundedCornerShape(10.dp), + ) + .padding(horizontal = 10.dp, vertical = 8.dp), + ) + // Outgoing rows only: the SDK reports `null` for + // inbound, and an outgoing row with no outbox + // entry reads "sent". + if (mine) { + deliveryMarker(m.delivery)?.let { marker -> + Text( + marker.text, + style = MaterialTheme.typography.labelSmall, + fontFamily = FontFamily.Monospace, + color = when (marker.tone) { + DeliveryTone.SENT -> + MaterialTheme.colorScheme.onSurfaceVariant + + DeliveryTone.PENDING -> + MaterialTheme.colorScheme.tertiary + + DeliveryTone.FAILED -> + MaterialTheme.colorScheme.error + }, + modifier = Modifier.padding( + top = 2.dp, + end = 2.dp, + ), + ) + } + } + } } } } } } + // TUI footer: `{n} queued` while the outbox still owns rows. + val queued = list?.count { it.direction == "out" && isOutboxPending(it.delivery) } ?: 0 + if (queued > 0) { + Text( + "$queued queued", + style = MaterialTheme.typography.labelSmall, + fontFamily = FontFamily.Monospace, + color = MaterialTheme.colorScheme.tertiary, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) + } + + hint?.let { + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.tertiary, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) + } + error?.let { Text( it, diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/Delivery.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/Delivery.kt new file mode 100644 index 0000000..a26766d --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/Delivery.kt @@ -0,0 +1,78 @@ +package com.siriusdevops.onionwire.ui + +/** + * Per-row delivery markers for outgoing chat messages. + * + * The vocabulary is the TUI's (`docs/TUI.md` → "Delivery state (outbox)"), so + * both clients read the same: + * + * ``` + * ✓ delivered — the peer's onion took the frame + * ◷ queued in this device's local outbox, waiting for a circuit + * » sending the retry worker has it in flight + * ✗ failed: … terminally failed (8 attempts, backoff capped at 30 min) + * ``` + * + * The string comes from `ChatMessage.delivery` and is produced by the store's + * own outbox status — `"sent"` / `"queued"` / `"sending"` / + * `"failed: "` for outgoing rows, `null` for incoming ones. An outgoing + * row with no outbox row was accepted on the first attempt and reads `"sent"`. + * + * Nothing here guesses: a delivery string this build does not recognise renders + * no marker rather than a tick, because a missing marker never claims delivery + * while a wrong tick does. + */ + +/** Which colour the marker is drawn in. */ +internal enum class DeliveryTone { + /** Delivered to the peer's onion. */ + SENT, + + /** Still local-only: queued, or being retried right now. */ + PENDING, + + /** Out of attempts — the message never left this device. */ + FAILED, +} + +internal data class DeliveryMarker(val text: String, val tone: DeliveryTone) + +/** + * Longest `failed: ` tail we render before eliding. The TUI caps the + * same reason at 24 cells for its 80-column row; a phone bubble wraps, so this + * only exists to stop a pathological Tor error from filling the screen. + */ +private const val MAX_REASON_CHARS = 48 + +/** Marker for one outgoing row, or `null` when there is nothing to say. */ +internal fun deliveryMarker(delivery: String?): DeliveryMarker? { + val state = delivery?.trim().orEmpty() + if (state.isEmpty()) return null + return when { + state == "sent" -> DeliveryMarker("\u2713", DeliveryTone.SENT) + state == "queued" -> DeliveryMarker("\u25f7 queued", DeliveryTone.PENDING) + state == "sending" -> DeliveryMarker("\u00bb sending", DeliveryTone.PENDING) + state.startsWith("failed") -> { + val reason = shortReason(state.substringAfter(':', "").trim()) + DeliveryMarker( + if (reason.isEmpty()) "\u2717 failed" else "\u2717 failed: $reason", + DeliveryTone.FAILED, + ) + } + // Unknown state: never render a tick for something we cannot read. + else -> null + } +} + +/** True while the outbox still owns the row — the TUI's `{n} queued` footer. */ +internal fun isOutboxPending(delivery: String?): Boolean { + val state = delivery?.trim().orEmpty() + return state == "queued" || state == "sending" +} + +private fun shortReason(reason: String): String = + if (reason.length <= MAX_REASON_CHARS) { + reason + } else { + reason.take(MAX_REASON_CHARS - 1).trimEnd() + "\u2026" + } diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/DeliveryMarkerTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/DeliveryMarkerTest.kt new file mode 100644 index 0000000..6340190 --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/DeliveryMarkerTest.kt @@ -0,0 +1,85 @@ +package com.siriusdevops.onionwire.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The delivery vocabulary is shared with the TUI (`docs/TUI.md` → "Delivery + * state (outbox)"). These strings are the SDK's contract + * (`crates/onionwire-sdk/src/lib.rs`), so a drift here is a client that lies + * about a message having landed. + */ +class DeliveryMarkerTest { + + @Test + fun delivered_row_gets_a_tick() { + val m = deliveryMarker("sent") + assertEquals(DeliveryMarker("\u2713", DeliveryTone.SENT), m) + } + + @Test + fun queued_row_says_queued_not_delivered() { + val m = deliveryMarker("queued") + assertEquals(DeliveryMarker("\u25f7 queued", DeliveryTone.PENDING), m) + } + + @Test + fun sending_row_is_pending() { + val m = deliveryMarker("sending") + assertEquals(DeliveryMarker("\u00bb sending", DeliveryTone.PENDING), m) + } + + @Test + fun failed_row_carries_the_reason() { + val m = deliveryMarker("failed: connection timed out") + assertEquals(DeliveryMarker("\u2717 failed: connection timed out", DeliveryTone.FAILED), m) + } + + @Test + fun failed_row_without_a_reason_still_reads_failed() { + assertEquals( + DeliveryMarker("\u2717 failed", DeliveryTone.FAILED), + deliveryMarker("failed"), + ) + } + + @Test + fun a_long_reason_is_elided() { + val m = deliveryMarker("failed: " + "x".repeat(200)) + val text = m?.text.orEmpty() + assertTrue(text.startsWith("\u2717 failed: xxx")) + assertTrue(text.endsWith("\u2026")) + assertTrue("marker grew to ${text.length} chars", text.length <= 48 + "\u2717 failed: ".length) + } + + @Test + fun incoming_row_has_no_marker() { + assertNull(deliveryMarker(null)) + assertNull(deliveryMarker("")) + assertNull(deliveryMarker(" ")) + } + + @Test + fun unknown_state_never_claims_delivery() { + // Fail-safe: an unreadable state renders nothing rather than a tick. + assertNull(deliveryMarker("scheduled")) + assertNull(deliveryMarker("SENT")) + } + + @Test + fun surrounding_whitespace_is_tolerated() { + assertEquals(DeliveryTone.SENT, deliveryMarker(" sent ")?.tone) + } + + @Test + fun pending_counts_only_queued_and_sending() { + assertTrue(isOutboxPending("queued")) + assertTrue(isOutboxPending("sending")) + assertFalse(isOutboxPending("sent")) + assertFalse(isOutboxPending("failed: no route")) + assertFalse(isOutboxPending(null)) + } +} From 6796f861e0319c38800ad9fd811e132e69bac41f Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 12 Sep 2026 19:15:34 -0400 Subject: [PATCH 8/8] docs(readme): keep manual-release bullet; do not resurrect auto-release on main paths --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 83fe649..98add8b 100644 --- a/README.md +++ b/README.md @@ -305,7 +305,7 @@ FORGEJO_TOKEN= scripts/build-release-local.sh vX.Y.Z Workflows (Forgejo Actions, `.forgejo/workflows/`): - [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — two jobs on the Pi runner (`docker` label), serialized by `onionwire-ci-pi`. `test`: `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` at the repo root. `sdk`: the same for `crates/onionwire-sdk` (separate cargo workspace — own `Cargo.lock`, root crate by path, `rustls` instead of `native-tls` — so a root signature change cannot silently break the Android SDK). Both run on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite. -- [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — on core paths to `main` (`src/`, `crates/`, `Cargo.toml`, `Cargo.lock`, `scripts/release-body.md`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release. `workflow_dispatch` rebuilds a tag or `dry_run`s. Concurrency group `onionwire-ci-pi` (same as `ci.yml`, `cancel-in-progress: false`) so cargo jobs do not overlap on the Pi. Amd64 dind is serialized by runner `capacity=1`. +- [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — manual, batched release (`workflow_dispatch` only: `dry_run`, `bump`, `version`, `tag`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release, fail-closed tag delete on failure. Dispatch [`android-release.yml`](.forgejo/workflows/android-release.yml) with that tag to add the APK + AAR (no automatic trigger fires on this Forgejo; it is `workflow_dispatch` only). Concurrency group `onionwire-ci-pi` (same as `ci.yml`, `cancel-in-progress: false`) so cargo jobs do not overlap on the Pi. Amd64 dind is serialized by runner `capacity=1`. Scripts: