Compare commits
63
Commits
9f3f9842c8
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2c1d444348 | ||
|
|
2c20b1c8a5 | ||
|
|
8657e6afc6 | ||
|
|
5b78e1566f | ||
|
|
0f5b5a16ab | ||
|
|
ea375fd88c | ||
|
|
b065d1783b | ||
|
|
fb980d12b4 | ||
|
|
f3f1b37221 | ||
|
|
6f339330c5 | ||
|
|
573291fc1e | ||
|
|
83a67f6fb1 | ||
|
|
c7a16d51e3 | ||
|
|
b1c9bac7d8 | ||
|
|
a61b47a947 | ||
|
|
597a28050f | ||
|
|
f90e40a3fc | ||
|
|
330e63e941 | ||
|
|
b8e756c3dd | ||
|
|
7faaf2aa1c | ||
|
|
746d809d48 | ||
|
|
70282dfb65 | ||
|
|
44e8c7322e | ||
|
|
29d0c1a73f | ||
|
|
d801a18db5 | ||
|
|
560d9c19b3 | ||
|
|
32db7fc4e8 | ||
|
|
863ab34915 | ||
|
|
a4e4a4ea63 | ||
|
|
ca622d3a39 | ||
|
|
abbed438ec | ||
|
|
6458c3183c | ||
|
|
9c50f2dbc1 | ||
|
|
487fd1c83c | ||
|
|
4e9f1d028a | ||
|
|
742916903b | ||
|
|
1ff2ef380c | ||
|
|
82c5a20848 | ||
|
|
34a64d6e53 | ||
|
|
7a6d922d12 | ||
|
|
27dc7917f2 | ||
|
|
4866f14231 | ||
|
|
8fba00ba7f | ||
|
|
7f0bdcbbc1 | ||
|
|
e6015033b6 | ||
|
|
2349a95dd4 | ||
|
|
7f936fa596 | ||
|
|
e5c7d690b8 | ||
|
|
524ed8ce53 | ||
|
|
dd43033888 | ||
|
|
6591d7cec0 | ||
|
|
3a33f6be15 | ||
|
|
c71636ad55 | ||
|
|
5a69e3927b | ||
|
|
1f182a7e7e | ||
|
|
7309158e12 | ||
|
|
8c09aecf4a | ||
|
|
060420c615 | ||
|
|
81f42ab761 | ||
|
|
9a519e3c5a | ||
|
|
17bf41a0b9 | ||
|
|
9286937e2d | ||
|
|
678c0344c8 |
No files matched your search
@@ -0,0 +1,79 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [master]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
gateway:
|
||||
name: Gateway plugin tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install uv
|
||||
run: curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
|
||||
# The gateway tests run inside the hermes-agent test harness, which is
|
||||
# git-ignored in this repo (read-only research reference). CI clones the
|
||||
# upstream repo at a pinned commit and drops in the vendored test copy.
|
||||
# Bump the pinned SHA when you update the local hermes-agent checkout.
|
||||
- name: Clone hermes-agent (pinned)
|
||||
run: |
|
||||
git clone https://github.com/NousResearch/hermes-agent.git hermes-agent
|
||||
git -C hermes-agent fetch --depth 1 origin 31f62d76af068abde3c699f91190e8ded07fd05b
|
||||
git -C hermes-agent checkout 31f62d76af068abde3c699f91190e8ded07fd05b
|
||||
|
||||
- name: Sync venv
|
||||
run: |
|
||||
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
|
||||
cd hermes-agent
|
||||
# pytest lives in the `dev` extra — a plain `uv sync` leaves the
|
||||
# venv without it and run_tests.sh refuses to run.
|
||||
uv sync --extra dev
|
||||
|
||||
- name: Run android gateway tests
|
||||
run: |
|
||||
cp tests/test_android.py hermes-agent/tests/gateway/test_android.py
|
||||
cd hermes-agent
|
||||
IRIS_PLUGIN_DIR="$GITHUB_WORKSPACE/gateway-plugin" \
|
||||
scripts/run_tests.sh tests/gateway/test_android.py
|
||||
|
||||
kotlin:
|
||||
name: Kotlin tests (android host + desktop)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "21"
|
||||
|
||||
# gradle.properties pins org.gradle.java.home to a local JDK path;
|
||||
# strip it so CI uses the JDK installed by setup-java.
|
||||
- name: Strip local JDK pin
|
||||
run: sed -i '/^org\.gradle\.java\.home/d' app/gradle.properties
|
||||
|
||||
- name: Install Android SDK
|
||||
run: |
|
||||
export ANDROID_HOME="$HOME/android-sdk"
|
||||
mkdir -p "$ANDROID_HOME/cmdline-tools"
|
||||
curl -fsSL -o /tmp/ct.zip \
|
||||
https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip
|
||||
unzip -q /tmp/ct.zip -d "$ANDROID_HOME/cmdline-tools"
|
||||
mv "$ANDROID_HOME/cmdline-tools/cmdline-tools" "$ANDROID_HOME/cmdline-tools/latest"
|
||||
# Finite input from a file: `yes | sdkmanager` dies with SIGPIPE
|
||||
# (exit 141) under Gitea's `bash -e -o pipefail` once sdkmanager
|
||||
# exits before `yes` is done writing.
|
||||
for i in $(seq 100); do echo y; done > /tmp/sdk_licenses_yes.txt
|
||||
"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses < /tmp/sdk_licenses_yes.txt > /dev/null
|
||||
echo "ANDROID_HOME=$ANDROID_HOME" >> "$GITHUB_ENV"
|
||||
echo "sdk.dir=$ANDROID_HOME" > app/local.properties
|
||||
|
||||
# Host-side tests only (no device needed). AGP auto-downloads the
|
||||
# missing SDK platforms (licenses accepted above).
|
||||
- name: Run host tests
|
||||
working-directory: app
|
||||
run: ./gradlew :shared:testAndroidHostTest :shared:desktopTest
|
||||
@@ -0,0 +1,226 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
# The release version comes from the repo-root VERSION file (the single
|
||||
# source of truth) — bump it in a commit, then dispatch this workflow.
|
||||
changelog:
|
||||
description: "Release notes (markdown, shown on the release page). Single-line field — use literal \\n for line breaks."
|
||||
required: false
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
gateway:
|
||||
name: Gateway plugin tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install uv
|
||||
run: curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
|
||||
- name: Clone hermes-agent (pinned)
|
||||
run: |
|
||||
git clone https://github.com/NousResearch/hermes-agent.git hermes-agent
|
||||
git -C hermes-agent fetch --depth 1 origin 31f62d76af068abde3c699f91190e8ded07fd05b
|
||||
git -C hermes-agent checkout 31f62d76af068abde3c699f91190e8ded07fd05b
|
||||
|
||||
- name: Sync venv
|
||||
run: |
|
||||
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
|
||||
cd hermes-agent
|
||||
# pytest lives in the `dev` extra — a plain `uv sync` leaves the
|
||||
# venv without it and run_tests.sh refuses to run.
|
||||
uv sync --extra dev
|
||||
|
||||
- name: Run android gateway tests
|
||||
run: |
|
||||
cp tests/test_android.py hermes-agent/tests/gateway/test_android.py
|
||||
cd hermes-agent
|
||||
IRIS_PLUGIN_DIR="$GITHUB_WORKSPACE/gateway-plugin" \
|
||||
scripts/run_tests.sh tests/gateway/test_android.py
|
||||
|
||||
kotlin:
|
||||
name: Kotlin tests (android host + desktop)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "21"
|
||||
|
||||
- name: Strip local JDK pin
|
||||
run: sed -i '/^org\.gradle\.java\.home/d' app/gradle.properties
|
||||
|
||||
- name: Install Android SDK
|
||||
run: |
|
||||
export ANDROID_HOME="$HOME/android-sdk"
|
||||
mkdir -p "$ANDROID_HOME/cmdline-tools"
|
||||
curl -fsSL -o /tmp/ct.zip \
|
||||
https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip
|
||||
unzip -q /tmp/ct.zip -d "$ANDROID_HOME/cmdline-tools"
|
||||
mv "$ANDROID_HOME/cmdline-tools/cmdline-tools" "$ANDROID_HOME/cmdline-tools/latest"
|
||||
# Finite input from a file: `yes | sdkmanager` dies with SIGPIPE
|
||||
# (exit 141) under Gitea's `bash -e -o pipefail` once sdkmanager
|
||||
# exits before `yes` is done writing.
|
||||
for i in $(seq 100); do echo y; done > /tmp/sdk_licenses_yes.txt
|
||||
"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses < /tmp/sdk_licenses_yes.txt > /dev/null
|
||||
echo "ANDROID_HOME=$ANDROID_HOME" >> "$GITHUB_ENV"
|
||||
echo "sdk.dir=$ANDROID_HOME" > app/local.properties
|
||||
|
||||
- name: Run host tests
|
||||
working-directory: app
|
||||
run: ./gradlew :shared:testAndroidHostTest :shared:desktopTest
|
||||
|
||||
# Gitea/act_runner does not implement the GitHub artifacts API
|
||||
# (upload-artifact@v4+ fails with GHESNotSupportedError), so the builds and
|
||||
# the release creation happen in ONE job — no artifact handoff between jobs.
|
||||
release:
|
||||
name: Build + create Gitea release
|
||||
runs-on: ubuntu-latest
|
||||
needs: [gateway, kotlin]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "21"
|
||||
|
||||
- name: Strip local JDK pin
|
||||
run: sed -i '/^org\.gradle\.java\.home/d' app/gradle.properties
|
||||
|
||||
- name: Install Android SDK
|
||||
run: |
|
||||
export ANDROID_HOME="$HOME/android-sdk"
|
||||
mkdir -p "$ANDROID_HOME/cmdline-tools"
|
||||
curl -fsSL -o /tmp/ct.zip \
|
||||
https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip
|
||||
unzip -q /tmp/ct.zip -d "$ANDROID_HOME/cmdline-tools"
|
||||
mv "$ANDROID_HOME/cmdline-tools/cmdline-tools" "$ANDROID_HOME/cmdline-tools/latest"
|
||||
# Finite input from a file: `yes | sdkmanager` dies with SIGPIPE
|
||||
# (exit 141) under Gitea's `bash -e -o pipefail` once sdkmanager
|
||||
# exits before `yes` is done writing.
|
||||
for i in $(seq 100); do echo y; done > /tmp/sdk_licenses_yes.txt
|
||||
"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses < /tmp/sdk_licenses_yes.txt > /dev/null
|
||||
echo "ANDROID_HOME=$ANDROID_HOME" >> "$GITHUB_ENV"
|
||||
echo "sdk.dir=$ANDROID_HOME" > app/local.properties
|
||||
|
||||
# jpackage --type deb shells out to fakeroot, which the runner image
|
||||
# does not ship.
|
||||
- name: Install fakeroot (for jpackage --type deb)
|
||||
run: sudo apt-get update -qq && sudo apt-get install -y -qq fakeroot
|
||||
|
||||
- name: Restore release keystore (from Gitea secrets)
|
||||
env:
|
||||
KS_B64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
|
||||
run: |
|
||||
if [ -n "$KS_B64" ]; then
|
||||
echo "$KS_B64" | base64 -d > app/release.keystore
|
||||
echo "ANDROID_KEYSTORE_FILE=$GITHUB_WORKSPACE/app/release.keystore" >> "$GITHUB_ENV"
|
||||
echo "ANDROID_KEYSTORE_PASSWORD=${{ secrets.ANDROID_KEYSTORE_PASSWORD }}" >> "$GITHUB_ENV"
|
||||
echo "ANDROID_KEY_ALIAS=${{ secrets.ANDROID_KEY_ALIAS }}" >> "$GITHUB_ENV"
|
||||
echo "ANDROID_KEY_PASSWORD=${{ secrets.ANDROID_KEY_PASSWORD }}" >> "$GITHUB_ENV"
|
||||
echo "Building SIGNED release APK"
|
||||
else
|
||||
echo "::warning::ANDROID_KEYSTORE_BASE64 secret not set — falling back to a DEBUG apk (see CI-SETUP.md §5)"
|
||||
fi
|
||||
|
||||
- name: Build APK + AAB
|
||||
run: |
|
||||
VERSION=$(cat "$GITHUB_WORKSPACE/VERSION")
|
||||
[ -n "$VERSION" ] || { echo "::error::VERSION file is missing or empty"; exit 1; }
|
||||
cd app
|
||||
if [ -n "$ANDROID_KEYSTORE_FILE" ]; then
|
||||
# APK for direct sideloading, AAB for Play Store uploads.
|
||||
./gradlew :androidApp:assembleRelease :androidApp:bundleRelease -PappVersion="$VERSION"
|
||||
cp androidApp/build/outputs/apk/release/androidApp-release.apk \
|
||||
"$GITHUB_WORKSPACE/iris-android-v$VERSION.apk"
|
||||
cp androidApp/build/outputs/bundle/release/androidApp-release.aab \
|
||||
"$GITHUB_WORKSPACE/iris-android-v$VERSION.aab"
|
||||
else
|
||||
./gradlew :androidApp:assembleDebug :androidApp:bundleDebug -PappVersion="$VERSION"
|
||||
cp androidApp/build/outputs/apk/debug/androidApp-debug.apk \
|
||||
"$GITHUB_WORKSPACE/iris-android-v$VERSION-debug.apk"
|
||||
cp androidApp/build/outputs/bundle/debug/androidApp-debug.aab \
|
||||
"$GITHUB_WORKSPACE/iris-android-v$VERSION-debug.aab"
|
||||
fi
|
||||
|
||||
# jpackage cannot cross-compile: this only produces Linux packages.
|
||||
# When a Windows / macOS runner exists later, add a second build job
|
||||
# for it (jpackage picks the native type: msi on Windows, dmg on macOS).
|
||||
- name: Build desktop app-image + deb
|
||||
run: |
|
||||
VERSION=$(cat "$GITHUB_WORKSPACE/VERSION")
|
||||
[ -n "$VERSION" ] || { echo "::error::VERSION file is missing or empty"; exit 1; }
|
||||
cd app
|
||||
# Self-contained app image (JRE bundled via jlink).
|
||||
./gradlew :desktopApp:jpackage -PappVersion="$VERSION"
|
||||
(cd desktopApp/build/jpackage && zip -qr \
|
||||
"$GITHUB_WORKSPACE/iris-desktop-linux-x64-v$VERSION.zip" iris)
|
||||
# .deb package (dpkg-deb ships with Ubuntu; fakeroot installed above).
|
||||
./gradlew :desktopApp:jpackage -PjpackageType=deb -PappVersion="$VERSION"
|
||||
cp desktopApp/build/jpackage/*.deb \
|
||||
"$GITHUB_WORKSPACE/iris-desktop-linux-x64-v$VERSION.deb"
|
||||
|
||||
- name: Create release + upload artifacts
|
||||
env:
|
||||
# Optional: create a personal access token (scope: Releases: write)
|
||||
# and store it as secret GITEA_TOKEN. Without it the workflow uses
|
||||
# the automatic GITHUB_TOKEN that Gitea Actions provides.
|
||||
RELEASE_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
SERVER="${GITEA_SERVER_URL:-$GITHUB_SERVER_URL}"
|
||||
REPO="${GITEA_REPOSITORY:-$GITHUB_REPOSITORY}"
|
||||
TOKEN="${RELEASE_TOKEN:-$GITHUB_TOKEN}"
|
||||
VERSION=$(cat "$GITHUB_WORKSPACE/VERSION")
|
||||
# The dispatch input is a single-line field; turn literal \n into real newlines.
|
||||
CHANGELOG=$(jq -r '.inputs.changelog // ""' "$GITHUB_EVENT_PATH" | sed 's/\\n/\n/g')
|
||||
TAG="v$VERSION"
|
||||
API="$SERVER/api/v1/repos/$REPO"
|
||||
AUTH="Authorization: token $TOKEN"
|
||||
|
||||
# curl wrapper: on HTTP >= 400, print the response body (Gitea's error
|
||||
# message) before failing — plain `curl -f` hides it (exit 22).
|
||||
api() {
|
||||
local code body
|
||||
body=$(mktemp)
|
||||
code=$(curl -s -o "$body" -w '%{http_code}' "$@") || { cat "$body"; rm -f "$body"; return 1; }
|
||||
if [ "${code:0:1}" != "2" ]; then
|
||||
echo "API error $code: $(cat "$body")" >&2
|
||||
rm -f "$body"
|
||||
return 1
|
||||
fi
|
||||
cat "$body"
|
||||
rm -f "$body"
|
||||
}
|
||||
|
||||
# Re-run safety: drop a previous release AND its tag for this version.
|
||||
# (Gitea's DELETE /releases/:id does NOT remove the tag; a leftover tag
|
||||
# makes the POST below fail with 409.)
|
||||
OLD_ID=$(api -H "$AUTH" "$API/releases/tags/$TAG" | jq -r '.id // empty') || true
|
||||
if [ -n "$OLD_ID" ]; then
|
||||
api -X DELETE -H "$AUTH" "$API/releases/$OLD_ID" > /dev/null
|
||||
fi
|
||||
api -X DELETE -H "$AUTH" "$API/tags/$TAG" > /dev/null || true
|
||||
|
||||
# Gitea creates the tag at the default branch HEAD automatically.
|
||||
RELEASE_ID=$(api -X POST -H "$AUTH" -H "Content-Type: application/json" \
|
||||
"$API/releases" \
|
||||
-d "$(jq -n --arg tag "$TAG" --arg title "Iris $VERSION" --arg body "$CHANGELOG" \
|
||||
'{tag_name:$tag, title:$title, body:$body}')" \
|
||||
| jq -r .id)
|
||||
echo "Created release $TAG (id $RELEASE_ID)"
|
||||
|
||||
for f in "$GITHUB_WORKSPACE"/iris-android-v* "$GITHUB_WORKSPACE"/iris-desktop-*; do
|
||||
[ -f "$f" ] || continue
|
||||
echo "Uploading $(basename "$f")"
|
||||
# Forgejo-style API: release assets live under /assets, not /attachments.
|
||||
api -X POST -H "$AUTH" -F "attachment=@$f" \
|
||||
"$API/releases/$RELEASE_ID/assets" > /dev/null
|
||||
done
|
||||
echo "Done: $SERVER/$REPO/releases/tag/$TAG"
|
||||
@@ -0,0 +1,19 @@
|
||||
# Gitleaks allowlist for iris_x_hermes.
|
||||
#
|
||||
# pi-lens runs `gitleaks detect --no-git` over the working tree, which includes
|
||||
# git-ignored paths. The hits below are all false positives:
|
||||
# - hermes-agent/ read-only research reference (never committed)
|
||||
# - **/build/** Gradle / jpackage build artifacts (regenerated)
|
||||
# - google-services.json standard Firebase config; its "API key" is a web
|
||||
# client key restricted by package name + SHA-1, and
|
||||
# the file is git-ignored (optional; FCM is inert
|
||||
# without it).
|
||||
title = "iris_x_hermes gitleaks allowlist"
|
||||
|
||||
[allowlist]
|
||||
description = "Git-ignored reference tree, build artifacts, and Firebase config"
|
||||
paths = [
|
||||
'''^hermes-agent/''',
|
||||
'''.*/build/''',
|
||||
'''^app/androidApp/google-services\.json$''',
|
||||
]
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"ignore": [
|
||||
"tests/test_android.py"
|
||||
],
|
||||
"rules": {
|
||||
"unchecked-throwing-call-python": {
|
||||
"disable": [
|
||||
"unchecked-throwing-call-python",
|
||||
"ast-grep:unchecked-throwing-call-python"
|
||||
]
|
||||
},
|
||||
"python-logger-credential-disclosure": {
|
||||
"disable": [
|
||||
"opengrep:python.lang.security.audit.logging.logger-credential-leak.python-logger-credential-disclosure"
|
||||
]
|
||||
},
|
||||
"sqlalchemy-execute-raw-query": {
|
||||
"disable": [
|
||||
"opengrep:python.sqlalchemy.security.sqlalchemy-execute-raw-query.sqlalchemy-execute-raw-query"
|
||||
]
|
||||
},
|
||||
"exported-activity": {
|
||||
"disable": [
|
||||
"opengrep:java.android.security.exported_activity.exported_activity"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,4 +12,10 @@ repos:
|
||||
entry: scripts/guard_hermes_agent.sh --staged
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
always_run: true
|
||||
- id: check-version-sync
|
||||
name: check gateway-plugin/plugin.yaml version == repo-root VERSION
|
||||
entry: scripts/check_version_sync.sh
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
@@ -3,38 +3,44 @@
|
||||
## Hard rules
|
||||
|
||||
- `hermes-agent/` is a **read-only research reference** (git-ignored). Never commit, push, or modify it — a pre-commit hook (`scripts/guard_hermes_agent.sh --staged`) fails any commit that stages it. Never modify hermes core; we only install our plugin into the live hermes home.
|
||||
- The plugin is installed by symlink: `~/.hermes/plugins/android` → `<repo>/gateway-plugin` (already set up on this machine).
|
||||
- A second pre-commit hook (`scripts/check_version_sync.sh`) fails any commit where the `gateway-plugin/plugin.yaml` version ≠ the repo-root `VERSION` file — keep them in sync.
|
||||
- **Commit/push scope:** when asked to "commit and push all changes," that means **all** changes in the working tree — it does NOT matter whether a change was made this session or earlier. Stage everything (`git add .`) and commit; do not cherry-pick or second-guess which files are "yours." The only exception is `hermes-agent/` (git-ignored, never staged).
|
||||
- The plugin is installed by symlink: `~/.hermes/plugins/iris` → `<repo>/gateway-plugin` (already set up on this machine).
|
||||
|
||||
## Layout
|
||||
|
||||
- `gateway-plugin/` — Python hermes platform plugin (`android`). No build step, zero new deps (stdlib + hermes-provided `websockets`/`httpx`). `protocol.py` is the frame source of truth, mirrored in `app/shared/.../protocol/Protocol.kt` and `docs/protocol/frames.schema.json`.
|
||||
- `app/` — one Compose Multiplatform Gradle project: `:shared` (KMP, most of the code; `jvmMain` is shared by the android and desktop targets since both are JVM-based), `:androidApp` (thin shell, package `dev.iris.app`), `:desktopApp` (thin shell).
|
||||
- `docs/` — numbered reference library; read `docs/00-overview.md` first. Locked decisions: `docs/16-open-questions.md`.
|
||||
- `tests/` — committed Python test suite: `test_android.py` (plugin tests; a copy of the hermes-agent mirror described below), `test_android_http.py` (HTTP fallback transport, see `docs/19-http-fallback-transport.md`), `ws_probe.py`, `e2e.py`, `README.md`.
|
||||
- `scripts/` — pre-commit guards (`guard_hermes_agent.sh`, `check_version_sync.sh`) and `make_release_keystore.sh`.
|
||||
- `backdrops/` — backdrop/wallpaper images (Pexels) used by the app theme.
|
||||
- `CI-SETUP.md` — Gitea CI/release setup reference.
|
||||
|
||||
## Commands
|
||||
|
||||
- `hermes` is **not on PATH**: use `hermes-agent/.venv/bin/hermes` (venv from `cd hermes-agent && uv sync`).
|
||||
- Gateway: `hermes gateway setup` (one-time; generates `ANDROID_TOKEN` in `~/.hermes/.env`, prints the token only once) → `hermes gateway` (run) → `hermes gateway status`.
|
||||
- Android: check the device is connected first (`adb devices` → `a5ca2a4b` listed as `device`); then `cd app && ./gradlew :androidApp:installDebug` to install on the phone and live-verify changes (launch/screenshot: see ADB below).
|
||||
- Gateway: `hermes gateway setup` (one-time; generates `IRIS_TOKEN` in `~/.hermes/.env`, prints the token only once) → `hermes gateway` (run) → `hermes gateway status`.
|
||||
- Android: check the device is connected first (`adb devices` → your device's serial listed as `device`; the serial differs per developer/machine); then `cd app && ./gradlew :androidApp:installDebug` to install on the phone and live-verify changes (launch/screenshot: see ADB below).
|
||||
- Desktop: `cd app && ./gradlew :desktopApp:run`; packaging: `:desktopApp:jpackage` (app-image; `-PjpackageType=deb` for a .deb).
|
||||
- Python tests — **never bare `pytest`**: `cd hermes-agent && scripts/run_tests.sh tests/gateway/test_android.py` (no args = full suite).
|
||||
- Kotlin tests: `cd app && ./gradlew :shared:testDebugUnitTest` / `:shared:desktopTest` (no test sources exist yet).
|
||||
- WS probe (gateway must be running): `hermes-agent/.venv/bin/python gateway-plugin/tests/ws_probe.py --token <ANDROID_TOKEN> --send "hello"` — assertion flags documented in `gateway-plugin/tests/README.md`.
|
||||
- E2E driver (gateway must be running; it never starts/stops it): `hermes-agent/.venv/bin/python gateway-plugin/tests/e2e.py`.
|
||||
- Kotlin tests: `cd app && ./gradlew :shared:testAndroidHostTest` / `:shared:desktopTest` (host-side; `jvmTest` is the shared source set).
|
||||
- WS probe (gateway must be running): `hermes-agent/.venv/bin/python tests/ws_probe.py --token <IRIS_TOKEN> --send "hello"` — assertion flags documented in `tests/README.md`.
|
||||
- E2E driver (gateway must be running; it never starts/stops it): `hermes-agent/.venv/bin/python tests/e2e.py`.
|
||||
|
||||
## Environment / pairing quirks
|
||||
|
||||
- Pairing token: `ANDROID_TOKEN` in `~/.hermes/.env`. The app has **no QR scanner** — pairing is manual URL + token entry.
|
||||
- WS default bind is `127.0.0.1`; for a phone on the LAN set `ANDROID_WS_HOST` to the gateway's LAN IP.
|
||||
- Pairing token: `IRIS_TOKEN` in `~/.hermes/.env`. Pairing is manual URL + token entry; on **Android** there's also a QR-scan button (camera) that fills URL + token from the gateway's pairing QR. Desktop has no camera, so it's manual entry only.
|
||||
- HTTP default bind is `127.0.0.1`; for a phone on the LAN set `IRIS_HTTP_HOST` to the gateway's LAN IP.
|
||||
- `app/local.properties` (`sdk.dir`) is git-ignored and required for Android builds.
|
||||
- `google-services.json` is optional: without it FCM is inert and ntfy is the push path. Public ntfy.sh SSE is flaky — self-host ntfy.
|
||||
- JDK 17; no system Gradle — always the wrapper (`./gradlew`).
|
||||
- Desktop jpackage on Linux/JDK 17 prints a non-fatal `pure virtual method called` (JDK-8348560); the app works.
|
||||
- **JDK 21** is required (the desktop Markdown renderer ships Java-21 bytecode); no system Gradle — always the wrapper (`./gradlew`). The JDK-21 home is machine-specific and set per machine (NOT committed): add `org.gradle.java.home=/path/to/jdk21` to `~/.gradle/gradle.properties`, or `export JAVA_HOME=/path/to/jdk21` before running `./gradlew`.
|
||||
- Desktop jpackage on Linux/JDK 21 prints a non-fatal `pure virtual method called` (JDK-8348560); the app works.
|
||||
|
||||
## Testing quirks
|
||||
|
||||
- `hermes-agent/tests/gateway/test_android.py` is a thin mirror that imports the **live `gateway-plugin/` package from this repo** (override with `ANDROID_PLUGIN_DIR`); HERMES_HOME is sandboxed per-test by the conftest. Tests must never touch the real `~/.hermes`.
|
||||
- `hermes-agent/tests/gateway/test_android.py` is a thin mirror that imports the **live `gateway-plugin/` package from this repo** (override with `IRIS_PLUGIN_DIR`); the committed `tests/test_android.py` is a copy of it, and `tests/test_android_http.py` covers the HTTP fallback transport. HERMES_HOME is sandboxed per-test by the conftest. Tests must never touch the real `~/.hermes`.
|
||||
- e2e scenarios 3 (reasoning) and 5 (commentary) are model-dependent → SKIP; 11 (push) and 12 (reconnect) are PARTIAL by design.
|
||||
- ADB: launch `adb shell am start -n dev.iris.app/.MainActivity`; reset pairing state `adb shell pm clear dev.iris.app`; screenshot `adb exec-out screencap -p > /tmp/shot.png`.
|
||||
- ADB UI taps: **never guess tap coordinates from a screenshot** — dump the hierarchy and tap the element's real bounds: `adb shell uiautomator dump` → `adb pull /sdcard/window_dump.xml` → find the node by `text` / `content-desc` / `resource-id` → `adb shell input tap` at the center of its `bounds="[x1,y1][x2,y2]"`. Re-dump after every navigation; if a tap misses, the dump is stale — re-dump, don't nudge coordinates.
|
||||
- Gateway logs: `~/.hermes/logs/gateway.log` or `hermes logs --follow`.
|
||||
- Gateway logs: `~/.hermes/logs/gateway.log` or `hermes logs --follow`.
|
||||
+518
@@ -0,0 +1,518 @@
|
||||
# CI / Release setup — manual edit list
|
||||
|
||||
Everything needed for the Gitea workflows (CI + manual release). Items marked
|
||||
**DONE** were already applied; the rest are copy-paste instructions.
|
||||
|
||||
---
|
||||
|
||||
## 1. DONE — no action needed
|
||||
|
||||
- `tests/test_android.py` — vendored byte-identical mirror of
|
||||
`hermes-agent/tests/gateway/test_android.py` (the git-ignored hermes checkout
|
||||
is the canonical copy; **keep the two in sync** when you change that test).
|
||||
- `.pi-lens.json` — added `"ignore": ["tests/test_android.py"]`
|
||||
so the scanner doesn't flag the vendored mirror.
|
||||
|
||||
---
|
||||
|
||||
## 2. NEW FILE: `.gitea/workflows/ci.yml`
|
||||
|
||||
Runs on every push to `master` and on PRs: gateway plugin tests + Kotlin host
|
||||
tests (android + desktop).
|
||||
|
||||
```yaml
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [master]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
gateway:
|
||||
name: Gateway plugin tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install uv
|
||||
run: curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
|
||||
# The gateway tests run inside the hermes-agent test harness, which is
|
||||
# git-ignored in this repo (read-only research reference). CI clones the
|
||||
# upstream repo at a pinned commit and drops in the vendored test copy.
|
||||
# Bump the pinned SHA when you update the local hermes-agent checkout.
|
||||
- name: Clone hermes-agent (pinned)
|
||||
run: |
|
||||
git clone https://github.com/NousResearch/hermes-agent.git hermes-agent
|
||||
git -C hermes-agent fetch --depth 1 origin 31f62d76af068abde3c699f91190e8ded07fd05b
|
||||
git -C hermes-agent checkout 31f62d76af068abde3c699f91190e8ded07fd05b
|
||||
|
||||
- name: Sync venv
|
||||
run: |
|
||||
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
|
||||
cd hermes-agent
|
||||
uv sync
|
||||
|
||||
- name: Run android gateway tests
|
||||
run: |
|
||||
cp tests/test_android.py hermes-agent/tests/gateway/test_android.py
|
||||
cd hermes-agent
|
||||
IRIS_PLUGIN_DIR="$GITHUB_WORKSPACE/gateway-plugin" \
|
||||
scripts/run_tests.sh tests/gateway/test_android.py
|
||||
|
||||
kotlin:
|
||||
name: Kotlin tests (android host + desktop)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "21"
|
||||
|
||||
# gradle.properties pins org.gradle.java.home to a local JDK path;
|
||||
# strip it so CI uses the JDK installed by setup-java.
|
||||
- name: Strip local JDK pin
|
||||
run: sed -i '/^org\.gradle\.java\.home/d' app/gradle.properties
|
||||
|
||||
- name: Install Android SDK
|
||||
run: |
|
||||
export ANDROID_HOME="$HOME/android-sdk"
|
||||
mkdir -p "$ANDROID_HOME/cmdline-tools"
|
||||
curl -fsSL -o /tmp/ct.zip \
|
||||
https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip
|
||||
unzip -q /tmp/ct.zip -d "$ANDROID_HOME/cmdline-tools"
|
||||
mv "$ANDROID_HOME/cmdline-tools/cmdline-tools" "$ANDROID_HOME/cmdline-tools/latest"
|
||||
yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses > /dev/null
|
||||
echo "ANDROID_HOME=$ANDROID_HOME" >> "$GITHUB_ENV"
|
||||
echo "sdk.dir=$ANDROID_HOME" > app/local.properties
|
||||
|
||||
# Host-side tests only (no device needed). AGP auto-downloads the
|
||||
# missing SDK platforms (licenses accepted above).
|
||||
- name: Run host tests
|
||||
working-directory: app
|
||||
run: ./gradlew :shared:testAndroidHostTest :shared:desktopTest
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. NEW FILE: `.gitea/workflows/release.yml`
|
||||
|
||||
The release version is the repo-root **`VERSION` file** (single source of
|
||||
truth — "everything from here on out is vX.Y.Z" = bump `VERSION` and
|
||||
commit). Manual trigger: **repo → Actions → Release → Run workflow**,
|
||||
optionally with a `changelog`. It runs the same tests as CI, builds a signed
|
||||
Android APK + AAB and the Linux desktop packages (jpackage, JRE bundled),
|
||||
then creates the Gitea release `v<VERSION>` with all artifacts as download
|
||||
attachments.
|
||||
|
||||
Note: builds + release creation happen in ONE job because Gitea/act_runner
|
||||
does not implement the GitHub artifacts API (`upload-artifact@v4+` fails
|
||||
with `GHESNotSupportedError`).
|
||||
|
||||
```yaml
|
||||
name: Release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
# The release version comes from the repo-root VERSION file (the single
|
||||
# source of truth) — bump it in a commit, then dispatch this workflow.
|
||||
changelog:
|
||||
description: "Release notes (markdown, shown on the release page). Single-line field — use literal \\n for line breaks."
|
||||
required: false
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
gateway:
|
||||
name: Gateway plugin tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install uv
|
||||
run: curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
|
||||
- name: Clone hermes-agent (pinned)
|
||||
run: |
|
||||
git clone https://github.com/NousResearch/hermes-agent.git hermes-agent
|
||||
git -C hermes-agent fetch --depth 1 origin 31f62d76af068abde3c699f91190e8ded07fd05b
|
||||
git -C hermes-agent checkout 31f62d76af068abde3c699f91190e8ded07fd05b
|
||||
|
||||
- name: Sync venv
|
||||
run: |
|
||||
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
|
||||
cd hermes-agent
|
||||
# pytest lives in the `dev` extra — a plain `uv sync` leaves the
|
||||
# venv without it and run_tests.sh refuses to run.
|
||||
uv sync --extra dev
|
||||
|
||||
- name: Run android gateway tests
|
||||
run: |
|
||||
cp tests/test_android.py hermes-agent/tests/gateway/test_android.py
|
||||
cd hermes-agent
|
||||
IRIS_PLUGIN_DIR="$GITHUB_WORKSPACE/gateway-plugin" \
|
||||
scripts/run_tests.sh tests/gateway/test_android.py
|
||||
|
||||
kotlin:
|
||||
name: Kotlin tests (android host + desktop)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "21"
|
||||
|
||||
- name: Strip local JDK pin
|
||||
run: sed -i '/^org\.gradle\.java\.home/d' app/gradle.properties
|
||||
|
||||
- name: Install Android SDK
|
||||
run: |
|
||||
export ANDROID_HOME="$HOME/android-sdk"
|
||||
mkdir -p "$ANDROID_HOME/cmdline-tools"
|
||||
curl -fsSL -o /tmp/ct.zip \
|
||||
https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip
|
||||
unzip -q /tmp/ct.zip -d "$ANDROID_HOME/cmdline-tools"
|
||||
mv "$ANDROID_HOME/cmdline-tools/cmdline-tools" "$ANDROID_HOME/cmdline-tools/latest"
|
||||
# Finite input from a file: `yes | sdkmanager` dies with SIGPIPE
|
||||
# (exit 141) under Gitea's `bash -e -o pipefail` once sdkmanager
|
||||
# exits before `yes` is done writing.
|
||||
for i in $(seq 100); do echo y; done > /tmp/sdk_licenses_yes.txt
|
||||
"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses < /tmp/sdk_licenses_yes.txt > /dev/null
|
||||
echo "ANDROID_HOME=$ANDROID_HOME" >> "$GITHUB_ENV"
|
||||
echo "sdk.dir=$ANDROID_HOME" > app/local.properties
|
||||
|
||||
- name: Run host tests
|
||||
working-directory: app
|
||||
run: ./gradlew :shared:testAndroidHostTest :shared:desktopTest
|
||||
|
||||
# Gitea/act_runner does not implement the GitHub artifacts API
|
||||
# (upload-artifact@v4+ fails with GHESNotSupportedError), so the builds and
|
||||
# the release creation happen in ONE job — no artifact handoff between jobs.
|
||||
release:
|
||||
name: Build + create Gitea release
|
||||
runs-on: ubuntu-latest
|
||||
needs: [gateway, kotlin]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "21"
|
||||
|
||||
- name: Strip local JDK pin
|
||||
run: sed -i '/^org\.gradle\.java\.home/d' app/gradle.properties
|
||||
|
||||
- name: Install Android SDK
|
||||
run: |
|
||||
export ANDROID_HOME="$HOME/android-sdk"
|
||||
mkdir -p "$ANDROID_HOME/cmdline-tools"
|
||||
curl -fsSL -o /tmp/ct.zip \
|
||||
https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip
|
||||
unzip -q /tmp/ct.zip -d "$ANDROID_HOME/cmdline-tools"
|
||||
mv "$ANDROID_HOME/cmdline-tools/cmdline-tools" "$ANDROID_HOME/cmdline-tools/latest"
|
||||
# Finite input from a file: `yes | sdkmanager` dies with SIGPIPE
|
||||
# (exit 141) under Gitea's `bash -e -o pipefail` once sdkmanager
|
||||
# exits before `yes` is done writing.
|
||||
for i in $(seq 100); do echo y; done > /tmp/sdk_licenses_yes.txt
|
||||
"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses < /tmp/sdk_licenses_yes.txt > /dev/null
|
||||
echo "ANDROID_HOME=$ANDROID_HOME" >> "$GITHUB_ENV"
|
||||
echo "sdk.dir=$ANDROID_HOME" > app/local.properties
|
||||
|
||||
# jpackage --type deb shells out to fakeroot, which the runner image
|
||||
# does not ship.
|
||||
- name: Install fakeroot (for jpackage --type deb)
|
||||
run: sudo apt-get update -qq && sudo apt-get install -y -qq fakeroot
|
||||
|
||||
- name: Restore release keystore (from Gitea secrets)
|
||||
env:
|
||||
KS_B64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
|
||||
run: |
|
||||
if [ -n "$KS_B64" ]; then
|
||||
echo "$KS_B64" | base64 -d > app/release.keystore
|
||||
echo "ANDROID_KEYSTORE_FILE=$GITHUB_WORKSPACE/app/release.keystore" >> "$GITHUB_ENV"
|
||||
echo "ANDROID_KEYSTORE_PASSWORD=${{ secrets.ANDROID_KEYSTORE_PASSWORD }}" >> "$GITHUB_ENV"
|
||||
echo "ANDROID_KEY_ALIAS=${{ secrets.ANDROID_KEY_ALIAS }}" >> "$GITHUB_ENV"
|
||||
echo "ANDROID_KEY_PASSWORD=${{ secrets.ANDROID_KEY_PASSWORD }}" >> "$GITHUB_ENV"
|
||||
echo "Building SIGNED release APK"
|
||||
else
|
||||
echo "::warning::ANDROID_KEYSTORE_BASE64 secret not set — falling back to a DEBUG apk (see CI-SETUP.md §5)"
|
||||
fi
|
||||
|
||||
- name: Build APK + AAB
|
||||
run: |
|
||||
VERSION=$(cat "$GITHUB_WORKSPACE/VERSION")
|
||||
[ -n "$VERSION" ] || { echo "::error::VERSION file is missing or empty"; exit 1; }
|
||||
cd app
|
||||
if [ -n "$ANDROID_KEYSTORE_FILE" ]; then
|
||||
# APK for direct sideloading, AAB for Play Store uploads.
|
||||
./gradlew :androidApp:assembleRelease :androidApp:bundleRelease -PappVersion="$VERSION"
|
||||
cp androidApp/build/outputs/apk/release/androidApp-release.apk \
|
||||
"$GITHUB_WORKSPACE/iris-android-v$VERSION.apk"
|
||||
cp androidApp/build/outputs/bundle/release/androidApp-release.aab \
|
||||
"$GITHUB_WORKSPACE/iris-android-v$VERSION.aab"
|
||||
else
|
||||
./gradlew :androidApp:assembleDebug :androidApp:bundleDebug -PappVersion="$VERSION"
|
||||
cp androidApp/build/outputs/apk/debug/androidApp-debug.apk \
|
||||
"$GITHUB_WORKSPACE/iris-android-v$VERSION-debug.apk"
|
||||
cp androidApp/build/outputs/bundle/debug/androidApp-debug.aab \
|
||||
"$GITHUB_WORKSPACE/iris-android-v$VERSION-debug.aab"
|
||||
fi
|
||||
|
||||
# jpackage cannot cross-compile: this only produces Linux packages.
|
||||
# When a Windows / macOS runner exists later, add a second build job
|
||||
# for it (jpackage picks the native type: msi on Windows, dmg on macOS).
|
||||
- name: Build desktop app-image + deb
|
||||
run: |
|
||||
VERSION=$(cat "$GITHUB_WORKSPACE/VERSION")
|
||||
[ -n "$VERSION" ] || { echo "::error::VERSION file is missing or empty"; exit 1; }
|
||||
cd app
|
||||
# Self-contained app image (JRE bundled via jlink).
|
||||
./gradlew :desktopApp:jpackage -PappVersion="$VERSION"
|
||||
(cd desktopApp/build/jpackage && zip -qr \
|
||||
"$GITHUB_WORKSPACE/iris-desktop-linux-x64-v$VERSION.zip" iris)
|
||||
# .deb package (dpkg-deb ships with Ubuntu; fakeroot installed above).
|
||||
./gradlew :desktopApp:jpackage -PjpackageType=deb -PappVersion="$VERSION"
|
||||
cp desktopApp/build/jpackage/*.deb \
|
||||
"$GITHUB_WORKSPACE/iris-desktop-linux-x64-v$VERSION.deb"
|
||||
|
||||
- name: Create release + upload artifacts
|
||||
env:
|
||||
# Optional: create a personal access token (scope: Releases: write)
|
||||
# and store it as secret GITEA_TOKEN. Without it the workflow uses
|
||||
# the automatic GITHUB_TOKEN that Gitea Actions provides.
|
||||
RELEASE_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
SERVER="${GITEA_SERVER_URL:-$GITHUB_SERVER_URL}"
|
||||
REPO="${GITEA_REPOSITORY:-$GITHUB_REPOSITORY}"
|
||||
TOKEN="${RELEASE_TOKEN:-$GITHUB_TOKEN}"
|
||||
VERSION=$(cat "$GITHUB_WORKSPACE/VERSION")
|
||||
# The dispatch input is a single-line field; turn literal \n into real newlines.
|
||||
CHANGELOG=$(jq -r '.inputs.changelog // ""' "$GITHUB_EVENT_PATH" | sed 's/\\n/\n/g')
|
||||
TAG="v$VERSION"
|
||||
API="$SERVER/api/v1/repos/$REPO"
|
||||
AUTH="Authorization: token $TOKEN"
|
||||
|
||||
# curl wrapper: on HTTP >= 400, print the response body (Gitea's error
|
||||
# message) before failing — plain `curl -f` hides it (exit 22).
|
||||
api() {
|
||||
local code body
|
||||
body=$(mktemp)
|
||||
code=$(curl -s -o "$body" -w '%{http_code}' "$@") || { cat "$body"; rm -f "$body"; return 1; }
|
||||
if [ "${code:0:1}" != "2" ]; then
|
||||
echo "API error $code: $(cat "$body")" >&2
|
||||
rm -f "$body"
|
||||
return 1
|
||||
fi
|
||||
cat "$body"
|
||||
rm -f "$body"
|
||||
}
|
||||
|
||||
# Re-run safety: drop a previous release AND its tag for this version.
|
||||
# (Gitea's DELETE /releases/:id does NOT remove the tag; a leftover tag
|
||||
# makes the POST below fail with 409.)
|
||||
OLD_ID=$(api -H "$AUTH" "$API/releases/tags/$TAG" | jq -r '.id // empty') || true
|
||||
if [ -n "$OLD_ID" ]; then
|
||||
api -X DELETE -H "$AUTH" "$API/releases/$OLD_ID" > /dev/null
|
||||
fi
|
||||
api -X DELETE -H "$AUTH" "$API/tags/$TAG" > /dev/null || true
|
||||
|
||||
# Gitea creates the tag at the default branch HEAD automatically.
|
||||
RELEASE_ID=$(api -X POST -H "$AUTH" -H "Content-Type: application/json" \
|
||||
"$API/releases" \
|
||||
-d "$(jq -n --arg tag "$TAG" --arg title "Iris $VERSION" --arg body "$CHANGELOG" \
|
||||
'{tag_name:$tag, title:$title, body:$body}')" \
|
||||
| jq -r .id)
|
||||
echo "Created release $TAG (id $RELEASE_ID)"
|
||||
|
||||
for f in "$GITHUB_WORKSPACE"/iris-android-v* "$GITHUB_WORKSPACE"/iris-desktop-*; do
|
||||
[ -f "$f" ] || continue
|
||||
echo "Uploading $(basename "$f")"
|
||||
# Forgejo-style API: release assets live under /assets, not /attachments.
|
||||
api -X POST -H "$AUTH" -F "attachment=@$f" \
|
||||
"$API/releases/$RELEASE_ID/assets" > /dev/null
|
||||
done
|
||||
echo "Done: $SERVER/$REPO/releases/tag/$TAG"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. EDITS to existing Gradle files
|
||||
|
||||
> **Note (versioning):** the `versionName` / `appVersion` lines shown below
|
||||
> have since been changed to read the repo-root **`VERSION` file** (single
|
||||
> source of truth; `-PappVersion` still overrides in CI). See
|
||||
> `.gitea/workflows/release.yml` and `gateway-plugin/version.py`.
|
||||
|
||||
### 4a. `app/androidApp/build.gradle.kts`
|
||||
|
||||
**Change 1** — in `defaultConfig`, replace:
|
||||
|
||||
```kotlin
|
||||
versionName = "0.1.0"
|
||||
```
|
||||
|
||||
with:
|
||||
|
||||
```kotlin
|
||||
// CI passes -PappVersion=<version> (release workflow); local builds
|
||||
// keep the default.
|
||||
versionName = (project.findProperty("appVersion") as? String) ?: "0.1.0"
|
||||
```
|
||||
|
||||
**Change 2** — inside the `android { }` block, right after the `buildTypes { }`
|
||||
block, add:
|
||||
|
||||
```kotlin
|
||||
// CI release signing: .gitea/workflows/release.yml restores a keystore
|
||||
// from Gitea secrets and exports ANDROID_KEYSTORE_* env vars (see
|
||||
// scripts/make_release_keystore.sh). Without them the release build stays
|
||||
// unsigned and the workflow falls back to a debug APK.
|
||||
val ciKeystore = System.getenv("ANDROID_KEYSTORE_FILE")
|
||||
if (ciKeystore != null) {
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
storeFile = file(ciKeystore)
|
||||
storePassword = System.getenv("ANDROID_KEYSTORE_PASSWORD")
|
||||
keyAlias = System.getenv("ANDROID_KEY_ALIAS")
|
||||
keyPassword = System.getenv("ANDROID_KEY_PASSWORD")
|
||||
}
|
||||
}
|
||||
buildTypes {
|
||||
release {
|
||||
signingConfig = signingConfigs.getByName("release")
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4b. `app/desktopApp/build.gradle.kts`
|
||||
|
||||
**Change 1** — near the top (after `val arch = ...`), add:
|
||||
|
||||
```kotlin
|
||||
// CI passes -PappVersion=<version> (release workflow); local builds keep the
|
||||
// default. jpackage requires a plain semver (no leading "v").
|
||||
val appVersion = (project.findProperty("appVersion") as? String) ?: "0.1.0"
|
||||
```
|
||||
|
||||
**Change 2** — in the `jpackage` Exec task's `commandLine(...)`, replace:
|
||||
|
||||
```kotlin
|
||||
"--app-version", "0.1.0",
|
||||
```
|
||||
|
||||
with:
|
||||
|
||||
```kotlin
|
||||
"--app-version", appVersion,
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. NEW FILE: `scripts/make_release_keystore.sh` (Android signing, one-time)
|
||||
|
||||
This is the noob-friendly signing setup. Run it **once** on your machine:
|
||||
|
||||
```bash
|
||||
scripts/make_release_keystore.sh
|
||||
```
|
||||
|
||||
It generates a keystore with random passwords and prints the four values to
|
||||
paste into Gitea. Then create the secrets in
|
||||
**Gitea → repo → Settings → Actions → Secrets**:
|
||||
|
||||
| Secret | Value |
|
||||
| --- | --- |
|
||||
| `ANDROID_KEYSTORE_BASE64` | the long base64 blob the script prints |
|
||||
| `ANDROID_KEYSTORE_PASSWORD` | printed by the script |
|
||||
| `ANDROID_KEY_ALIAS` | `iris` |
|
||||
| `ANDROID_KEY_PASSWORD` | printed by the script |
|
||||
|
||||
Until the secrets exist, the release workflow still works but ships a
|
||||
**debug** APK (installable, but not suitable for updates).
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
# One-time setup: create the Android release keystore and print the values to
|
||||
# paste into Gitea (repo -> Settings -> Actions -> Secrets).
|
||||
#
|
||||
# Usage: scripts/make_release_keystore.sh [output-file]
|
||||
# (default: ~/iris-release.keystore)
|
||||
#
|
||||
# WARNING: back up the keystore file immediately. If it is lost, the app can
|
||||
# never be updated on users' phones (a new key = a brand-new app as far as
|
||||
# Android is concerned).
|
||||
set -euo pipefail
|
||||
|
||||
OUT="${1:-$HOME/iris-release.keystore}"
|
||||
if [ -e "$OUT" ]; then
|
||||
echo "Refusing to overwrite existing file: $OUT" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
STORE_PASS="$(openssl rand -base64 18 | tr -d '/+=')"
|
||||
KEY_PASS="$(openssl rand -base64 18 | tr -d '/+=')"
|
||||
|
||||
keytool -genkeypair -v \
|
||||
-keystore "$OUT" -storetype PKCS12 \
|
||||
-alias iris -keyalg RSA -keysize 2048 -validity 10000 \
|
||||
-storepass "$STORE_PASS" -keypass "$KEY_PASS" \
|
||||
-dname "CN=Iris Release, OU=Mobile, O=Iris, C=DE"
|
||||
|
||||
echo
|
||||
echo "Keystore written to: $OUT"
|
||||
echo ">>> Back it up NOW (password manager / cloud storage). <<<"
|
||||
echo
|
||||
echo "Add these four secrets in Gitea (repo -> Settings -> Actions -> Secrets):"
|
||||
echo
|
||||
echo " ANDROID_KEYSTORE_BASE64 = $(base64 -w0 "$OUT")"
|
||||
echo
|
||||
echo " ANDROID_KEYSTORE_PASSWORD = $STORE_PASS"
|
||||
echo " ANDROID_KEY_ALIAS = iris"
|
||||
echo " ANDROID_KEY_PASSWORD = $KEY_PASS"
|
||||
```
|
||||
|
||||
Don't forget: `chmod +x scripts/make_release_keystore.sh`
|
||||
|
||||
---
|
||||
|
||||
## 6. Prerequisites / checks before the first run
|
||||
|
||||
1. **act_runner must be registered** on gitea.zephyre.one with the label
|
||||
`ubuntu-latest` (that's what both workflows request). Check under
|
||||
Gitea → (your user or the org) → Actions → Runners.
|
||||
2. The runner needs internet access (GitHub, Google, Maven Central, Gradle).
|
||||
3. No Gitea secrets are *required* — but add the four keystore secrets from
|
||||
§5 for a signed APK, and optionally a `GITEA_TOKEN` (Releases: write) if
|
||||
the automatic `GITHUB_TOKEN` doesn't have release permission.
|
||||
|
||||
## 7. Using it
|
||||
|
||||
- **CI**: pushes to `master` / PRs run automatically.
|
||||
- **Release**: repo → **Actions** → *Release* → **Run workflow** → enter
|
||||
`version` (e.g. `0.2.0`) + `changelog` → start. The release appears at
|
||||
`https://gitea.zephyre.one/ARIA/iris_x_hermes/releases/tag/v0.2.0` with:
|
||||
- `iris-android-v0.2.0.apk` (signed, or `-debug` without keystore secrets)
|
||||
- `iris-desktop-linux-x64-v0.2.0.zip` (app image, JRE bundled)
|
||||
- `iris-desktop-linux-x64-v0.2.0.deb`
|
||||
- Re-running with the same version **replaces** the old release (old tag +
|
||||
attachments are deleted first).
|
||||
|
||||
## 8. Later: Windows / macOS desktop builds
|
||||
|
||||
When the Windows VM / MacBook runner exists:
|
||||
|
||||
1. Register act_runner on that machine (labels e.g. `windows-latest`,
|
||||
`macos-latest`).
|
||||
2. In `release.yml`, copy the `desktop` job, change `runs-on`, and adjust the
|
||||
artifact names (`iris-desktop-windows-x64-…`, `iris-desktop-macos-…`).
|
||||
jpackage then produces `msi`/`dmg` natively — no other changes needed.
|
||||
3. Bump the pinned hermes-agent SHA in both workflows whenever you update the
|
||||
local `hermes-agent/` checkout (`git -C hermes-agent rev-parse HEAD`).
|
||||
@@ -2,14 +2,21 @@
|
||||
|
||||
A chat app for [hermes-agent](https://github.com/NousResearch/hermes-agent): a **native Android app** and a **desktop app** (Linux, macOS, Windows) — both built from one shared Kotlin codebase (Compose Multiplatform).
|
||||
|
||||
Iris pairs with your running `hermes gateway` over a private WebSocket and gives you a Telegram-quality chat experience with your personal agent: streaming replies, visible reasoning, structured tool activity, channels, threads, media, search, and push notifications.
|
||||
Iris pairs with your running `hermes gateway` over a private, token-authenticated connection and gives you a Telegram-quality chat experience with your personal agent: streaming replies, visible reasoning, structured tool activity, channels, threads, media, search, and push notifications.
|
||||
|
||||
## Features
|
||||
|
||||
- **Native Hermes-Gateway integration** — your hermes → gateway → Iris app
|
||||
- **Absolute Privacy!** — everything stays on your own infrastructure
|
||||
- **No file limit**
|
||||
- **No character limit**
|
||||
- **Absolute Privacy!** — chat stays on your own infrastructure
|
||||
(push: ntfy by default, **but the default ntfy server is the public
|
||||
`ntfy.sh`** — self-host ntfy to keep push metadata on your own machine;
|
||||
FCM is opt-in and routes push metadata via Google — see
|
||||
[Push notifications](#push-notifications))
|
||||
- **100 MB file uploads by default** — configurable on the gateway via
|
||||
`max_upload_bytes` (see [Media](docs/07-media.md) §7.7); all limits are set
|
||||
on the gateway side (hermes), not in the app
|
||||
- **No 4,096-character message limit like Telegram** — messages travel over
|
||||
your own gateway (hard frame-body cap: 1 MiB)
|
||||
- **Full markdown support** — tables, checkmarks, bold, inline code, code blocks + syntax highlighting…
|
||||
- **HTML Artifact Preview** — agent-sent HTML/CSS/JS rendered in an in-app WebView
|
||||
- **All settings live in the app**, not in hermes `config.yml`! Change everything on the fly.
|
||||
@@ -24,11 +31,11 @@ Iris pairs with your running `hermes gateway` over a private WebSocket and gives
|
||||
## How it works
|
||||
|
||||
```
|
||||
hermes-agent ──> hermes gateway ──(WebSocket :8790)──> Iris app (Android / Desktop)
|
||||
hermes-agent ──> hermes gateway ──(HTTP :8791)──> Iris app (Android / Desktop)
|
||||
```
|
||||
|
||||
- `gateway-plugin/` is a hermes **platform plugin** (`android`). It runs inside the
|
||||
`hermes gateway` process and opens a WebSocket server the apps connect to.
|
||||
`hermes gateway` process and opens an HTTP server the apps connect to.
|
||||
Zero new Python dependencies, zero hermes-core changes.
|
||||
- `app/` is one Compose Multiplatform Gradle project: `:shared` (KMP, most of the
|
||||
code), `:androidApp` (native Kotlin + Jetpack Compose client), `:desktopApp`
|
||||
@@ -36,14 +43,53 @@ hermes-agent ──> hermes gateway ──(WebSocket :8790)──> Iris app (And
|
||||
- The app is a first-class hermes *messaging platform*, so everything the gateway
|
||||
already does just works: slash commands, cron delivery, `send_message` routing,
|
||||
coexistence with Telegram/Discord/etc.
|
||||
- Push notifications: FCM (primary) or ntfy (fallback).
|
||||
- Push notifications: ntfy (default) or FCM (opt-in).
|
||||
|
||||
## Push notifications
|
||||
|
||||
Push wakes a backgrounded/offline device; on reconnect the app syncs the
|
||||
outbox, so nothing is lost.
|
||||
|
||||
- **ntfy (default)** — the backend for truly private communication.
|
||||
⚠️ **By default it uses the public `https://ntfy.sh` cloud service** — push
|
||||
metadata (topic, notification title) passes through ntfy.sh's servers.
|
||||
Set `NTFY_SERVER_URL` to a **self-hosted ntfy** to keep push metadata on
|
||||
your own infrastructure (recommended; public ntfy.sh SSE is also flaky).
|
||||
- **FCM (opt-in, `IRIS_PUSH_BACKEND=fcm`)** — standard/reliable, but FCM push
|
||||
metadata (notification title, device token) is routed through **Google's
|
||||
servers**. If you want truly private communication, use ntfy instead.
|
||||
|
||||
Setup: [`docs/install.md`](docs/install.md); details:
|
||||
[`docs/08-push.md`](docs/08-push.md).
|
||||
|
||||
## Install the gateway
|
||||
|
||||
Three commands on the machine where hermes runs:
|
||||
|
||||
```bash
|
||||
cd hermes-agent && uv sync # 1. hermes with its venv (separate project, not this repo)
|
||||
|
||||
# 2. install the Iris plugin — the #gateway-plugin suffix points the
|
||||
# installer at the plugin subfolder of this monorepo
|
||||
hermes plugins install git@gitea.zephyre.one:ARIA/iris_x_hermes.git#gateway-plugin
|
||||
|
||||
# 3. generate the pairing token + server URL, then run the gateway
|
||||
hermes gateway setup
|
||||
hermes gateway
|
||||
```
|
||||
|
||||
`hermes gateway setup` prints the **server URL** and **pairing token / QR**
|
||||
the app needs on its Connect screen.
|
||||
|
||||
All options (LAN binding, TLS, push, device allowlist) and the full app
|
||||
pairing walkthrough: [`docs/install.md`](docs/install.md).
|
||||
|
||||
## Build from source
|
||||
|
||||
### Prerequisites
|
||||
|
||||
| Where | You need |
|
||||
|---|---|
|
||||
| --- | --- |
|
||||
| Gateway host | [hermes-agent](https://github.com/NousResearch/hermes-agent) with its venv (`uv sync`) |
|
||||
| Android build machine | JDK 17, Android SDK (`sdk.dir` in `app/local.properties` or `ANDROID_HOME`), ADB with a connected device |
|
||||
| Desktop build machine | JDK 17 only |
|
||||
@@ -52,19 +98,21 @@ No system Gradle needed — both apps use the project wrapper (`./gradlew`).
|
||||
|
||||
### 1. Gateway (on the gateway host)
|
||||
|
||||
If you're developing from a checkout, skip `hermes plugins install` and
|
||||
symlink the plugin so it always tracks your working tree:
|
||||
|
||||
```bash
|
||||
# hermes-agent is a separate project (not part of this repo)
|
||||
cd hermes-agent && uv sync
|
||||
|
||||
# install the Iris plugin into the live hermes home
|
||||
mkdir -p ~/.hermes/plugins
|
||||
ln -s "$PWD/gateway-plugin" ~/.hermes/plugins/android
|
||||
hermes gateway status # should list "android"
|
||||
ln -s "$PWD/gateway-plugin" ~/.hermes/plugins/iris
|
||||
hermes gateway status # should list the Iris platform
|
||||
|
||||
hermes gateway setup # generates ANDROID_TOKEN, prints the server URL
|
||||
hermes gateway setup # generates IRIS_TOKEN, prints server URL + pairing QR
|
||||
hermes gateway # run the gateway
|
||||
```
|
||||
|
||||
(Otherwise see [Install the gateway](#install-the-gateway) above.)
|
||||
|
||||
### 2. Android app
|
||||
|
||||
```bash
|
||||
@@ -86,21 +134,22 @@ cd app
|
||||
|
||||
On the app's **Connect** screen:
|
||||
|
||||
1. **Server URL** — `ws://<gateway-ip>:8790/ws` (printed by `hermes gateway setup`).
|
||||
2. **Pairing token** — from the setup output, or `ANDROID_TOKEN` in `~/.hermes/.env`
|
||||
1. **Server URL** — `http://<gateway-ip>:8791` (printed by `hermes gateway setup`).
|
||||
2. **Pairing token** — from the setup output, or `IRIS_TOKEN` in `~/.hermes/.env`
|
||||
on the gateway host.
|
||||
3. **Test & Connect.**
|
||||
|
||||
Notes:
|
||||
|
||||
- The app has **no QR scanner** — pairing is manual URL + token entry.
|
||||
- The default bind is `127.0.0.1` (desktop on the same machine only). For a phone
|
||||
on the LAN, set `ANDROID_WS_HOST` to the gateway's LAN IP.
|
||||
- Remote access: Tailscale/WireGuard, or a reverse proxy with CA-signed WSS
|
||||
(`ANDROID_WS_CERT` / `ANDROID_WS_KEY`).
|
||||
- **Android** has a **Scan QR** button that reads the QR printed by
|
||||
`hermes gateway setup` and pre-fills URL + token; desktop uses manual entry.
|
||||
- The default bind is `127.0.0.1` (desktop on the same machine only). For a
|
||||
phone on the LAN, set `IRIS_HTTP_HOST` to the gateway's LAN IP.
|
||||
- Remote access: Tailscale/WireGuard, or a reverse proxy/tunnel with TLS
|
||||
(`IRIS_HTTP_CERT` / `IRIS_HTTP_KEY`).
|
||||
|
||||
Full walkthrough, push setup (FCM/ntfy), and troubleshooting:
|
||||
[`docs/setup.md`](docs/setup.md).
|
||||
Full walkthrough, push setup (ntfy/FCM), TLS, and troubleshooting:
|
||||
[`docs/install.md`](docs/install.md).
|
||||
|
||||
## Contributing
|
||||
|
||||
@@ -112,7 +161,7 @@ Contributions are welcome! Before you start:
|
||||
2. **Know the layout.**
|
||||
|
||||
| Path | What |
|
||||
|---|---|
|
||||
| --- | --- |
|
||||
| `gateway-plugin/` | Python hermes platform plugin (`android`); `protocol.py` is the frame source of truth |
|
||||
| `app/shared` | KMP module with most of the client code (shared by Android + Desktop) |
|
||||
| `app/androidApp` | Thin Android shell (package `dev.iris.app`) |
|
||||
@@ -123,8 +172,8 @@ Contributions are welcome! Before you start:
|
||||
- Python (gateway plugin): `cd hermes-agent && scripts/run_tests.sh tests/gateway/test_android.py`
|
||||
(never bare `pytest` — hermes's runner sandboxes `HERMES_HOME`).
|
||||
- Kotlin: `cd app && ./gradlew :shared:testDebugUnitTest`
|
||||
- Live check (gateway must be running): `gateway-plugin/tests/ws_probe.py` and
|
||||
`gateway-plugin/tests/e2e.py` — see [`gateway-plugin/tests/README.md`](gateway-plugin/tests/README.md).
|
||||
- Live check (gateway must be running): `tests/ws_probe.py` and
|
||||
`tests/e2e.py` — see [`tests/README.md`](tests/README.md).
|
||||
4. **Keep the protocol in sync.** `gateway-plugin/protocol.py`,
|
||||
`app/shared/.../protocol/Protocol.kt`, and `docs/protocol/frames.schema.json`
|
||||
must always agree.
|
||||
@@ -135,4 +184,4 @@ Open an issue first for anything big, then send a pull request.
|
||||
|
||||
## License
|
||||
|
||||
Apache License 2.0 — see [LICENSE](LICENSE).
|
||||
Apache License 2.0 — see [LICENSE](LICENSE).
|
||||
@@ -13,8 +13,19 @@ android {
|
||||
applicationId = "dev.iris.app"
|
||||
minSdk = 29
|
||||
targetSdk = 34
|
||||
versionCode = 1
|
||||
versionName = "0.1.0"
|
||||
// Play Store requires an incrementing versionCode per upload; CI can
|
||||
// pass -PappVersionCode=<n>. Local builds keep the default.
|
||||
versionCode = (project.findProperty("appVersionCode")?.toString()?.toIntOrNull()) ?: 1
|
||||
// The repo-root VERSION file is the single source of truth (bump it
|
||||
// to cut a release); CI can still override with -PappVersion.
|
||||
versionName =
|
||||
(project.findProperty("appVersion") as? String)
|
||||
?: project
|
||||
.file("../../VERSION")
|
||||
.takeIf { it.exists() }
|
||||
?.readText()
|
||||
?.trim()
|
||||
?: "0.1.0"
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
@@ -23,10 +34,39 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
// CI release signing: .gitea/workflows/release.yml restores a keystore
|
||||
// from Gitea secrets and exports ANDROID_KEYSTORE_* env vars (see
|
||||
// scripts/make_release_keystore.sh). Without them the release build stays
|
||||
// unsigned and the workflow falls back to a debug APK.
|
||||
val ciKeystore = System.getenv("ANDROID_KEYSTORE_FILE")
|
||||
if (ciKeystore != null) {
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
storeFile = file(ciKeystore)
|
||||
storePassword = System.getenv("ANDROID_KEYSTORE_PASSWORD")
|
||||
keyAlias = System.getenv("ANDROID_KEY_ALIAS")
|
||||
keyPassword = System.getenv("ANDROID_KEY_PASSWORD")
|
||||
}
|
||||
}
|
||||
buildTypes {
|
||||
release {
|
||||
signingConfig = signingConfigs.getByName("release")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
// targetSdk is deliberately pinned to 34 (a stable API level): the
|
||||
// reference device is API 29 and API 37 (the only newer installed
|
||||
// platform) is a preview SDK, which is not appropriate to target for a
|
||||
// stable build. Silence the informational OldTargetApi hint.
|
||||
lint {
|
||||
disable += "OldTargetApi"
|
||||
}
|
||||
}
|
||||
|
||||
kotlin {
|
||||
@@ -41,7 +81,7 @@ dependencies {
|
||||
implementation("androidx.compose.material3:material3")
|
||||
implementation("androidx.compose.ui:ui")
|
||||
implementation("androidx.activity:activity-compose:1.13.0")
|
||||
implementation("androidx.core:core-splashscreen:1.0.1")
|
||||
implementation("androidx.core:core-splashscreen:1.2.0")
|
||||
}
|
||||
|
||||
// M5: apply the google-services plugin only when a Firebase project is
|
||||
@@ -49,4 +89,4 @@ dependencies {
|
||||
// inert and the ntfy listener is the push path.
|
||||
if (file("google-services.json").exists()) {
|
||||
apply(plugin = "com.google.gms.google-services")
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,16 @@
|
||||
<!-- M5: ntfy listener foreground service (dataSync type on API 34). -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
<!-- QR pairing (docs/20): the in-app scanner reads the camera. -->
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-feature android:name="android.hardware.camera" android:required="false" />
|
||||
|
||||
<!-- M-3: cleartext (http://) is required because the gateway is a LAN host
|
||||
addressed by IP (e.g. 192.168.x.x), not a domain. Android's
|
||||
network_security_config can only scope cleartext to domain names, not
|
||||
IP ranges, so a per-host allowlist isn't possible for this use case.
|
||||
The token is still required for auth; traffic is only ever sent to the
|
||||
user-configured gateway on the local network. -->
|
||||
<application
|
||||
android:label="Iris"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
@@ -38,8 +47,22 @@
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="iris" android:host="chat" />
|
||||
</intent-filter>
|
||||
<!-- QR pairing (docs/20): iris://pair deep link (scanned QR / link). -->
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="iris" android:host="pair" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- QR pairing (docs/20): full-screen scanner launched from the
|
||||
Connect screen. Not exported; started only by our own app. -->
|
||||
<activity
|
||||
android:name="iris.platform.QrScanActivity"
|
||||
android:exported="false"
|
||||
android:screenOrientation="portrait" />
|
||||
|
||||
<!-- M4: serve cached media/documents to other apps (ACTION_VIEW). -->
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
|
||||
@@ -16,11 +16,16 @@ import iris.platform.AndroidEnv
|
||||
import iris.platform.AndroidSecureStore
|
||||
import iris.platform.AppBridge
|
||||
import iris.platform.syncNtfyListener
|
||||
import iris.util.PairLink
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
private val deepLinkChatId = mutableStateOf<String?>(null)
|
||||
private val deepLinkThreadId = mutableStateOf<String?>(null)
|
||||
|
||||
// QR pairing (docs/20): a parsed iris://pair link to prefill the Connect
|
||||
// screen with.
|
||||
private val pendingPair = mutableStateOf<PairLink?>(null)
|
||||
|
||||
private val notificationPermission =
|
||||
registerForActivityResult(ActivityResultContracts.RequestPermission()) { /* result ignored */ }
|
||||
|
||||
@@ -37,7 +42,13 @@ class MainActivity : ComponentActivity() {
|
||||
setContent {
|
||||
val chatId by deepLinkChatId
|
||||
val threadId by deepLinkThreadId
|
||||
IrisApp(store = store, deepLinkChatId = chatId, deepLinkThreadId = threadId)
|
||||
val pair by pendingPair
|
||||
IrisApp(
|
||||
store = store,
|
||||
deepLinkChatId = chatId,
|
||||
deepLinkThreadId = threadId,
|
||||
deepLinkPair = pair,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,6 +60,10 @@ class MainActivity : ComponentActivity() {
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
AppBridge.foreground = true
|
||||
// Wake the connect loop's backoff: after a background stint the
|
||||
// network is usually back, so re-probe immediately instead of making
|
||||
// the user wait out the (up to 30 s) backoff with a Connecting banner.
|
||||
AppBridge.controller?.client?.poke()
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
@@ -60,6 +75,14 @@ class MainActivity : ComponentActivity() {
|
||||
* extras or an iris://chat/<id>?thread=<tid> URI). */
|
||||
private fun handleDeepLink(intent: Intent?) {
|
||||
val data = intent?.data
|
||||
// QR pairing (docs/20): iris://pair?host=…&port=…&secure=…&token=… —
|
||||
// the whole payload is in the query string; parse it with the shared
|
||||
// PairLink parser.
|
||||
if (data?.scheme == "iris" && data.host == "pair") {
|
||||
val link = PairLink.parse(data.toString())
|
||||
if (link != null) pendingPair.value = link
|
||||
return
|
||||
}
|
||||
val chatId =
|
||||
intent?.getStringExtra("chat_id")
|
||||
?: data?.pathSegments?.firstOrNull()
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
@@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
+1
-1
@@ -3,4 +3,4 @@
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
<monochrome android:drawable="@drawable/ic_launcher_monochrome" />
|
||||
</adaptive-icon>
|
||||
</adaptive-icon>
|
||||
+1
-1
@@ -3,4 +3,4 @@
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
<monochrome android:drawable="@drawable/ic_launcher_monochrome" />
|
||||
</adaptive-icon>
|
||||
</adaptive-icon>
|
||||
@@ -19,6 +19,8 @@ plugins {
|
||||
id("com.android.kotlin.multiplatform.library") version "9.3.1" apply false
|
||||
id("org.jetbrains.compose") version "1.11.1" apply false
|
||||
id("org.jetbrains.kotlin.plugin.compose") version "2.4.10" apply false
|
||||
// Local cache DB (docs/16: "Local DB (KMP) — SQLDelight").
|
||||
id("app.cash.sqldelight") version "2.3.2" apply false
|
||||
}
|
||||
|
||||
tasks.register("clean") {
|
||||
|
||||
@@ -9,11 +9,23 @@ plugins {
|
||||
val composeVersion = "1.11.1"
|
||||
val os = OperatingSystem.current()
|
||||
val arch = System.getProperty("os.arch") ?: "amd64"
|
||||
val desktopTarget = when {
|
||||
os.isMacOsX -> if (arch == "aarch64") "macos-arm64" else "macos-x64"
|
||||
os.isWindows -> "windows-x64"
|
||||
else -> if (arch == "aarch64") "linux-arm64" else "linux-x64"
|
||||
}
|
||||
// The repo-root VERSION file is the single source of truth (bump it to cut
|
||||
// a release); CI can still override with -PappVersion. jpackage requires a
|
||||
// plain semver (no leading "v").
|
||||
val appVersion =
|
||||
(project.findProperty("appVersion") as? String)
|
||||
?: project
|
||||
.file("../../VERSION")
|
||||
.takeIf { it.exists() }
|
||||
?.readText()
|
||||
?.trim()
|
||||
?: "0.1.0"
|
||||
val desktopTarget =
|
||||
when {
|
||||
os.isMacOsX -> if (arch == "aarch64") "macos-arm64" else "macos-x64"
|
||||
os.isWindows -> "windows-x64"
|
||||
else -> if (arch == "aarch64") "linux-arm64" else "linux-x64"
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":shared"))
|
||||
@@ -45,19 +57,21 @@ afterEvaluate {
|
||||
|
||||
val jpackageInputDir = layout.buildDirectory.dir("jpackage-input")
|
||||
|
||||
val fatJar = tasks.register<Jar>("fatJar") {
|
||||
archiveClassifier.set("all")
|
||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||
manifest { attributes("Main-Class" to "iris.desktop.MainKt") }
|
||||
from(sourceSets.main.get().output)
|
||||
from({
|
||||
configurations.runtimeClasspath.get()
|
||||
.filter { it.name.endsWith(".jar") }
|
||||
.map { zipTree(it) }
|
||||
}) {
|
||||
exclude("META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA")
|
||||
val fatJar =
|
||||
tasks.register<Jar>("fatJar") {
|
||||
archiveClassifier.set("all")
|
||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||
manifest { attributes("Main-Class" to "iris.desktop.MainKt") }
|
||||
from(sourceSets.main.get().output)
|
||||
from({
|
||||
configurations.runtimeClasspath
|
||||
.get()
|
||||
.filter { it.name.endsWith(".jar") }
|
||||
.map { zipTree(it) }
|
||||
}) {
|
||||
exclude("META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Stage the fat jar into the jpackage input dir. A dedicated Sync task keeps
|
||||
// the Exec task free of task references (configuration-cache compatible) and
|
||||
@@ -73,23 +87,39 @@ tasks.register<Exec>("jpackage") {
|
||||
val jpackageBin = file("${System.getProperty("java.home")}/bin/jpackage")
|
||||
val type = (project.findProperty("jpackageType") as? String) ?: "app-image"
|
||||
val inputDir = jpackageInputDir.get().asFile
|
||||
val destDir = layout.buildDirectory.dir("jpackage").get().asFile
|
||||
val destDir =
|
||||
layout.buildDirectory
|
||||
.dir("jpackage")
|
||||
.get()
|
||||
.asFile
|
||||
inputs.dir(inputDir)
|
||||
outputs.dir(destDir)
|
||||
commandLine(
|
||||
if (jpackageBin.exists()) jpackageBin.absolutePath else "jpackage",
|
||||
"--name", "iris",
|
||||
"--app-version", "0.1.0",
|
||||
"--vendor", "Iris",
|
||||
"--type", type,
|
||||
"--input", inputDir.absolutePath,
|
||||
"--main-jar", "desktopApp-all.jar",
|
||||
"--main-class", "iris.desktop.MainKt",
|
||||
"--icon", file("src/main/resources/icon.png").absolutePath,
|
||||
"--dest", destDir.absolutePath,
|
||||
"--java-options", "-Xmx1g",
|
||||
"--name",
|
||||
"iris",
|
||||
"--app-version",
|
||||
appVersion,
|
||||
"--vendor",
|
||||
"Iris",
|
||||
"--type",
|
||||
type,
|
||||
"--input",
|
||||
inputDir.absolutePath,
|
||||
"--main-jar",
|
||||
"desktopApp-all.jar",
|
||||
"--main-class",
|
||||
"iris.desktop.MainKt",
|
||||
"--icon",
|
||||
file("src/main/resources/icon.png").absolutePath,
|
||||
"--dest",
|
||||
destDir.absolutePath,
|
||||
"--java-options",
|
||||
"-Xmx1g",
|
||||
// M9: KCEF (JCEF) AWT reflection access (see the JavaExec block above).
|
||||
"--java-options", "--add-opens=java.desktop/sun.awt=ALL-UNNAMED",
|
||||
"--java-options", "--add-opens=java.desktop/java.awt.peer=ALL-UNNAMED",
|
||||
"--java-options",
|
||||
"--add-opens=java.desktop/sun.awt=ALL-UNNAMED",
|
||||
"--java-options",
|
||||
"--add-opens=java.desktop/java.awt.peer=ALL-UNNAMED",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -19,9 +19,12 @@ import iris.IrisApp
|
||||
import iris.net.GatewayClient
|
||||
import iris.platform.DesktopBridge
|
||||
import iris.platform.DesktopSecureStore
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import java.awt.Color
|
||||
import java.awt.Graphics2D
|
||||
import javax.imageio.ImageIO
|
||||
import java.awt.RenderingHints
|
||||
import java.awt.SystemTray
|
||||
import java.awt.event.WindowEvent
|
||||
@@ -29,10 +32,7 @@ import java.awt.event.WindowFocusListener
|
||||
import java.awt.image.BufferedImage
|
||||
import java.io.File
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import javax.imageio.ImageIO
|
||||
|
||||
/**
|
||||
* M6: desktop shell (docs/11 §11.2/§11.3).
|
||||
@@ -48,6 +48,7 @@ private val windowJson = File(System.getProperty("user.home"), ".iris/window.jso
|
||||
|
||||
// Window/taskbar icon (src/main/resources/icon.png).
|
||||
private class IrisDesktop
|
||||
|
||||
private val windowIcon = ImageIO.read(IrisDesktop::class.java.getResource("/icon.png")!!).toComposeImageBitmap()
|
||||
|
||||
// Tray icon colors (ARGB). .toInt(): the literals exceed the Int range.
|
||||
@@ -87,15 +88,37 @@ fun main() {
|
||||
LaunchedEffect(Unit) {
|
||||
while (true) {
|
||||
delay(2_000)
|
||||
val state = DesktopBridge.controller?.client?.state?.value
|
||||
val (color, tooltip) = when (state) {
|
||||
null,
|
||||
is GatewayClient.State.Disconnected -> TRAY_OFFLINE to "Iris — offline"
|
||||
is GatewayClient.State.Connecting,
|
||||
is GatewayClient.State.Reconnecting -> TRAY_CONNECTING to "Iris — connecting…"
|
||||
is GatewayClient.State.Connected -> TRAY_CONNECTED to "Iris — connected"
|
||||
is GatewayClient.State.AuthFailed -> TRAY_AUTH_FAILED to "Iris — auth failed"
|
||||
}
|
||||
val state =
|
||||
DesktopBridge.controller
|
||||
?.client
|
||||
?.state
|
||||
?.value
|
||||
val (color, tooltip) =
|
||||
when (state) {
|
||||
null,
|
||||
is GatewayClient.State.Disconnected,
|
||||
-> {
|
||||
TRAY_OFFLINE to "Iris — offline"
|
||||
}
|
||||
|
||||
is GatewayClient.State.Connecting,
|
||||
is GatewayClient.State.Reconnecting,
|
||||
-> {
|
||||
TRAY_CONNECTING to "Iris — connecting…"
|
||||
}
|
||||
|
||||
is GatewayClient.State.Connected -> {
|
||||
TRAY_CONNECTED to "Iris — connected"
|
||||
}
|
||||
|
||||
is GatewayClient.State.AuthFailed -> {
|
||||
TRAY_AUTH_FAILED to "Iris — auth failed"
|
||||
}
|
||||
|
||||
is GatewayClient.State.TlsConfirmRequired -> {
|
||||
TRAY_AUTH_FAILED to "Iris — gateway certificate needs confirmation"
|
||||
}
|
||||
}
|
||||
trayColor = color
|
||||
trayTooltip = tooltip
|
||||
}
|
||||
@@ -126,15 +149,17 @@ fun main() {
|
||||
state = loadWindowState(),
|
||||
) {
|
||||
composeWindow = window
|
||||
window.addWindowFocusListener(object : WindowFocusListener {
|
||||
override fun windowGainedFocus(e: WindowEvent) {
|
||||
DesktopBridge.foreground = true
|
||||
}
|
||||
window.addWindowFocusListener(
|
||||
object : WindowFocusListener {
|
||||
override fun windowGainedFocus(e: WindowEvent) {
|
||||
DesktopBridge.foreground = true
|
||||
}
|
||||
|
||||
override fun windowLostFocus(e: WindowEvent) {
|
||||
DesktopBridge.foreground = false
|
||||
}
|
||||
})
|
||||
override fun windowLostFocus(e: WindowEvent) {
|
||||
DesktopBridge.foreground = false
|
||||
}
|
||||
},
|
||||
)
|
||||
IrisApp(store)
|
||||
}
|
||||
}
|
||||
@@ -187,4 +212,4 @@ private fun saveWindowState(window: ComposeWindow?) {
|
||||
)
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,13 @@
|
||||
org.gradle.jvmargs=-Xmx4g -Dfile.encoding=UTF-8
|
||||
# Desktop targets the Java 21 runtime (Markdown renderer 0.44.0 is
|
||||
# Java-21 bytecode). AGP is JDK-21-compatible, so the Android build is
|
||||
# unaffected (its bytecode target stays JVM 17 via minSdk/jvmTarget).
|
||||
#
|
||||
# The JDK-21 home is machine-specific, so it is NOT hardcoded here (a
|
||||
# committed path would break every other checkout). Set it per machine via
|
||||
# one of:
|
||||
# - ~/.gradle/gradle.properties -> org.gradle.java.home=/path/to/jdk21
|
||||
# - or export JAVA_HOME=/path/to/jdk21 before running ./gradlew
|
||||
org.gradle.caching=true
|
||||
org.gradle.configuration-cache=true
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@ plugins {
|
||||
id("com.android.kotlin.multiplatform.library")
|
||||
id("org.jetbrains.compose")
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
// Local cache DB (docs/16: "Local DB (KMP) — SQLDelight").
|
||||
id("app.cash.sqldelight")
|
||||
}
|
||||
|
||||
val composeVersion = "1.11.1"
|
||||
@@ -25,6 +27,53 @@ val kcefVersion = "2025.03.23"
|
||||
// release). Provides GFM tables, bold/italic/underscore, and the -code module
|
||||
// for language-aware syntax highlighting (Highlights).
|
||||
val markdownVersion = "0.44.0"
|
||||
// Local cache DB (messages/channels/meta; docs/10 §10.7, docs/16).
|
||||
val sqldelightVersion = "2.3.2"
|
||||
// CameraX + ML Kit for in-app QR pairing (docs/20). Android-only.
|
||||
val cameraxVersion = "1.5.1"
|
||||
val mlKitVersion = "16.1.1"
|
||||
|
||||
// ── App version (generated) ─────────────────────────────────────────────
|
||||
// The repo-root VERSION file is the single source of truth (bump it to cut
|
||||
// a release; CI can still override with -PappVersion). Generate AppVersion.kt
|
||||
// into commonMain so both targets can display it in Settings and send it to
|
||||
// the gateway (X-Iris-App-Version header).
|
||||
//
|
||||
// A real task with the VERSION file as a DECLARED input: on a
|
||||
// configuration-cache hit the script body does not re-run, so only the task
|
||||
// (keyed on the file's content) can regenerate AppVersion.kt after a bump.
|
||||
// The doLast reads everything from the task's own inputs/outputs (which are
|
||||
// configuration-cache serializable) — it must not reference script-scope
|
||||
// vals, because a .kts script lambda captures the script object and the
|
||||
// configuration cache rejects that.
|
||||
val generatedVersionDir = layout.buildDirectory.dir("generated/app-version")
|
||||
val generateAppVersion by tasks.registering {
|
||||
inputs.file(project.file("../../VERSION"))
|
||||
inputs.property("appVersionOverride", (project.findProperty("appVersion") as? String).orEmpty())
|
||||
val outFile = generatedVersionDir.map { it.file("AppVersion.kt") }
|
||||
outputs.file(outFile)
|
||||
doLast {
|
||||
val override = inputs.properties["appVersionOverride"] as? String ?: ""
|
||||
val versionFile = inputs.files.singleFile
|
||||
val version =
|
||||
override.ifBlank {
|
||||
versionFile.takeIf { it.exists() }?.readText()?.trim() ?: "0.1.0"
|
||||
}
|
||||
val f = outFile.get().asFile
|
||||
f.parentFile?.mkdirs()
|
||||
f.writeText(
|
||||
"""
|
||||
|package iris
|
||||
|
|
||||
|/** Generated from the repo-root VERSION file - do not edit. */
|
||||
|object AppVersion {
|
||||
| const val VERSION = "$version"
|
||||
|}
|
||||
|
|
||||
""".trimMargin(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
kotlin {
|
||||
android {
|
||||
@@ -36,14 +85,31 @@ kotlin {
|
||||
}
|
||||
withHostTest { }
|
||||
}
|
||||
jvm("desktop")
|
||||
jvm("desktop") {
|
||||
// Desktop runs on the Java 21 runtime (see gradle.properties
|
||||
// org.gradle.java.home); target 21 so the Markdown renderer 0.44.0
|
||||
// (Java-21 bytecode) loads. Android keeps its JVM 17 target above.
|
||||
compilerOptions {
|
||||
jvmTarget.set(JvmTarget.JVM_21)
|
||||
}
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
// AppVersion.kt is generated from the repo-root VERSION file (see
|
||||
// generateAppVersion above) into commonMain so both targets can read it.
|
||||
commonMain {
|
||||
kotlin.srcDir(generatedVersionDir)
|
||||
}
|
||||
// Both targets are JVM-based (androidTarget + jvm("desktop")), so
|
||||
// shared JVM code (File I/O, SHA-256, media cache) lives in jvmMain.
|
||||
val jvmMain by creating { dependsOn(commonMain.get()) }
|
||||
val androidMain by getting { dependsOn(jvmMain) }
|
||||
val desktopMain by getting { dependsOn(jvmMain) }
|
||||
// Host tests shared by the android (withHostTest) and desktop targets
|
||||
// (e.g. the SQLDelight cache DB tests, which need the JDBC driver).
|
||||
val jvmTest by creating { dependsOn(commonTest.get()) }
|
||||
val androidHostTest by getting { dependsOn(jvmTest) }
|
||||
val desktopTest by getting { dependsOn(jvmTest) }
|
||||
|
||||
commonMain.dependencies {
|
||||
implementation("org.jetbrains.compose.runtime:runtime:$composeVersion")
|
||||
@@ -67,15 +133,24 @@ kotlin {
|
||||
// M9: HTML artifact previews — WebView composable (platform WebView
|
||||
// on Android, KCEF/JCEF on desktop).
|
||||
implementation("io.github.kevinnzou:compose-webview-multiplatform:$webviewVersion")
|
||||
// Local cache DB runtime (generated code from commonMain/sqldelight).
|
||||
implementation("app.cash.sqldelight:runtime:$sqldelightVersion")
|
||||
}
|
||||
commonTest.dependencies {
|
||||
implementation(kotlin("test"))
|
||||
}
|
||||
jvmTest.dependencies {
|
||||
implementation(kotlin("test"))
|
||||
// JDBC SQLite driver: in-memory DB for the cache tests.
|
||||
implementation("app.cash.sqldelight:sqlite-driver:$sqldelightVersion")
|
||||
}
|
||||
// M9: KCEF (JCEF/Chromium) for desktop HTML artifact previews. The
|
||||
// webview library exposes it transitively, but we reference KCEF
|
||||
// directly (init + progress) so declare it explicitly.
|
||||
desktopMain.dependencies {
|
||||
implementation("dev.datlag:kcef:$kcefVersion")
|
||||
// Local cache DB: JDBC SQLite driver (file in ~/.iris).
|
||||
implementation("app.cash.sqldelight:sqlite-driver:$sqldelightVersion")
|
||||
}
|
||||
// M4: ExoPlayer (Media3) for inline audio/video playback (Android only).
|
||||
androidMain.dependencies {
|
||||
@@ -86,10 +161,32 @@ kotlin {
|
||||
implementation("androidx.media3:media3-ui:1.11.0")
|
||||
// SAF picker (rememberLauncherForActivityResult).
|
||||
implementation("androidx.activity:activity-compose:1.13.0")
|
||||
// CameraX + ML Kit for QR pairing (docs/20): the scanner activity
|
||||
// uses the camera2 CameraX backend and ML Kit's barcode model.
|
||||
implementation("androidx.camera:camera-core:$cameraxVersion")
|
||||
implementation("androidx.camera:camera-camera2:$cameraxVersion")
|
||||
implementation("androidx.camera:camera-lifecycle:$cameraxVersion")
|
||||
implementation("androidx.camera:camera-view:$cameraxVersion")
|
||||
implementation("com.google.mlkit:barcode-scanning:$mlKitVersion")
|
||||
// M5: FCM push (inert without a Firebase project / google-services.json;
|
||||
// the ntfy listener is the fallback). The google-services plugin is
|
||||
// applied conditionally in the app module.
|
||||
implementation("com.google.firebase:firebase-messaging:25.1.2")
|
||||
// Local cache DB: Android SQLite driver (app database dir).
|
||||
implementation("app.cash.sqldelight:android-driver:$sqldelightVersion")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sqldelight {
|
||||
databases {
|
||||
create("IrisDatabase") {
|
||||
packageName.set("iris.db")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Every Kotlin compile depends on the generated AppVersion.kt being current.
|
||||
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
|
||||
dependsOn(generateAppVersion)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package iris.platform
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import androidx.core.content.ContextCompat
|
||||
@@ -15,7 +16,9 @@ actual fun setActiveController(controller: Any?) {
|
||||
actual fun syncNtfyListener(backend: String) {
|
||||
val context = AndroidEnv.context
|
||||
val intent = Intent(context, NtfyListenerService::class.java)
|
||||
val store = AndroidSecureStore(context)
|
||||
// L-18: reuse one AndroidSecureStore instead of rebuilding it (and
|
||||
// re-running EncryptedSharedPreferences.create + migration) on every call.
|
||||
val store = ntfyStore(context)
|
||||
if (backend == "ntfy" && store.ntfyTopic.isNotBlank()) {
|
||||
ContextCompat.startForegroundService(context, intent)
|
||||
} else {
|
||||
@@ -25,6 +28,18 @@ actual fun syncNtfyListener(backend: String) {
|
||||
}
|
||||
}
|
||||
|
||||
private val ntfyStoreLock = Any()
|
||||
|
||||
@Volatile
|
||||
private var cachedNtfyStore: AndroidSecureStore? = null
|
||||
|
||||
private fun ntfyStore(context: Context): AndroidSecureStore {
|
||||
cachedNtfyStore?.let { return it }
|
||||
return synchronized(ntfyStoreLock) {
|
||||
cachedNtfyStore ?: AndroidSecureStore(context).also { cachedNtfyStore = it }
|
||||
}
|
||||
}
|
||||
|
||||
actual fun postSystemNotification(
|
||||
chatId: String?,
|
||||
chatName: String?,
|
||||
@@ -33,7 +48,7 @@ actual fun postSystemNotification(
|
||||
threadId: String?,
|
||||
) {
|
||||
val context = AndroidEnv.context
|
||||
val id = chatId ?: "android:default"
|
||||
val id = chatId ?: "default"
|
||||
// POST_NOTIFICATIONS is a runtime permission on API 33+.
|
||||
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS)
|
||||
!= PackageManager.PERMISSION_GRANTED
|
||||
|
||||
@@ -9,6 +9,7 @@ import iris.data.SecureStore
|
||||
import iris.ui.theme.Backdrop
|
||||
import iris.ui.theme.BackgroundMode
|
||||
import iris.ui.theme.UserTheme
|
||||
import iris.util.STREAM_SMOOTHNESS_DEFAULT
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
@@ -76,6 +77,14 @@ class AndroidSecureStore(
|
||||
get() = prefs.getString(KEY_TOKEN, "").orEmpty()
|
||||
set(value) = prefs.edit().putString(KEY_TOKEN, value.trim()).apply()
|
||||
|
||||
override var deviceToken: String
|
||||
get() = prefs.getString(KEY_DEVICE_TOKEN, "").orEmpty()
|
||||
set(value) = prefs.edit().putString(KEY_DEVICE_TOKEN, value.trim()).apply()
|
||||
|
||||
override var pinnedCertFingerprint: String
|
||||
get() = prefs.getString(KEY_PINNED_CERT, "").orEmpty()
|
||||
set(value) = prefs.edit().putString(KEY_PINNED_CERT, value.trim()).apply()
|
||||
|
||||
override val deviceId: String
|
||||
get() {
|
||||
var id = prefs.getString(KEY_DEVICE_ID, null)
|
||||
@@ -126,6 +135,10 @@ class AndroidSecureStore(
|
||||
get() = prefs.getBoolean(KEY_STREAMING_ENABLED, true)
|
||||
set(value) = prefs.edit().putBoolean(KEY_STREAMING_ENABLED, value).apply()
|
||||
|
||||
override var streamSmoothness: Float
|
||||
get() = prefs.getFloat(KEY_STREAM_SMOOTHNESS, STREAM_SMOOTHNESS_DEFAULT)
|
||||
set(value) = prefs.edit().putFloat(KEY_STREAM_SMOOTHNESS, value).apply()
|
||||
|
||||
override var reasoningAutoCollapse: Boolean
|
||||
get() = prefs.getBoolean(KEY_REASONING_AUTO_COLLAPSE, true)
|
||||
set(value) = prefs.edit().putBoolean(KEY_REASONING_AUTO_COLLAPSE, value).apply()
|
||||
@@ -162,19 +175,42 @@ class AndroidSecureStore(
|
||||
get() = prefs.getFloat(KEY_FONT_SIZE_SCALE, 1.0f)
|
||||
set(value) = prefs.edit().putFloat(KEY_FONT_SIZE_SCALE, value).apply()
|
||||
|
||||
override var runtimeFooterEnabled: Boolean
|
||||
get() = prefs.getBoolean(KEY_RUNTIME_FOOTER_ENABLED, false)
|
||||
set(value) = prefs.edit().putBoolean(KEY_RUNTIME_FOOTER_ENABLED, value).apply()
|
||||
|
||||
override var runtimeFooterFields: String
|
||||
get() = prefs.getString(KEY_RUNTIME_FOOTER_FIELDS, "").orEmpty()
|
||||
set(value) = prefs.edit().putString(KEY_RUNTIME_FOOTER_FIELDS, value).apply()
|
||||
|
||||
override fun savePairing(
|
||||
url: String,
|
||||
token: String,
|
||||
) {
|
||||
serverUrl = url
|
||||
this.token = token
|
||||
// A (re-)pair may target a different gateway: the old per-device
|
||||
// token is dead there. The next hello.ack re-mints/returns it.
|
||||
deviceToken = ""
|
||||
}
|
||||
|
||||
override fun clear() {
|
||||
// M-10: clearing pairing must also wipe the device identity + push
|
||||
// state, otherwise a re-pair to a different gateway would keep the old
|
||||
// deviceId/syncCursor/ntfyTopic and the server would treat the new
|
||||
// pairing as the same device.
|
||||
prefs
|
||||
.edit()
|
||||
.remove(KEY_URL)
|
||||
.remove(KEY_TOKEN)
|
||||
.remove(KEY_DEVICE_TOKEN)
|
||||
.remove(KEY_DEVICE_ID)
|
||||
.remove(KEY_SYNC_CURSOR)
|
||||
.remove(KEY_FCM_TOKEN)
|
||||
.remove(KEY_NTFY_TOPIC)
|
||||
.remove(KEY_NTFY_SERVER)
|
||||
.remove(KEY_PUSH_BACKEND)
|
||||
.remove(KEY_PINNED_CERT)
|
||||
.apply()
|
||||
}
|
||||
|
||||
@@ -183,15 +219,18 @@ class AndroidSecureStore(
|
||||
const val SECURE_PREFS_NAME = "iris_secure"
|
||||
const val KEY_URL = "server_url"
|
||||
const val KEY_TOKEN = "token"
|
||||
const val KEY_DEVICE_TOKEN = "device_token"
|
||||
const val KEY_DEVICE_ID = "device_id"
|
||||
const val KEY_SYNC_CURSOR = "sync_cursor"
|
||||
const val KEY_FCM_TOKEN = "fcm_token"
|
||||
const val KEY_NTFY_TOPIC = "ntfy_topic"
|
||||
const val KEY_NTFY_SERVER = "ntfy_server"
|
||||
const val KEY_PUSH_BACKEND = "push_backend"
|
||||
const val KEY_PINNED_CERT = "pinned_cert_fingerprint"
|
||||
const val KEY_THREADS_ENABLED = "threads_enabled"
|
||||
const val KEY_TOOL_DETAIL = "tool_detail"
|
||||
const val KEY_STREAMING_ENABLED = "streaming_enabled"
|
||||
const val KEY_STREAM_SMOOTHNESS = "stream_smoothness"
|
||||
const val KEY_REASONING_AUTO_COLLAPSE = "reasoning_auto_collapse"
|
||||
const val KEY_USER_BUBBLE_COLOR = "user_bubble_color"
|
||||
const val KEY_AGENT_BUBBLE_COLOR = "agent_bubble_color"
|
||||
@@ -199,5 +238,7 @@ class AndroidSecureStore(
|
||||
const val KEY_BACKGROUND_COLOR = "background_color"
|
||||
const val KEY_BACKGROUND_IMAGE_PATH = "background_image_path"
|
||||
const val KEY_FONT_SIZE_SCALE = "font_size_scale"
|
||||
const val KEY_RUNTIME_FOOTER_ENABLED = "runtime_footer_enabled"
|
||||
const val KEY_RUNTIME_FOOTER_FIELDS = "runtime_footer_fields"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package iris.platform
|
||||
|
||||
import app.cash.sqldelight.db.SqlDriver
|
||||
import app.cash.sqldelight.driver.android.AndroidSqliteDriver
|
||||
import iris.db.IrisDatabase
|
||||
|
||||
actual fun appDataDir(): String = AndroidEnv.context.filesDir.absolutePath
|
||||
|
||||
// The schema-aware driver creates the schema on first run and applies
|
||||
// pending .sqm migrations on existing DBs (e.g. v1 -> v2: the `tool`
|
||||
// table), stamping PRAGMA user_version along the way.
|
||||
actual fun createCacheDriver(): SqlDriver = AndroidSqliteDriver(IrisDatabase.Schema, AndroidEnv.context, "iris_cache.db")
|
||||
@@ -22,7 +22,10 @@ import com.multiplatform.webview.web.rememberWebViewStateWithHTMLData
|
||||
private const val ARTIFACT_BASE_URL = "https://iris-artifact.local/"
|
||||
|
||||
@Composable
|
||||
actual fun PlatformWebView(html: String, modifier: Modifier) {
|
||||
actual fun PlatformWebView(
|
||||
html: String,
|
||||
modifier: Modifier,
|
||||
) {
|
||||
val state = rememberWebViewStateWithHTMLData(data = html, baseUrl = ARTIFACT_BASE_URL)
|
||||
state.webSettings.androidWebSettings.domStorageEnabled = true
|
||||
WebView(state, modifier = modifier)
|
||||
@@ -33,16 +36,18 @@ actual fun Modifier.handleSystemBack(onBack: () -> Unit): Modifier {
|
||||
val dispatcher = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher
|
||||
val currentOnBack = rememberUpdatedState(onBack)
|
||||
DisposableEffect(dispatcher) {
|
||||
if (dispatcher != null) {
|
||||
val callback = object : OnBackPressedCallback(true) {
|
||||
override fun handleOnBackPressed() {
|
||||
currentOnBack.value()
|
||||
}
|
||||
val callback =
|
||||
dispatcher?.let { d ->
|
||||
val c =
|
||||
object : OnBackPressedCallback(true) {
|
||||
override fun handleOnBackPressed() {
|
||||
currentOnBack.value()
|
||||
}
|
||||
}
|
||||
d.addCallback(c)
|
||||
c
|
||||
}
|
||||
dispatcher.addCallback(callback)
|
||||
onDispose { callback.remove() }
|
||||
}
|
||||
onDispose { }
|
||||
onDispose { callback?.remove() }
|
||||
}
|
||||
return this
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,14 @@ object AppBridge {
|
||||
@Volatile
|
||||
var controller: IrisController? = null
|
||||
|
||||
/** True while the launcher activity is resumed (set by MainActivity). */
|
||||
/** True while the launcher activity is resumed (set by MainActivity).
|
||||
* A change is forwarded to the controller (M8: unread clear on focus). */
|
||||
@Volatile
|
||||
var foreground: Boolean = false
|
||||
}
|
||||
set(value) {
|
||||
if (field != value) {
|
||||
field = value
|
||||
controller?.setForeground(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,32 +11,41 @@ import iris.net.GatewayClient
|
||||
*
|
||||
* - [onNewToken]: persist the rotated token and push it to the server via
|
||||
* `fcm.register` (so the next push targets the current token).
|
||||
* - [onMessageReceived]: the data payload drives a silent sync. When the app
|
||||
* is foregrounded the WS path already delivered the frame (in-app banner),
|
||||
* so we only post a system notification when backgrounded.
|
||||
* - [onMessageReceived]: posts a system notification from the data payload.
|
||||
* When the app is foregrounded the SSE path already delivered the frame
|
||||
* (in-app banner), so we only post a notification when backgrounded.
|
||||
*
|
||||
* Inert without a Firebase project (no google-services.json): the service is
|
||||
* declared in the manifest but never receives messages, and the app falls
|
||||
* back to the ntfy listener.
|
||||
*/
|
||||
class IrisFirebaseMessagingService : FirebaseMessagingService() {
|
||||
|
||||
override fun onNewToken(token: String) {
|
||||
val store = AndroidSecureStore(applicationContext)
|
||||
store.fcmToken = token
|
||||
// Push the rotation to the server if we're connected.
|
||||
// Push the rotation to the server if we're connected (the ntfy topic
|
||||
// rides along so a wiped registry recovers both push tokens).
|
||||
AppBridge.controller?.client?.sendFrame(
|
||||
iris.protocol.fcmRegisterFrame(fcmToken = token),
|
||||
iris.protocol.fcmRegisterFrame(
|
||||
fcmToken = token,
|
||||
ntfyTopic = store.ntfyTopic.ifBlank { null },
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
override fun onMessageReceived(message: RemoteMessage) {
|
||||
// Foreground + live WS: the in-app banner already showed this.
|
||||
// Foreground + live SSE: the in-app banner already showed this.
|
||||
if (AppBridge.foreground) return
|
||||
// Live WS: the frame arrives over the socket and the controller
|
||||
// Live SSE: the frame arrives over the stream and the controller
|
||||
// mirrors it to a system notification itself — posting here would
|
||||
// duplicate it (docs/08 §8.7).
|
||||
if (AppBridge.controller?.client?.state?.value is GatewayClient.State.Connected) return
|
||||
if (AppBridge.controller
|
||||
?.client
|
||||
?.state
|
||||
?.value is GatewayClient.State.Connected
|
||||
) {
|
||||
return
|
||||
}
|
||||
// Backgrounded/killed: FCM already displayed the `notification`
|
||||
// payload on our behalf (the data payload only carries sync
|
||||
// metadata). Posting again would show a second notification with a
|
||||
@@ -44,7 +53,7 @@ class IrisFirebaseMessagingService : FirebaseMessagingService() {
|
||||
// exception: the app must display them itself.
|
||||
if (message.notification != null) return
|
||||
val data = message.data
|
||||
val chatId = data["chat_id"] ?: "android:default"
|
||||
val chatId = data["chat_id"] ?: "default"
|
||||
val threadId = data["thread_id"]
|
||||
val title = data["title"] ?: "Iris"
|
||||
val body = data["body"] ?: data["title"].orEmpty()
|
||||
@@ -55,4 +64,4 @@ class IrisFirebaseMessagingService : FirebaseMessagingService() {
|
||||
}
|
||||
IrisNotifications.post(applicationContext, chatId, null, title, body, threadId)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import androidx.core.app.NotificationCompat
|
||||
|
||||
/**
|
||||
@@ -21,15 +20,22 @@ object IrisNotifications {
|
||||
const val ACTION_OPEN_CHAT = "dev.iris.app.OPEN_CHAT"
|
||||
private const val NOTIF_ID_BASE = 1_000_000
|
||||
|
||||
fun ensureChannel(context: Context, chatId: String, chatName: String? = null) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
||||
// L-31: notification channel ids are capped at 64 chars (Android limit) and
|
||||
// are user-visible, so a long server-provided chatId must be truncated.
|
||||
private fun channelIdFor(chatId: String): String = (CHANNEL_PREFIX + chatId).take(64)
|
||||
|
||||
fun ensureChannel(
|
||||
context: Context,
|
||||
chatId: String,
|
||||
chatName: String? = null,
|
||||
) {
|
||||
val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
val id = CHANNEL_PREFIX + chatId
|
||||
val id = channelIdFor(chatId)
|
||||
val name = chatName ?: chatId
|
||||
if (nm.getNotificationChannel(id) == null) {
|
||||
nm.createNotificationChannel(
|
||||
NotificationChannel(id, name, NotificationManager.IMPORTANCE_DEFAULT)
|
||||
.apply { description = "Iris messages for $name" }
|
||||
.apply { description = "Iris messages for $name" },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -43,23 +49,28 @@ object IrisNotifications {
|
||||
threadId: String?,
|
||||
) {
|
||||
ensureChannel(context, chatId, chatName)
|
||||
val id = NOTIF_ID_BASE + (chatId.hashCode() and 0xffff)
|
||||
val intent = Intent(ACTION_OPEN_CHAT).apply {
|
||||
setPackage(context.packageName)
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
putExtra("chat_id", chatId)
|
||||
if (threadId != null) putExtra("thread_id", threadId)
|
||||
}
|
||||
val pi = PendingIntent.getActivity(
|
||||
context,
|
||||
id,
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
// L-32: 24-bit hash (was 16-bit) to reduce the chance two chatIds map
|
||||
// to the same notification id and clobber each other.
|
||||
val id = NOTIF_ID_BASE + (chatId.hashCode() and 0xffffff)
|
||||
val intent =
|
||||
Intent(ACTION_OPEN_CHAT).apply {
|
||||
setPackage(context.packageName)
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
putExtra("chat_id", chatId)
|
||||
if (threadId != null) putExtra("thread_id", threadId)
|
||||
}
|
||||
val pi =
|
||||
PendingIntent.getActivity(
|
||||
context,
|
||||
id,
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
nm.notify(
|
||||
id,
|
||||
NotificationCompat.Builder(context, CHANNEL_PREFIX + chatId)
|
||||
NotificationCompat
|
||||
.Builder(context, channelIdFor(chatId))
|
||||
.setSmallIcon(android.R.drawable.ic_dialog_info)
|
||||
.setContentTitle(title)
|
||||
.setContentText(body)
|
||||
@@ -69,4 +80,4 @@ object IrisNotifications {
|
||||
.build(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,11 +11,13 @@ import android.os.IBinder
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import iris.protocol.IrisJson
|
||||
import iris.util.IrisLog
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
@@ -28,18 +30,31 @@ import java.util.concurrent.TimeUnit
|
||||
*
|
||||
* A foreground service that subscribes to this device's ntfy topic and posts
|
||||
* a system notification for each push. The structured payload rides in the
|
||||
* `X-Data` header (JSON: chat_id, kind, cursor, thread_id); the message body
|
||||
* is the short preview. When the app is foregrounded the WS path already
|
||||
* delivered the frame, so the service skips posting to avoid a duplicate.
|
||||
* `X-Data` SSE field (JSON: chat_id, kind, cursor, thread_id); the message
|
||||
* body is the short preview. When the app is foregrounded the SSE path
|
||||
* already delivered the frame, so the service skips posting to avoid a
|
||||
* duplicate.
|
||||
*
|
||||
* The stream is reconnected with capped exponential backoff when it drops
|
||||
* (EOF, network error, or a non-2xx response) — `START_STICKY` alone only
|
||||
* restarts the service after process death, not after a failed read.
|
||||
*/
|
||||
class NtfyListenerService : Service() {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
private var streamJob: Job? = null
|
||||
private val client = OkHttpClient.Builder()
|
||||
.readTimeout(0, TimeUnit.MILLISECONDS) // long-lived stream
|
||||
.build()
|
||||
private val client =
|
||||
OkHttpClient
|
||||
.Builder()
|
||||
// ntfy sends keep-alive comments every ~10 s; a 60 s read timeout
|
||||
// detects a half-open connection instead of hanging forever.
|
||||
.readTimeout(60, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
override fun onStartCommand(
|
||||
intent: Intent?,
|
||||
flags: Int,
|
||||
startId: Int,
|
||||
): Int {
|
||||
startForeground(NOTIF_ID, foregroundNotification())
|
||||
streamJob?.cancel()
|
||||
streamJob = scope.launch { stream() }
|
||||
@@ -60,47 +75,79 @@ class NtfyListenerService : Service() {
|
||||
if (topic.isBlank()) return
|
||||
val server = store.ntfyServer.ifBlank { DEFAULT_NTFY_SERVER }.removeSuffix("/")
|
||||
val url = "$server/$topic"
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.header("Accept", "text/event-stream")
|
||||
.build()
|
||||
try {
|
||||
client.newCall(request).execute().use { resp ->
|
||||
if (!resp.isSuccessful) return
|
||||
val body = resp.body ?: return
|
||||
val source = body.source()
|
||||
var data: String? = null
|
||||
var title: String? = null
|
||||
var msgBody: String? = null
|
||||
while (!source.exhausted()) {
|
||||
val line = source.readUtf8Line() ?: break
|
||||
when {
|
||||
line.startsWith("X-Data:") -> data = line.removePrefix("X-Data:").trim()
|
||||
line.startsWith("X-Title:") -> title = line.removePrefix("X-Title:").trim()
|
||||
line.startsWith("data:") -> msgBody = line.removePrefix("data:").trim()
|
||||
line.isEmpty() -> {
|
||||
// Event boundary: process the accumulated message.
|
||||
data?.let { handleData(it, title, msgBody) }
|
||||
data = null
|
||||
title = null
|
||||
msgBody = null
|
||||
}
|
||||
val request =
|
||||
Request
|
||||
.Builder()
|
||||
.url(url)
|
||||
.header("Accept", "text/event-stream")
|
||||
.build()
|
||||
var backoff = 1_000L
|
||||
while (true) {
|
||||
try {
|
||||
client.newCall(request).execute().use { resp ->
|
||||
if (!resp.isSuccessful) {
|
||||
IrisLog.w("ntfy stream HTTP ${resp.code}")
|
||||
} else {
|
||||
val body = resp.body ?: return
|
||||
readEvents(body.source())
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
IrisLog.w("ntfy stream dropped: ${e.message}")
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// Stream dropped; the service is START_STICKY so the system
|
||||
// restarts it. If it keeps failing, the WS path still works.
|
||||
// Stream ended (EOF, error, or non-2xx): back off and reconnect.
|
||||
delay(backoff)
|
||||
backoff = (backoff * 2).coerceAtMost(30_000L)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleData(dataJson: String, title: String?, msgBody: String?) {
|
||||
val data = try {
|
||||
IrisJson.instance.decodeFromString<JsonObject>(dataJson)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
/**
|
||||
* Read ntfy SSE events until EOF. `readUtf8Line()` returns null at EOF;
|
||||
* do NOT use `source.exhausted()` here — it reads until EOF and would
|
||||
* block forever on a live stream.
|
||||
*/
|
||||
private fun readEvents(source: okio.BufferedSource) {
|
||||
var data: String? = null
|
||||
var title: String? = null
|
||||
var msgBody: String? = null
|
||||
while (true) {
|
||||
val line = source.readUtf8Line() ?: break
|
||||
when {
|
||||
line.startsWith("X-Data:") -> {
|
||||
data = line.removePrefix("X-Data:").trim()
|
||||
}
|
||||
|
||||
line.startsWith("X-Title:") -> {
|
||||
title = line.removePrefix("X-Title:").trim()
|
||||
}
|
||||
|
||||
line.startsWith("data:") -> {
|
||||
msgBody = line.removePrefix("data:").trim()
|
||||
}
|
||||
|
||||
line.isEmpty() -> {
|
||||
// Event boundary: process the accumulated message.
|
||||
data?.let { handleData(it, title, msgBody) }
|
||||
data = null
|
||||
title = null
|
||||
msgBody = null
|
||||
}
|
||||
}
|
||||
}
|
||||
val chatId = data?.str("chat_id") ?: "android:default"
|
||||
}
|
||||
|
||||
private fun handleData(
|
||||
dataJson: String,
|
||||
title: String?,
|
||||
msgBody: String?,
|
||||
) {
|
||||
val data =
|
||||
try {
|
||||
IrisJson.instance.decodeFromString<JsonObject>(dataJson)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
val chatId = data?.str("chat_id") ?: "default"
|
||||
val threadId = data?.str("thread_id")
|
||||
// The short preview rides in the SSE `data:` field; fall back to the
|
||||
// X-Title, then a generic label.
|
||||
@@ -126,11 +173,12 @@ class NtfyListenerService : Service() {
|
||||
LISTENER_CHANNEL,
|
||||
"Iris push listener",
|
||||
NotificationManager.IMPORTANCE_MIN,
|
||||
)
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
return NotificationCompat.Builder(context, LISTENER_CHANNEL)
|
||||
return NotificationCompat
|
||||
.Builder(context, LISTENER_CHANNEL)
|
||||
.setSmallIcon(android.R.drawable.ic_dialog_info)
|
||||
.setContentTitle("Iris")
|
||||
.setContentText("Listening for messages")
|
||||
@@ -146,5 +194,4 @@ class NtfyListenerService : Service() {
|
||||
}
|
||||
|
||||
/** Read a string field from a JSON object (null when absent / not a string). */
|
||||
private fun JsonObject?.str(key: String): String? =
|
||||
(this?.get(key) as? JsonPrimitive)?.content
|
||||
private fun JsonObject?.str(key: String): String? = (this?.get(key) as? JsonPrimitive)?.content
|
||||
@@ -0,0 +1,49 @@
|
||||
package iris.platform
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.ContextWrapper
|
||||
import android.content.Intent
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
|
||||
/**
|
||||
* Android QR scanner (docs/20): launches [QrScanActivity] and returns the
|
||||
* scanned text (or null on cancel) to [onResult].
|
||||
*/
|
||||
@Composable
|
||||
actual fun QrScanButton(onResult: (String?) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val launcher =
|
||||
rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult(),
|
||||
) { result ->
|
||||
val text =
|
||||
if (result.resultCode == Activity.RESULT_OK) {
|
||||
result.data?.getStringExtra(QrScanActivity.EXTRA_QR)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
onResult(text)
|
||||
}
|
||||
Button(onClick = {
|
||||
val activity = context.resolveActivity()
|
||||
if (activity != null) {
|
||||
launcher.launch(Intent(activity, QrScanActivity::class.java))
|
||||
}
|
||||
}) {
|
||||
Text("Scan QR")
|
||||
}
|
||||
}
|
||||
|
||||
/** Walk a (possibly wrapped) context to the hosting [Activity], if any. */
|
||||
private fun Context.resolveActivity(): Activity? =
|
||||
when (this) {
|
||||
is Activity -> this
|
||||
is ContextWrapper -> baseContext.resolveActivity()
|
||||
else -> null
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package iris.platform
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Bundle
|
||||
import android.view.ViewGroup
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.addCallback
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.camera.core.CameraSelector
|
||||
import androidx.camera.core.ImageAnalysis
|
||||
import androidx.camera.core.ImageProxy
|
||||
import androidx.camera.core.Preview
|
||||
import androidx.camera.lifecycle.ProcessCameraProvider
|
||||
import androidx.camera.view.PreviewView
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.google.mlkit.vision.barcode.BarcodeScanning
|
||||
import com.google.mlkit.vision.common.InputImage
|
||||
|
||||
/**
|
||||
* Full-screen QR scanner (docs/20). Launched from the Connect screen's
|
||||
* "Scan QR" button; returns the raw QR text via [EXTRA_QR] on
|
||||
* [Activity.RESULT_OK], or [Activity.RESULT_CANCELED] on back/cancel.
|
||||
*
|
||||
* Uses the camera2 CameraX backend + ML Kit's barcode model. The camera is
|
||||
* stopped in [onDestroy].
|
||||
*/
|
||||
class QrScanActivity : ComponentActivity() {
|
||||
companion object {
|
||||
/** Intent extra carrying the scanned QR text. */
|
||||
const val EXTRA_QR = "qr"
|
||||
}
|
||||
|
||||
private lateinit var previewView: PreviewView
|
||||
private var cameraProvider: ProcessCameraProvider? = null
|
||||
private var settled = false
|
||||
|
||||
private val permissionLauncher =
|
||||
registerForActivityResult(
|
||||
ActivityResultContracts.RequestPermission(),
|
||||
) { granted ->
|
||||
if (granted) startCamera() else finish()
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
previewView =
|
||||
PreviewView(this).apply {
|
||||
layoutParams =
|
||||
ViewGroup.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
)
|
||||
}
|
||||
setContentView(previewView)
|
||||
|
||||
onBackPressedDispatcher.addCallback(this) {
|
||||
if (!settled) setResult(Activity.RESULT_CANCELED)
|
||||
finish()
|
||||
}
|
||||
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
|
||||
== PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
startCamera()
|
||||
} else {
|
||||
permissionLauncher.launch(Manifest.permission.CAMERA)
|
||||
}
|
||||
}
|
||||
|
||||
private fun startCamera() {
|
||||
val future = ProcessCameraProvider.getInstance(this)
|
||||
future.addListener(
|
||||
{
|
||||
val provider = future.get()
|
||||
cameraProvider = provider
|
||||
val preview =
|
||||
Preview.Builder().build().also {
|
||||
it.setSurfaceProvider(previewView.surfaceProvider)
|
||||
}
|
||||
val analyzer =
|
||||
ImageAnalysis
|
||||
.Builder()
|
||||
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||||
.build()
|
||||
try {
|
||||
provider.unbindAll()
|
||||
provider.bindToLifecycle(
|
||||
this,
|
||||
CameraSelector.DEFAULT_BACK_CAMERA,
|
||||
preview,
|
||||
analyzer,
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
// No usable camera (e.g. headless emulator): bail out.
|
||||
finish()
|
||||
return@addListener
|
||||
}
|
||||
analyzer.setAnalyzer(ContextCompat.getMainExecutor(this)) { proxy ->
|
||||
analyzeImage(proxy)
|
||||
}
|
||||
},
|
||||
ContextCompat.getMainExecutor(this),
|
||||
)
|
||||
}
|
||||
|
||||
private fun analyzeImage(proxy: ImageProxy) {
|
||||
val mediaImage = proxy.image
|
||||
if (mediaImage == null) {
|
||||
proxy.close()
|
||||
return
|
||||
}
|
||||
val inputImage = InputImage.fromMediaImage(mediaImage, proxy.imageInfo.rotationDegrees)
|
||||
BarcodeScanning
|
||||
.getClient()
|
||||
.process(inputImage)
|
||||
.addOnSuccessListener { barcodes ->
|
||||
val text = barcodes.firstOrNull { it.rawValue != null }?.rawValue
|
||||
if (text != null) finishWithResult(text)
|
||||
}.addOnCompleteListener { proxy.close() }
|
||||
}
|
||||
|
||||
private fun finishWithResult(text: String) {
|
||||
if (settled) return
|
||||
settled = true
|
||||
setResult(Activity.RESULT_OK, Intent().putExtra(EXTRA_QR, text))
|
||||
finish()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
cameraProvider?.unbindAll()
|
||||
super.onDestroy()
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
@@ -26,19 +27,21 @@ import iris.ui.theme.IrisColors
|
||||
import iris.ui.theme.IrisTheme
|
||||
import iris.ui.theme.LocalUserTheme
|
||||
import iris.ui.theme.rememberBackgroundImage
|
||||
import iris.util.PairLink
|
||||
|
||||
/**
|
||||
* Root composable shared by the Android and Desktop shells.
|
||||
*
|
||||
* M1: routes between the Connect screen (unpaired / auth failed) and the
|
||||
* Chat screen (paired). Later milestones add the channel list, search,
|
||||
* settings, and media (docs/10-android-app.md).
|
||||
* Routes between the Connect screen (unpaired / auth failed) and the main
|
||||
* app (paired), which hosts the channel list, chat, search, settings, and
|
||||
* media (docs/10-android-app.md).
|
||||
*/
|
||||
@Composable
|
||||
fun IrisApp(
|
||||
store: SecureStore,
|
||||
deepLinkChatId: String? = null,
|
||||
deepLinkThreadId: String? = null,
|
||||
deepLinkPair: PairLink? = null,
|
||||
) {
|
||||
val controller = remember(store) { IrisController(store) }
|
||||
DisposableEffect(controller) {
|
||||
@@ -66,10 +69,11 @@ fun IrisApp(
|
||||
// untouched, so the UI keeps its proportions at any size.
|
||||
CompositionLocalProvider(
|
||||
LocalUserTheme provides theme,
|
||||
LocalDensity provides Density(
|
||||
density = baseDensity.density,
|
||||
fontScale = baseDensity.fontScale * fontScale,
|
||||
),
|
||||
LocalDensity provides
|
||||
Density(
|
||||
density = baseDensity.density,
|
||||
fontScale = baseDensity.fontScale * fontScale,
|
||||
),
|
||||
) {
|
||||
// The color goes through Surface's `color` parameter: a
|
||||
// Modifier.background on the Surface would be painted *under* the
|
||||
@@ -95,20 +99,49 @@ fun IrisApp(
|
||||
)
|
||||
}
|
||||
val s = state
|
||||
// QR pairing (docs/20): an iris://pair deep link prefills
|
||||
// the Connect screen, taking priority over stored creds.
|
||||
val pairUrl = deepLinkPair?.url ?: store.serverUrl
|
||||
val pairToken = deepLinkPair?.token ?: store.token
|
||||
when (s) {
|
||||
GatewayClient.State.Disconnected ->
|
||||
ConnectScreen(controller, prefillUrl = store.serverUrl, prefillToken = store.token)
|
||||
is GatewayClient.State.AuthFailed ->
|
||||
ConnectScreen(
|
||||
controller,
|
||||
prefillUrl = store.serverUrl,
|
||||
prefillToken = store.token,
|
||||
initialError = "Pairing rejected: ${s.message}",
|
||||
)
|
||||
GatewayClient.State.Disconnected -> {
|
||||
key(deepLinkPair) {
|
||||
ConnectScreen(controller, prefillUrl = pairUrl, prefillToken = pairToken)
|
||||
}
|
||||
}
|
||||
|
||||
is GatewayClient.State.AuthFailed -> {
|
||||
key(deepLinkPair) {
|
||||
ConnectScreen(
|
||||
controller,
|
||||
prefillUrl = pairUrl,
|
||||
prefillToken = pairToken,
|
||||
initialError = "Pairing rejected: ${s.message}",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// TLS: the gateway's certificate is untrusted and not
|
||||
// the pinned one (docs/09 §9.4) — ask the user to
|
||||
// confirm its fingerprint (SSH host-key style).
|
||||
is GatewayClient.State.TlsConfirmRequired -> {
|
||||
key(deepLinkPair) {
|
||||
ConnectScreen(
|
||||
controller,
|
||||
prefillUrl = pairUrl,
|
||||
prefillToken = pairToken,
|
||||
initialError = "Gateway certificate needs confirmation — verify its fingerprint on the gateway host, then confirm below.",
|
||||
tlsFingerprint = s.fingerprint,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Connecting / Reconnecting / Connected all render the chat; the header
|
||||
// status bubble + connection banner show the link state
|
||||
// without blocking the view (M7's full-screen spinner is gone).
|
||||
else -> ChatScreen(controller)
|
||||
else -> {
|
||||
ChatScreen(controller)
|
||||
}
|
||||
}
|
||||
// M9: full-screen HTML artifact preview (opened from an
|
||||
// artifact card in the chat); covers everything while open.
|
||||
@@ -117,4 +150,4 @@ fun IrisApp(
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,15 +26,32 @@ class ChannelStore {
|
||||
_channels.value = sorted(channels)
|
||||
}
|
||||
|
||||
/** Restore the directory from the persistent local cache on startup
|
||||
* (offline: the drawer is populated before the gateway connection is
|
||||
* up). The server re-seeds it on connect (`hello.ack`). No-op when
|
||||
* [channels] is empty (first launch). */
|
||||
fun loadFromCache(channels: List<ChannelInfo>) {
|
||||
if (channels.isNotEmpty()) _channels.value = sorted(channels)
|
||||
}
|
||||
|
||||
/** Reconcile a server frame into the cache. */
|
||||
fun onFrame(frame: Frame) {
|
||||
when (frame.type) {
|
||||
TYPE_CHANNEL_CREATED, TYPE_CHANNEL_RENAMED -> upsert(frame)
|
||||
TYPE_CHANNEL_DELETED -> remove(frame)
|
||||
TYPE_CHANNEL_CREATED, TYPE_CHANNEL_RENAMED -> {
|
||||
upsert(frame)
|
||||
}
|
||||
|
||||
TYPE_CHANNEL_DELETED -> {
|
||||
remove(frame)
|
||||
}
|
||||
|
||||
TYPE_CHANNEL_LIST -> {
|
||||
frame.payloadAs<ChannelListPayload>()?.let { setAll(it.channels) }
|
||||
}
|
||||
else -> Unit
|
||||
|
||||
else -> {
|
||||
Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,7 +65,58 @@ class ChannelStore {
|
||||
|
||||
private fun remove(frame: Frame) {
|
||||
val p = frame.payloadAs<ChannelDeletedPayload>() ?: return
|
||||
_channels.value = _channels.value.filter { it.chatId != p.chatId }
|
||||
// A channel delete also removes its threads (child entries); a thread
|
||||
// delete removes just that thread. Both are hard deletes server-side.
|
||||
_channels.value =
|
||||
_channels.value.filter { it.chatId != p.chatId && it.parentChatId != p.chatId }
|
||||
}
|
||||
|
||||
// ── Optimistic local updates (M-7) ────────────────────────────────────
|
||||
//
|
||||
// The gateway only broadcasts channel.created/renamed/deleted — there are
|
||||
// no favorite/icon/automation/default events. So a toggle sent by THIS
|
||||
// device would not update its own UI until a full channel.list re-fetch.
|
||||
// These apply the change locally (optimistically); a later channel.list /
|
||||
// hello.ack re-seed reconciles any divergence (e.g. a server rejection).
|
||||
|
||||
/** Toggle the cosmetic favorite flag locally. */
|
||||
fun setFavorite(
|
||||
chatId: String,
|
||||
on: Boolean,
|
||||
) = update(chatId) { it.copy(favorite = on) }
|
||||
|
||||
/** Toggle the automation flag locally. */
|
||||
fun setAutomation(
|
||||
chatId: String,
|
||||
on: Boolean,
|
||||
) = update(chatId) { it.copy(automation = on) }
|
||||
|
||||
/** Set the icon (base64) and/or avatar color locally; null clears a field. */
|
||||
fun setIcon(
|
||||
chatId: String,
|
||||
icon: String?,
|
||||
color: String?,
|
||||
) = update(chatId) { it.copy(icon = icon, color = color) }
|
||||
|
||||
/** Make [chatId] the default channel locally (clearing the previous one). */
|
||||
fun setDefault(chatId: String) {
|
||||
_channels.value =
|
||||
sorted(
|
||||
_channels.value.map {
|
||||
when {
|
||||
it.chatId == chatId -> it.copy(isDefault = true)
|
||||
it.isDefault -> it.copy(isDefault = false)
|
||||
else -> it
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private fun update(
|
||||
chatId: String,
|
||||
transform: (ChannelInfo) -> ChannelInfo,
|
||||
) {
|
||||
_channels.value = sorted(_channels.value.map { if (it.chatId == chatId) transform(it) else it })
|
||||
}
|
||||
|
||||
private fun sorted(list: List<ChannelInfo>): List<ChannelInfo> =
|
||||
@@ -62,20 +130,16 @@ class ChannelStore {
|
||||
// ── UI helpers ────────────────────────────────────────────────────────
|
||||
|
||||
/** Channels (default + user channels) for the drawer/rail. */
|
||||
fun channelsForDrawer(): List<ChannelInfo> =
|
||||
_channels.value.filter { it.kind != "thread" }
|
||||
fun channelsForDrawer(): List<ChannelInfo> = _channels.value.filter { it.kind != "thread" }
|
||||
|
||||
/** Threads under a channel, for the topic switcher. */
|
||||
fun threadsFor(chatId: String): List<ChannelInfo> =
|
||||
_channels.value.filter { it.kind == "thread" && it.parentChatId == chatId }
|
||||
fun threadsFor(chatId: String): List<ChannelInfo> = _channels.value.filter { it.kind == "thread" && it.parentChatId == chatId }
|
||||
|
||||
fun byId(chatId: String): ChannelInfo? =
|
||||
_channels.value.firstOrNull { it.chatId == chatId }
|
||||
fun byId(chatId: String): ChannelInfo? = _channels.value.firstOrNull { it.chatId == chatId }
|
||||
|
||||
fun defaultChannel(): ChannelInfo? =
|
||||
_channels.value.firstOrNull { it.isDefault } ?: _channels.value.firstOrNull()
|
||||
fun defaultChannel(): ChannelInfo? = _channels.value.firstOrNull { it.isDefault } ?: _channels.value.firstOrNull()
|
||||
|
||||
fun clear() {
|
||||
_channels.value = emptyList()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package iris.data
|
||||
|
||||
import app.cash.sqldelight.db.SqlDriver
|
||||
import iris.db.IrisDatabase
|
||||
import iris.protocol.ChannelInfo
|
||||
import iris.protocol.IrisJson
|
||||
|
||||
/**
|
||||
* Persistent local cache (SQLite via SQLDelight — the locked "Local DB (KMP)"
|
||||
* decision, docs/16; schema docs/10 §10.7). The server is authoritative; this
|
||||
* is a cache that lets the app start instantly and read chats offline:
|
||||
*
|
||||
* - [loadLanes] / [loadChannels] restore the in-memory stores on startup,
|
||||
* before the gateway connection is up (snappy start, offline reading).
|
||||
* - [saveLanes] / [saveChannels] snapshot the in-memory stores (debounced by
|
||||
* the controller) so every reconciled frame survives a process death.
|
||||
* - [metaGet] / [metaPut] hold small UI state (last-viewed lane).
|
||||
*
|
||||
* [MessageItem]s and [ToolItem]s are persisted; live streaming state and
|
||||
* local system notices are ephemeral. Rows are JSON payloads keyed by
|
||||
* (lane, id), so the schema does not drift with the model fields.
|
||||
*
|
||||
* All access is synchronized: the debounced save collectors run on the
|
||||
* controller scope while [dispose] may flush from the UI thread.
|
||||
*/
|
||||
class ChatDb(
|
||||
driver: SqlDriver,
|
||||
) {
|
||||
private val db = IrisDatabase(driver)
|
||||
private val json = IrisJson.instance
|
||||
private val lock = Any()
|
||||
|
||||
// ── messages ──────────────────────────────────────────────────────────
|
||||
|
||||
/** All persisted lanes (lane key -> items: messages ordered by ts with
|
||||
* tool cards interleaved at their anchored position). */
|
||||
fun loadLanes(): Map<String, List<ChatItem>> =
|
||||
synchronized(lock) {
|
||||
val messages = linkedMapOf<String, MutableList<ChatItem>>()
|
||||
for (row in db.cacheQueries.allMessages().executeAsList()) {
|
||||
val item = decodeMessage(row.payload) ?: continue
|
||||
messages.getOrPut(row.lane) { mutableListOf() }.add(item)
|
||||
}
|
||||
val tools = linkedMapOf<String, MutableList<ToolItem>>()
|
||||
for (row in db.cacheQueries.allTools().executeAsList()) {
|
||||
val item = decodeTool(row.payload) ?: continue
|
||||
tools.getOrPut(row.lane) { mutableListOf() }.add(item)
|
||||
}
|
||||
(messages.keys + tools.keys).distinct().associateWith { lane ->
|
||||
val items: MutableList<ChatItem> = messages[lane].orEmpty().toMutableList()
|
||||
// Insert each tool card after its anchor message (the message
|
||||
// it followed live). Cards sharing an anchor keep their seq
|
||||
// order; a card whose anchor is gone (deleted message) falls
|
||||
// to the end of the lane. The lastPos cache assumes anchors
|
||||
// are monotonically non-decreasing per lane (true for the
|
||||
// onToolStart anchor rule: last non-streaming message) — a
|
||||
// tool anchored to an EARLIER message processed after a
|
||||
// later-anchored one would be misplaced.
|
||||
val lastPos = mutableMapOf<String, Int>()
|
||||
for (tool in tools[lane].orEmpty()) {
|
||||
val anchor = tool.anchorId
|
||||
val pos =
|
||||
if (anchor == null) {
|
||||
-1
|
||||
} else {
|
||||
lastPos.getOrPut(anchor) { items.indexOfFirst { it.id == anchor } }
|
||||
}
|
||||
if (pos >= 0) {
|
||||
items.add(pos + 1, tool)
|
||||
if (anchor != null) lastPos[anchor] = pos + 1
|
||||
} else {
|
||||
items.add(tool)
|
||||
}
|
||||
}
|
||||
items
|
||||
}
|
||||
}
|
||||
|
||||
/** Replace the whole message + tool cache with [lanes] (atomic snapshot).
|
||||
* Local system notices are skipped (ephemeral). */
|
||||
fun saveLanes(lanes: Map<String, List<ChatItem>>) {
|
||||
synchronized(lock) {
|
||||
db.transaction {
|
||||
db.cacheQueries.clearMessages()
|
||||
db.cacheQueries.clearTools()
|
||||
for ((lane, items) in lanes) {
|
||||
var toolSeq = 0
|
||||
for (item in items) {
|
||||
when (item) {
|
||||
is MessageItem -> {
|
||||
if (!item.isSystem) {
|
||||
db.cacheQueries.upsertMessage(lane, item.id, item.ts, json.encodeToString(item))
|
||||
}
|
||||
}
|
||||
|
||||
is ToolItem -> {
|
||||
db.cacheQueries.upsertTool(lane, item.id, toolSeq++.toLong(), json.encodeToString(item))
|
||||
}
|
||||
|
||||
// Picker cards ride in the message table (JSON
|
||||
// payload; decodeMessage picks the type back out).
|
||||
is PickerItem -> {
|
||||
db.cacheQueries.upsertMessage(lane, item.id, item.ts, json.encodeToString(item))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── channels ──────────────────────────────────────────────────────────
|
||||
|
||||
/** The persisted channel directory (channels + threads). */
|
||||
fun loadChannels(): List<ChannelInfo> =
|
||||
synchronized(lock) {
|
||||
val list = mutableListOf<ChannelInfo>()
|
||||
for (row in db.cacheQueries.allChannels().executeAsList()) {
|
||||
try {
|
||||
list.add(json.decodeFromString(row.payload))
|
||||
} catch (_: Exception) {
|
||||
// Corrupt row — skip it; the server re-seeds on connect.
|
||||
}
|
||||
}
|
||||
list
|
||||
}
|
||||
|
||||
/** Replace the whole channel directory (atomic snapshot). */
|
||||
fun saveChannels(channels: List<ChannelInfo>) {
|
||||
synchronized(lock) {
|
||||
db.transaction {
|
||||
db.cacheQueries.clearChannels()
|
||||
for (c in channels) {
|
||||
db.cacheQueries.upsertChannel(c.chatId, json.encodeToString(c))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── meta ──────────────────────────────────────────────────────────────
|
||||
|
||||
fun metaGet(key: String): String? =
|
||||
synchronized(lock) {
|
||||
db.cacheQueries.metaGet(key).executeAsOneOrNull()
|
||||
}
|
||||
|
||||
fun metaPut(
|
||||
key: String,
|
||||
value: String,
|
||||
) {
|
||||
synchronized(lock) {
|
||||
db.cacheQueries.metaPut(key, value)
|
||||
}
|
||||
}
|
||||
|
||||
/** Wipe the whole cache (forget pairing → a different gateway). */
|
||||
fun clearAll() {
|
||||
synchronized(lock) {
|
||||
db.transaction {
|
||||
db.cacheQueries.clearMessages()
|
||||
db.cacheQueries.clearTools()
|
||||
db.cacheQueries.clearChannels()
|
||||
db.cacheQueries.clearMeta()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun decodeMessage(payload: String): ChatItem? =
|
||||
try {
|
||||
json.decodeFromString<MessageItem>(payload).sanitizeForRestore()
|
||||
} catch (_: Exception) {
|
||||
// Not a message payload — a picker card (MessageItem requires
|
||||
// "role", PickerItem requires "title": the two never cross-decode).
|
||||
try {
|
||||
json.decodeFromString<PickerItem>(payload)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun decodeTool(payload: String): ToolItem? =
|
||||
try {
|
||||
json.decodeFromString<ToolItem>(payload).sanitizeForRestore()
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
|
||||
/** A restored message is never mid-flight: a streaming bubble is
|
||||
* finalized (the sync replay finalizes it for real on reconnect) and a
|
||||
* pending send becomes failed (tap to retry) — the gateway never
|
||||
* acknowledged it before the process died. */
|
||||
private fun MessageItem.sanitizeForRestore(): MessageItem =
|
||||
copy(
|
||||
streaming = false,
|
||||
pending = false,
|
||||
status = if (status == MsgStatus.Pending) MsgStatus.Failed else status,
|
||||
)
|
||||
|
||||
/** A restored tool card is never mid-flight: an open card (the process
|
||||
* died before tool.end) is closed as interrupted, mirroring
|
||||
* [ChatStore.finalizeInterrupted]. */
|
||||
private fun ToolItem.sanitizeForRestore(): ToolItem = if (done) this else copy(done = true, ok = false)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,16 +2,26 @@ package iris.data
|
||||
|
||||
/**
|
||||
* Pairing settings storage. The token is a secret: platform actuals keep it
|
||||
* in secure storage (EncryptedSharedPreferences on Android — M5; plain
|
||||
* SharedPreferences for M1 dev, file on desktop).
|
||||
* in secure storage (EncryptedSharedPreferences on Android, OS keyring or an
|
||||
* encrypted file on desktop).
|
||||
*/
|
||||
interface SecureStore {
|
||||
/** ws(s)://host:port/ws */
|
||||
/** http(s)://host:port (legacy ws(s):// URLs are still accepted) */
|
||||
var serverUrl: String
|
||||
|
||||
/** ANDROID_TOKEN presented in the hello frame. */
|
||||
/** IRIS_TOKEN presented in the auth header (bootstrap / fallback). */
|
||||
var token: String
|
||||
|
||||
/** Per-device token minted at pairing (hello.ack ``device_token``,
|
||||
* docs/09 §9.3). Presented INSTEAD of [token] when non-empty; the
|
||||
* gateway can revoke it per device. Empty until the first hello.ack. */
|
||||
var deviceToken: String
|
||||
|
||||
/** SHA-256 fingerprint (colon-separated pairs) of the gateway's TLS
|
||||
* certificate, confirmed by the user on first pair (docs/09 §9.4).
|
||||
* Empty = nothing pinned (CA-signed certs need no pin). */
|
||||
var pinnedCertFingerprint: String
|
||||
|
||||
/** Stable app-generated device id (persisted). */
|
||||
val deviceId: String
|
||||
|
||||
@@ -44,6 +54,10 @@ interface SecureStore {
|
||||
/** UI setting: stream assistant replies live (token by token). */
|
||||
var streamingEnabled: Boolean
|
||||
|
||||
/** UI setting: streaming smoothness — seconds between visible text
|
||||
* updates while streaming (0.2–0.8; lower = faster/smoother). */
|
||||
var streamSmoothness: Float
|
||||
|
||||
/** UI setting: auto-collapse long reasoning blocks in the chat view. */
|
||||
var reasoningAutoCollapse: Boolean
|
||||
|
||||
@@ -66,6 +80,15 @@ interface SecureStore {
|
||||
* system font scale). */
|
||||
var fontSizeScale: Float
|
||||
|
||||
/** UI setting: show the runtime-metadata footer under final assistant
|
||||
* messages (model / context % / cwd / latency / cost). */
|
||||
var runtimeFooterEnabled: Boolean
|
||||
|
||||
/** UI setting: which runtime-footer fields to show, as a comma-separated
|
||||
* list in display order (e.g. "model,context_pct,cwd"). Empty = the
|
||||
* default set. Valid keys: model, context_pct, cwd, latency, cost. */
|
||||
var runtimeFooterFields: String
|
||||
|
||||
fun savePairing(
|
||||
url: String,
|
||||
token: String,
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
package iris.media
|
||||
|
||||
/** A readable local file (expect/actual; JVM impl in jvmMain). */
|
||||
expect class FileSource(path: String) : AutoCloseable {
|
||||
/** Total size in bytes. */
|
||||
fun size(): Long
|
||||
|
||||
/** Read up to [buf.size] bytes into [buf]; returns bytes read or -1 at EOF. */
|
||||
fun read(buf: ByteArray): Int
|
||||
}
|
||||
@@ -6,32 +6,43 @@ import iris.protocol.KIND_IMAGE
|
||||
import iris.protocol.KIND_VIDEO
|
||||
|
||||
/** Map a MIME type to a media kind (docs/07 §7.1). */
|
||||
fun kindFromMime(mime: String): String = when {
|
||||
mime.startsWith("image/") -> KIND_IMAGE
|
||||
mime.startsWith("video/") -> KIND_VIDEO
|
||||
mime.startsWith("audio/") -> KIND_AUDIO
|
||||
else -> KIND_DOCUMENT
|
||||
}
|
||||
fun kindFromMime(mime: String): String =
|
||||
when {
|
||||
mime.startsWith("image/") -> KIND_IMAGE
|
||||
mime.startsWith("video/") -> KIND_VIDEO
|
||||
mime.startsWith("audio/") -> KIND_AUDIO
|
||||
else -> KIND_DOCUMENT
|
||||
}
|
||||
|
||||
/** Best-effort file extension for a MIME type (cache file naming). */
|
||||
fun extForMime(mime: String): String = when {
|
||||
mime == "image/jpeg" -> ".jpg"
|
||||
mime == "image/png" -> ".png"
|
||||
mime == "image/webp" -> ".webp"
|
||||
mime == "image/gif" -> ".gif"
|
||||
mime == "image/heic" -> ".heic"
|
||||
mime == "image/heif" -> ".heif"
|
||||
mime == "video/mp4" -> ".mp4"
|
||||
mime == "video/webm" -> ".webm"
|
||||
mime == "video/quicktime" -> ".mov"
|
||||
mime == "audio/mpeg" -> ".mp3"
|
||||
mime == "audio/mp4" || mime == "audio/x-m4a" -> ".m4a"
|
||||
mime == "audio/ogg" -> ".ogg"
|
||||
mime == "audio/wav" -> ".wav"
|
||||
mime == "audio/flac" -> ".flac"
|
||||
mime == "audio/aac" -> ".aac"
|
||||
mime == "application/pdf" -> ".pdf"
|
||||
mime == "application/zip" -> ".zip"
|
||||
mime == "text/plain" -> ".txt"
|
||||
else -> ".bin"
|
||||
}
|
||||
fun extForMime(mime: String): String =
|
||||
when {
|
||||
mime == "image/jpeg" -> ".jpg"
|
||||
mime == "image/png" -> ".png"
|
||||
mime == "image/webp" -> ".webp"
|
||||
mime == "image/gif" -> ".gif"
|
||||
mime == "image/heic" -> ".heic"
|
||||
mime == "image/heif" -> ".heif"
|
||||
mime == "video/mp4" -> ".mp4"
|
||||
mime == "video/webm" -> ".webm"
|
||||
mime == "video/quicktime" -> ".mov"
|
||||
mime == "audio/mpeg" -> ".mp3"
|
||||
mime == "audio/mp4" || mime == "audio/x-m4a" -> ".m4a"
|
||||
mime == "audio/ogg" -> ".ogg"
|
||||
mime == "audio/wav" -> ".wav"
|
||||
mime == "audio/flac" -> ".flac"
|
||||
mime == "audio/aac" -> ".aac"
|
||||
mime == "application/pdf" -> ".pdf"
|
||||
mime == "application/zip" -> ".zip"
|
||||
mime == "text/plain" -> ".txt"
|
||||
else -> ".bin"
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a server-provided media id before it is used in a file path or a
|
||||
* `GET /v1/media/{id}` URL (M-2 / S-1). The id comes from the gateway's
|
||||
* `media.offer` frame; a value like `../../x` would write outside the media
|
||||
* directory and break the pull URL. Only a conservative token charset is
|
||||
* accepted.
|
||||
*/
|
||||
fun isValidMediaId(id: String): Boolean = id.length in 1..128 && id.all { it.isLetterOrDigit() || it == '_' || it == '-' }
|
||||
@@ -1,67 +1,48 @@
|
||||
package iris.net
|
||||
|
||||
import iris.data.SecureStore
|
||||
import iris.media.FileSource
|
||||
import iris.media.Sha256
|
||||
import iris.protocol.ChannelInfo
|
||||
import iris.protocol.ErrorPayload
|
||||
import iris.protocol.Frame
|
||||
import iris.protocol.HelloAckPayload
|
||||
import iris.protocol.IrisJson
|
||||
import iris.protocol.MediaPullEndPayload
|
||||
import iris.protocol.MediaUploadAckPayload
|
||||
import iris.protocol.ServerCaps
|
||||
import iris.protocol.TYPE_ERROR
|
||||
import iris.protocol.TYPE_HELLO_ACK
|
||||
import iris.protocol.TYPE_MEDIA_PULL_END
|
||||
import iris.protocol.TYPE_MEDIA_UPLOAD_ACK
|
||||
import iris.protocol.TYPE_PONG
|
||||
import iris.protocol.helloFrame
|
||||
import iris.protocol.mediaPullFrame
|
||||
import iris.protocol.mediaUploadEndFrame
|
||||
import iris.protocol.mediaUploadStartFrame
|
||||
import iris.protocol.messageSendFrame
|
||||
import iris.protocol.pingFrame
|
||||
import iris.protocol.syncFrame
|
||||
import iris.util.IrisLog
|
||||
import iris.util.nowMillis
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import kotlin.time.TimeMark
|
||||
import kotlin.time.TimeSource
|
||||
import okhttp3.OkHttpClient
|
||||
import okio.ByteString
|
||||
import okio.ByteString.Companion.toByteString
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlin.random.Random
|
||||
|
||||
/**
|
||||
* OkHttp WebSocket client for the hermes android gateway (docs/10 §10.3).
|
||||
* HTTP client for the hermes iris gateway (docs/19).
|
||||
*
|
||||
* - connect + hello (real auth leg), hello.ack
|
||||
* HTTP is the only transport: send via `POST /v1/frame`, receive over SSE
|
||||
* `/v1/events` (long-poll fallback), media via `POST/GET /v1/media`.
|
||||
*
|
||||
* - connect: health probe + SSE hello (the HTTP hello.ack)
|
||||
* - reconnect: exponential backoff + jitter; re-hello on every (re)connect
|
||||
* - heartbeat: app-level ping every 20s; reap after ~60s of silence
|
||||
* - events: server frames (minus hello.ack) on [events]
|
||||
* - request/response correlation by id (M2+ consumers)
|
||||
* - events: server frames on [events]
|
||||
* - correlation: the POST body carries the synchronous reply (e.g. read
|
||||
* receipt, errors); everything else arrives on the event stream, and the
|
||||
* app reconciles by frame id (docs/19 §19.7)
|
||||
*/
|
||||
class GatewayClient(
|
||||
private val scope: CoroutineScope,
|
||||
@@ -69,7 +50,9 @@ class GatewayClient(
|
||||
) {
|
||||
sealed interface State {
|
||||
data object Disconnected : State
|
||||
|
||||
data object Connecting : State
|
||||
|
||||
data class Connected(
|
||||
val caps: ServerCaps,
|
||||
val channels: List<ChannelInfo>,
|
||||
@@ -78,8 +61,19 @@ class GatewayClient(
|
||||
* it must not re-post system notifications (docs/08 §8.7). */
|
||||
val lastPushedCursor: Long = 0,
|
||||
) : State
|
||||
|
||||
data object Reconnecting : State
|
||||
data class AuthFailed(val message: String) : State
|
||||
|
||||
data class AuthFailed(
|
||||
val message: String,
|
||||
) : State
|
||||
|
||||
/** The gateway's TLS certificate is untrusted and doesn't match the
|
||||
* pinned fingerprint (docs/09 §9.4). Terminal: the connect loop
|
||||
* stops and the UI asks the user to confirm the fingerprint. */
|
||||
data class TlsConfirmRequired(
|
||||
val fingerprint: String,
|
||||
) : State
|
||||
}
|
||||
|
||||
private val _state = MutableStateFlow<State>(State.Disconnected)
|
||||
@@ -92,36 +86,79 @@ class GatewayClient(
|
||||
private val _events = MutableSharedFlow<Frame>(extraBufferCapacity = 128)
|
||||
val events: SharedFlow<Frame> = _events.asSharedFlow()
|
||||
|
||||
private val client: OkHttpClient = OkHttpClient.Builder()
|
||||
.pingInterval(20, TimeUnit.SECONDS)
|
||||
.build()
|
||||
// TLS: the pinning trust manager wraps the platform default (CA-signed
|
||||
// certs behave as before); a self-signed gateway cert is accepted only
|
||||
// after the user confirms its fingerprint (docs/09 §9.4). The pin is
|
||||
// read live from the store so a fresh confirm takes effect without
|
||||
// rebuilding the client.
|
||||
private val pinningTm = PinningTrustManager { store.pinnedCertFingerprint }
|
||||
|
||||
private val client: OkHttpClient =
|
||||
OkHttpClient
|
||||
.Builder()
|
||||
.pingInterval(20, TimeUnit.SECONDS)
|
||||
.sslSocketFactory(pinningSslSocketFactory(pinningTm), pinningTm)
|
||||
.build()
|
||||
|
||||
private var connectJob: Job? = null
|
||||
private var socket: WebSocket? = null
|
||||
private var nextRequestId = 1
|
||||
|
||||
// Incremented from the SSE callback thread (onHttpHello) and the UI
|
||||
// thread (sendFrame/sendMessage) — keep it atomic or ids collide and
|
||||
// request/response correlation breaks.
|
||||
private fun nextId(): Int = synchronized(this) { nextRequestId++ }
|
||||
|
||||
// Written by poke() (UI thread) and the connect loop (Default).
|
||||
@Volatile
|
||||
private var attempt = 0
|
||||
|
||||
// Set by poke() (app returned to the foreground): the connect loop's
|
||||
// backoff waits in 500 ms slices and re-probes immediately when set.
|
||||
@Volatile
|
||||
private var wakeRequested = false
|
||||
|
||||
// True once a connection has been established this session; reset by
|
||||
// start(). Drives Connecting (first dial) vs Reconnecting (redial after a
|
||||
// drop) so the UI can show the right status without a blocking screen.
|
||||
private var hasConnected = false
|
||||
private var lastLiveness: TimeMark = TimeSource.Monotonic.markNow()
|
||||
private val pending = mutableMapOf<Int, CompletableDeferred<Frame>>()
|
||||
|
||||
// M4: binary frames (media upload chunks / pull stream) have no per-frame
|
||||
// id, so at most one binary session is active per socket. The gateway
|
||||
// allows one upload per connection; pull is request/response.
|
||||
private sealed interface BinarySession {
|
||||
data class Pulling(
|
||||
val requestId: Int,
|
||||
val chunks: Channel<ByteArray>,
|
||||
val end: CompletableDeferred<Frame>,
|
||||
) : BinarySession
|
||||
}
|
||||
// HTTP leg: [http] is created lazily from the stored URL; [httpCursor] is
|
||||
// the resume cursor (SSE id / outbox high-water mark), updated from the
|
||||
// SSE/poll callback threads.
|
||||
private var http: HttpGateway? = null
|
||||
|
||||
private var binarySession: BinarySession? = null
|
||||
@Volatile
|
||||
private var httpCursor: Long = 0
|
||||
private var sseFailures = 0
|
||||
private var usingLongPoll = false
|
||||
|
||||
// M4: only one pull may be in flight at a time (binarySession is a single
|
||||
// slot). Serialize concurrent offers so their byte streams don't interleave.
|
||||
// Last hello.ack payload — used to restore State.Connected after a
|
||||
// reconnect state race in the connect loop. Written by the SSE callback
|
||||
// thread, read by the long-poll loop.
|
||||
@Volatile
|
||||
private var lastAck: HelloAckPayload? = null
|
||||
|
||||
// Epoch ms of the last frame delivered by the receive stream (SSE or
|
||||
// long-poll). The watchdog uses this to detect a STALE stream: a live
|
||||
// connection (heartbeats / poll answers keep it open, so the read timeout
|
||||
// never fires) that has stopped delivering frames — the state a gateway
|
||||
// restart can leave the app in, where sent messages sit at "sending…"
|
||||
// because their echo is never delivered (issue #6). Set when the receive
|
||||
// loop (re)starts so the first window isn't treated as stale.
|
||||
@Volatile
|
||||
private var lastFrameMs: Long = 0L
|
||||
|
||||
/**
|
||||
* Fired promptly the moment the SSE hello (hello.ack) is received — on
|
||||
* every (re)connect. Used for time-critical work that must not wait for
|
||||
* the state collector, which can be starved for seconds during app
|
||||
* startup (Dispatchers.Default) and would push a history request past a
|
||||
* flaky network's window. Set before [start].
|
||||
*/
|
||||
var onHelloAck: ((State.Connected) -> Unit)? = null
|
||||
|
||||
// Only one pull may be in flight at a time. Serialize concurrent offers so
|
||||
// their byte streams don't interleave.
|
||||
private val pullMutex = Mutex()
|
||||
|
||||
// ── Lifecycle ─────────────────────────────────────────────────────────
|
||||
@@ -134,13 +171,34 @@ class GatewayClient(
|
||||
connectJob = scope.launch { connectLoop() }
|
||||
}
|
||||
|
||||
/** Stop the connect loop and close the socket. */
|
||||
/**
|
||||
* Stop the connect loop and reset the HTTP leg. Without the reset, a
|
||||
* re-pair to a *different* gateway would keep using the cached
|
||||
* [HttpGateway] (old URL, old token, old resume cursor) until the process
|
||||
* is killed.
|
||||
*/
|
||||
fun stop() {
|
||||
connectJob?.cancel()
|
||||
connectJob = null
|
||||
socket?.close(1000, "client shutdown")
|
||||
socket = null
|
||||
_state.value = State.Disconnected
|
||||
http?.close()
|
||||
http = null
|
||||
httpCursor = 0
|
||||
sseFailures = 0
|
||||
usingLongPoll = false
|
||||
lastAck = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Call when the app returns to the foreground: if the connect loop is
|
||||
* between attempts (backing off after failed health probes — up to 30 s),
|
||||
* wake it so it re-probes immediately instead of making the user wait out
|
||||
* the backoff with a "Connecting…" banner. No-op while connected.
|
||||
*/
|
||||
fun poke() {
|
||||
if (_state.value is State.Connected) return
|
||||
attempt = 0
|
||||
wakeRequested = true
|
||||
}
|
||||
|
||||
/** Re-pair: stop, then start fresh (used after saving new settings). */
|
||||
@@ -152,181 +210,294 @@ class GatewayClient(
|
||||
private suspend fun connectLoop() {
|
||||
while (currentCoroutineContext().isActive) {
|
||||
val url = store.serverUrl.trim()
|
||||
val token = store.token
|
||||
// Per-device token when the gateway minted one (docs/09 §9.3),
|
||||
// else the shared IRIS_TOKEN (bootstrap).
|
||||
val token = store.deviceToken.ifBlank { store.token }
|
||||
if (url.isBlank() || token.isBlank()) {
|
||||
_state.value = State.Disconnected
|
||||
return
|
||||
}
|
||||
_state.value = if (hasConnected) State.Reconnecting else State.Connecting
|
||||
val dial = dial(url, token)
|
||||
when (val result = dial.result) {
|
||||
is DialResult.AuthFailed -> {
|
||||
_state.value = State.AuthFailed(result.message)
|
||||
dial.socket.close(1000, "auth failed")
|
||||
return
|
||||
}
|
||||
DialResult.Connected -> {
|
||||
hasConnected = true
|
||||
attempt = 0
|
||||
lastLiveness = TimeSource.Monotonic.markNow()
|
||||
dial.closed.await()
|
||||
if (!currentCoroutineContext().isActive) return
|
||||
// socket dropped -> loop again (Reconnecting)
|
||||
}
|
||||
is DialResult.Failed -> {
|
||||
attempt++
|
||||
delay(backoffMs(attempt))
|
||||
val gw = httpGateway() ?: continue
|
||||
// Health probe: if the gateway is alive, open the SSE receive loop
|
||||
// (which delivers the hello.ack). Otherwise back off and retry.
|
||||
val healthOk =
|
||||
try {
|
||||
gw.health()
|
||||
} catch (e: Exception) {
|
||||
if (failTls(e)) return
|
||||
false
|
||||
}
|
||||
if (!healthOk) {
|
||||
attempt++
|
||||
backoffOrWake(backoffMs(attempt))
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Dial (one connect + hello) ────────────────────────────────────────
|
||||
|
||||
private sealed interface DialResult {
|
||||
data object Connected : DialResult
|
||||
data class AuthFailed(val message: String) : DialResult
|
||||
data class Failed(val message: String) : DialResult
|
||||
}
|
||||
|
||||
private data class Dial(
|
||||
val result: DialResult,
|
||||
val socket: WebSocket,
|
||||
val closed: CompletableDeferred<Unit>,
|
||||
)
|
||||
|
||||
private suspend fun dial(url: String, token: String): Dial {
|
||||
val closed = CompletableDeferred<Unit>()
|
||||
val helloAck = CompletableDeferred<HelloAckPayload>()
|
||||
val authError = CompletableDeferred<String>()
|
||||
val fail = CompletableDeferred<String>()
|
||||
|
||||
val request = Request.Builder().url(url).build()
|
||||
val ws = client.newWebSocket(
|
||||
request,
|
||||
object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||
IrisLog.d("ws open (${response.code})")
|
||||
webSocket.send(
|
||||
helloFrame(
|
||||
token = token,
|
||||
deviceId = store.deviceId,
|
||||
deviceName = store.deviceName,
|
||||
fcmToken = store.fcmToken.ifBlank { null },
|
||||
ntfyTopic = store.ntfyTopic.ifBlank { null },
|
||||
).toWire(),
|
||||
)
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
lastLiveness = TimeSource.Monotonic.markNow()
|
||||
val frame = try {
|
||||
IrisJson.instance.decodeFromString(Frame.serializer(), text)
|
||||
} catch (_: Exception) {
|
||||
return
|
||||
}
|
||||
when (frame.type) {
|
||||
TYPE_HELLO_ACK -> {
|
||||
val ack = frame.payloadAs<HelloAckPayload>()
|
||||
if (ack != null) helloAck.complete(ack)
|
||||
}
|
||||
TYPE_ERROR -> {
|
||||
val err = frame.payloadAs<ErrorPayload>()
|
||||
if (!authError.isCompleted) authError.complete(err?.message ?: "auth failed")
|
||||
// M7: post-connect error frames are app events, not
|
||||
// auth failures — let the controller react.
|
||||
_events.tryEmit(frame)
|
||||
}
|
||||
TYPE_PONG -> Unit
|
||||
else -> {
|
||||
_events.tryEmit(frame)
|
||||
frame.id?.let { id ->
|
||||
pending[id]?.complete(frame)
|
||||
// M4: terminal frame of a pull stream — close
|
||||
// the chunk channel so the pull loop exits.
|
||||
if (frame.type == TYPE_MEDIA_PULL_END) {
|
||||
(binarySession as? BinarySession.Pulling)?.let {
|
||||
it.chunks.close()
|
||||
binarySession = null
|
||||
}
|
||||
}
|
||||
attempt = 0
|
||||
hasConnected = true
|
||||
sseFailures = 0
|
||||
usingLongPoll = false
|
||||
httpCursor = store.syncCursor
|
||||
lastFrameMs = nowMs()
|
||||
// Provisional Connected state (previous caps/channels) until the
|
||||
// SSE hello arrives with the real ones.
|
||||
val prev = _state.value
|
||||
_state.value =
|
||||
State.Connected(
|
||||
caps = (prev as? State.Connected)?.caps ?: ServerCaps(),
|
||||
channels = (prev as? State.Connected)?.channels ?: emptyList(),
|
||||
lastPushedCursor = (prev as? State.Connected)?.lastPushedCursor ?: 0,
|
||||
)
|
||||
// Run the HTTP receive loop (SSE/long-poll) until cancelled.
|
||||
coroutineScope {
|
||||
val receiveJob = launch { httpReceiveLoop(gw) }
|
||||
// Dead-stream watchdog: the SSE read timeout (45 s) is the
|
||||
// only in-stream dead-connection detector; probe /v1/health
|
||||
// in parallel so a dropped network flips the state to
|
||||
// Reconnecting within ~20 s (2 failed probes) instead of 45,
|
||||
// and a stuck stream can't keep a stale "Connected".
|
||||
var probeFailures = 0
|
||||
while (receiveJob.isActive) {
|
||||
delay(10_000)
|
||||
val ok =
|
||||
try {
|
||||
gw.health()
|
||||
} catch (e: Exception) {
|
||||
if (failTls(e)) {
|
||||
receiveJob.cancel()
|
||||
break
|
||||
}
|
||||
false
|
||||
}
|
||||
probeFailures = if (ok) 0 else probeFailures + 1
|
||||
if (probeFailures >= 2) {
|
||||
receiveJob.cancel()
|
||||
break
|
||||
}
|
||||
// Stale-stream watchdog: the gateway is up (health ok) but
|
||||
// the receive stream has delivered no frames for a while —
|
||||
// a live-but-dead connection the read timeout can't see.
|
||||
// Force a fresh (re)connect so parked frames (e.g. our own
|
||||
// echo) are re-delivered from the outbox.
|
||||
if (lastFrameMs > 0L && nowMs() - lastFrameMs > STALE_STREAM_TIMEOUT_MS) {
|
||||
IrisLog.w("receive stream stale (no frames for ${STALE_STREAM_TIMEOUT_MS}ms); forcing reconnect")
|
||||
receiveJob.cancel()
|
||||
break
|
||||
}
|
||||
}
|
||||
receiveJob.join()
|
||||
}
|
||||
// Terminal failures: don't redial with the same bad token / the
|
||||
// same untrusted certificate (the UI asks the user to act).
|
||||
if (_state.value is State.AuthFailed || _state.value is State.TlsConfirmRequired) return
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
|
||||
lastLiveness = TimeSource.Monotonic.markNow()
|
||||
// M4: binary frames belong to the active pull stream
|
||||
// (uploads are outbound; stray inbound chunks are dropped).
|
||||
(binarySession as? BinarySession.Pulling)
|
||||
?.chunks
|
||||
?.trySend(bytes.toByteArray())
|
||||
}
|
||||
// ── HTTP receive leg ──────────────────────────────────────────────────
|
||||
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
||||
IrisLog.w("ws closed code=$code reason=\"$reason\"")
|
||||
closed.complete(Unit)
|
||||
}
|
||||
/** Lazily build the HTTP client from the stored URL. Synchronized: two
|
||||
* threads racing the check-then-create would leak a gateway (and its
|
||||
* OkHttp clients). */
|
||||
private fun httpGateway(): HttpGateway? =
|
||||
synchronized(this) {
|
||||
val url = store.serverUrl.trim()
|
||||
val token = store.deviceToken.ifBlank { store.token }
|
||||
if (url.isBlank() || token.isBlank()) return@synchronized null
|
||||
http
|
||||
?: HttpGateway(
|
||||
client,
|
||||
HttpGateway.deriveHttpUrl(url),
|
||||
// Live provider: a device token minted by the next
|
||||
// hello.ack is picked up without rebuilding the client.
|
||||
token = { store.deviceToken.ifBlank { store.token } },
|
||||
store.deviceId,
|
||||
deviceName = store.deviceName,
|
||||
fcmToken = { store.fcmToken.ifBlank { null } },
|
||||
ntfyTopic = { store.ntfyTopic.ifBlank { null } },
|
||||
).also { http = it }
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
|
||||
IrisLog.e("ws failure: ${t.javaClass.simpleName}: ${t.message} (http=${response?.code})")
|
||||
fail.complete(t.message ?: "connection failed")
|
||||
closed.complete(Unit)
|
||||
/**
|
||||
* The HTTP receive loop: SSE by default; after two consecutive SSE open
|
||||
* failures (buffering proxy) it switches to long-poll until the next full
|
||||
* (re)connect (docs/19 §19.6). Runs until the coroutine is cancelled.
|
||||
*/
|
||||
private suspend fun httpReceiveLoop(gw: HttpGateway) {
|
||||
var backoff = 1_000L
|
||||
while (currentCoroutineContext().isActive) {
|
||||
if (usingLongPoll) {
|
||||
try {
|
||||
val res = gw.poll(httpCursor)
|
||||
res.frames.forEach { emitHttpFrame(it) }
|
||||
if (res.cursor > httpCursor) httpCursor = res.cursor
|
||||
// The poll answered: the link is back (long-poll has no
|
||||
// hello — restore the Connected state from the last one).
|
||||
restoreConnected()
|
||||
} catch (e: HttpGateway.HttpAuthException) {
|
||||
_state.value = State.AuthFailed("gateway rejected the pairing token (HTTP 401)")
|
||||
return
|
||||
} catch (e: Exception) {
|
||||
if (failTls(e)) return
|
||||
markStreamLost()
|
||||
IrisLog.w("http poll failed: ${e.message}")
|
||||
delay(backoff)
|
||||
backoff = minOf(backoff * 2, 15_000)
|
||||
}
|
||||
},
|
||||
)
|
||||
socket = ws
|
||||
|
||||
val winner = CompletableDeferred<DialResult>()
|
||||
helloAck.invokeOnCompletion { e ->
|
||||
if (e == null) {
|
||||
val ack = helloAck.getCompleted()
|
||||
_state.value = State.Connected(ack.serverCaps, ack.channels, ack.lastPushedCursor)
|
||||
// M5: reconnect catch-up — replay frames parked while offline.
|
||||
val local = store.syncCursor
|
||||
if (local < ack.syncCursor) {
|
||||
val id = nextRequestId++
|
||||
ws.send(syncFrame(id, local).toWire())
|
||||
} else {
|
||||
try {
|
||||
gw.events(
|
||||
cursor = httpCursor,
|
||||
onHello = { onHttpHello(it) },
|
||||
onFrame = { emitHttpFrame(it) },
|
||||
onCursor = { if (it > httpCursor) httpCursor = it },
|
||||
// A keep-alive comment proves the stream is alive —
|
||||
// count it toward liveness so an idle-but-healthy
|
||||
// stream isn't force-reconnected by the stale
|
||||
// watchdog every 3 minutes.
|
||||
onKeepAlive = { lastFrameMs = nowMs() },
|
||||
)
|
||||
// Clean EOF: back off briefly so a server that keeps
|
||||
// closing cleanly can't tight-loop the reconnect.
|
||||
backoff = 1_000L
|
||||
delay(backoff)
|
||||
} catch (e: HttpGateway.HttpAuthException) {
|
||||
_state.value = State.AuthFailed("gateway rejected the pairing token (HTTP 401)")
|
||||
return
|
||||
} catch (e: Exception) {
|
||||
if (failTls(e)) return
|
||||
sseFailures++
|
||||
markStreamLost()
|
||||
if (sseFailures >= 2) {
|
||||
// SSE seems blocked: switch to long-poll.
|
||||
usingLongPoll = true
|
||||
continue
|
||||
}
|
||||
IrisLog.w("sse read failed: ${e.message}")
|
||||
delay(backoff)
|
||||
backoff = minOf(backoff * 2, 15_000)
|
||||
}
|
||||
winner.complete(DialResult.Connected)
|
||||
}
|
||||
}
|
||||
authError.invokeOnCompletion { e ->
|
||||
if (e == null) winner.complete(DialResult.AuthFailed(authError.getCompleted()))
|
||||
}
|
||||
|
||||
/** The SSE `event: hello` (the HTTP hello.ack). */
|
||||
private fun onHttpHello(ack: HelloAckPayload) {
|
||||
lastAck = ack
|
||||
// Per-device token (docs/09 §9.3): minted at pairing, stable across
|
||||
// (re)connects. Store it — from the next request on the app presents
|
||||
// it instead of the shared IRIS_TOKEN, so the gateway can revoke
|
||||
// THIS device without touching the others.
|
||||
if (ack.deviceToken.isNotBlank() && ack.deviceToken != store.deviceToken) {
|
||||
store.deviceToken = ack.deviceToken
|
||||
}
|
||||
fail.invokeOnCompletion { e ->
|
||||
if (e == null) winner.complete(DialResult.Failed(fail.getCompleted()))
|
||||
val connected = State.Connected(ack.serverCaps, ack.channels, ack.lastPushedCursor)
|
||||
_state.value = connected
|
||||
// M5: reconnect catch-up — replay frames parked while offline.
|
||||
val local = store.syncCursor
|
||||
if (local < ack.syncCursor) {
|
||||
val id = nextId()
|
||||
scope.launch { httpGateway()?.postFrame(syncFrame(id, local)) }
|
||||
}
|
||||
val result = withTimeoutOrNull(15_000) { winner.await() }
|
||||
?: DialResult.Failed("timeout waiting for hello.ack")
|
||||
return Dial(result, ws, closed)
|
||||
// Prompt fast path (before the possibly-starved state collector).
|
||||
onHelloAck?.invoke(connected)
|
||||
}
|
||||
|
||||
/** The receive stream just died: don't keep claiming "Connected" while
|
||||
* between attempts (a stale green dot through a Wi-Fi drop). */
|
||||
private fun markStreamLost() {
|
||||
if (_state.value is State.Connected) _state.value = State.Reconnecting
|
||||
}
|
||||
|
||||
/** The receive stream is open again (long-poll answered): the link is
|
||||
* back. Long-poll has no hello, so restore the Connected state from the
|
||||
* last hello.ack (the SSE path gets a fresh one). Fire [onHelloAck] too:
|
||||
* the long-poll path has no `event: hello`, so without this the app's
|
||||
* "on connected" side effects (resend queued offline sends, load the
|
||||
* active lane's history) never run when a gateway restart lands while
|
||||
* the app is on the long-poll fallback — queued messages would sit at
|
||||
* "sending…" forever until an app restart (issue #6). */
|
||||
private fun restoreConnected() {
|
||||
if (_state.value !is State.Reconnecting) return
|
||||
val connected =
|
||||
lastAck?.let { State.Connected(it.serverCaps, it.channels, it.lastPushedCursor) }
|
||||
?: State.Connected(ServerCaps(), emptyList())
|
||||
_state.value = connected
|
||||
onHelloAck?.invoke(connected)
|
||||
}
|
||||
|
||||
/** Deliver an HTTP-leg frame to the same sinks as any other frame. */
|
||||
private fun emitHttpFrame(frame: Frame) {
|
||||
lastFrameMs = nowMs()
|
||||
if (!_events.tryEmit(frame)) {
|
||||
// The collector is starved beyond the 128-frame buffer: the frame
|
||||
// is dropped. Log it — a silent drop here loses user-visible
|
||||
// content (echoes, deltas, notifications).
|
||||
IrisLog.e("events buffer full — dropped frame ${frame.type} (id=${frame.id})")
|
||||
}
|
||||
}
|
||||
|
||||
/** Deliver the POST body's synchronous reply (or null) and handle a 401.
|
||||
* Shared by [sendMessage] and [sendFrame]. */
|
||||
private fun handlePostResult(res: HttpGateway.PostResult?) {
|
||||
res?.frame?.let { emitHttpFrame(it) }
|
||||
if (res?.status == 401) {
|
||||
_state.value = State.AuthFailed("gateway rejected the pairing token (HTTP 401)")
|
||||
}
|
||||
}
|
||||
|
||||
/** Terminal TLS failure: the presented certificate is untrusted and not
|
||||
* the pinned one (docs/09 §9.4). Retry can't succeed — stop the connect
|
||||
* loop and let the UI ask the user to confirm the fingerprint. True when
|
||||
* the state was set. */
|
||||
private fun failTls(e: Exception): Boolean {
|
||||
val tls = tlsFingerprintRequired(e) ?: return false
|
||||
IrisLog.w("tls: untrusted gateway certificate (fingerprint ${tls.fingerprint})")
|
||||
_state.value = State.TlsConfirmRequired(tls.fingerprint)
|
||||
return true
|
||||
}
|
||||
|
||||
// ── Outbound ──────────────────────────────────────────────────────────
|
||||
|
||||
/** Send a text message (fire-and-forget; the server echoes it back).
|
||||
* M4: [mediaRefs] reference completed uploads (media.upload.ack refs).
|
||||
* [autoThread] asks the gateway to mint a fresh thread for the message
|
||||
* (auto-threading, docs/06 §6.3). */
|
||||
* [mediaRefs] reference completed uploads (POST /v1/media refs).
|
||||
* [autoThread] asks the gateway to mint a fresh thread for the message
|
||||
* (auto-threading, docs/06 §6.3).
|
||||
* [onResult] is called with the POST's HTTP status — 0 means "no
|
||||
* response" (not connected, or the network failed); 2xx means the
|
||||
* gateway accepted it; 4xx is a gateway rejection (error frame already
|
||||
* delivered via [events]). Used to fail the optimistic bubble instead
|
||||
* of leaving it at "sending…" forever. */
|
||||
fun sendMessage(
|
||||
chatId: String,
|
||||
text: String,
|
||||
threadId: String? = null,
|
||||
mediaRefs: List<String> = emptyList(),
|
||||
autoThread: Boolean = false,
|
||||
onResult: ((Int) -> Unit)? = null,
|
||||
) {
|
||||
val ws = socket ?: return
|
||||
val id = nextRequestId++
|
||||
ws.send(messageSendFrame(id, chatId, text, threadId, mediaRefs, autoThread).toWire())
|
||||
if (_state.value !is State.Connected) {
|
||||
onResult?.invoke(0)
|
||||
return
|
||||
}
|
||||
val id = nextId()
|
||||
scope.launch {
|
||||
val res =
|
||||
httpGateway()?.postFrame(
|
||||
messageSendFrame(id, chatId, text, threadId, mediaRefs, autoThread),
|
||||
)
|
||||
// The synchronous reply (e.g. the read receipt, or an error frame
|
||||
// on 4xx) comes back in the POST body, not on the event stream —
|
||||
// deliver it or it is lost (docs/19 §19.7).
|
||||
handlePostResult(res)
|
||||
onResult?.invoke(res?.status ?: 0)
|
||||
}
|
||||
}
|
||||
|
||||
// ── M4: media upload / pull ───────────────────────────────────────────
|
||||
// ── Media upload / pull ───────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Upload a local file as media (docs/07 §7.2): media.upload.start,
|
||||
* 256 KiB binary chunks, media.upload.end {sha256}. Returns the server's
|
||||
* media_ref (for message.send media_refs) on success.
|
||||
* Upload a local file as media via `POST /v1/media` (docs/19 §19.15, v2).
|
||||
* Returns the server's media_ref (for message.send media_refs) on success.
|
||||
*/
|
||||
suspend fun uploadMedia(
|
||||
path: String,
|
||||
@@ -335,163 +506,140 @@ class GatewayClient(
|
||||
filename: String,
|
||||
mediaRef: String,
|
||||
): Result<String> {
|
||||
val ws = socket ?: return Result.failure(IllegalStateException("not connected"))
|
||||
val source = FileSource(path)
|
||||
val size = source.size()
|
||||
if (size <= 0) {
|
||||
source.close()
|
||||
return Result.failure(IllegalStateException("empty file"))
|
||||
}
|
||||
val id = nextRequestId++
|
||||
val reply = CompletableDeferred<Frame>()
|
||||
pending[id] = reply
|
||||
try {
|
||||
ws.send(mediaUploadStartFrame(id, mediaRef, kind, mime, filename, size).toWire())
|
||||
val sha = Sha256()
|
||||
source.use {
|
||||
val buf = ByteArray(UPLOAD_CHUNK_BYTES)
|
||||
while (true) {
|
||||
val n = it.read(buf)
|
||||
if (n < 0) break
|
||||
if (n == 0) continue
|
||||
sha.update(buf, 0, n)
|
||||
ws.send(buf.copyOfRange(0, n).toByteString())
|
||||
}
|
||||
}
|
||||
ws.send(mediaUploadEndFrame(id, mediaRef, sha.hex()).toWire())
|
||||
val frame = withTimeout(UPLOAD_TIMEOUT_MS) { reply.await() }
|
||||
return when (frame.type) {
|
||||
TYPE_MEDIA_UPLOAD_ACK -> {
|
||||
val p = frame.payloadAs<MediaUploadAckPayload>()
|
||||
if (p != null && p.ok) Result.success(p.mediaRef)
|
||||
else Result.failure(IllegalStateException("upload rejected by server"))
|
||||
}
|
||||
TYPE_ERROR -> {
|
||||
val e = frame.payloadAs<ErrorPayload>()
|
||||
Result.failure(IllegalStateException(e?.message ?: "upload failed"))
|
||||
}
|
||||
else -> Result.failure(IllegalStateException("unexpected reply ${frame.type}"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
return Result.failure(e)
|
||||
} finally {
|
||||
pending.remove(id)
|
||||
}
|
||||
val http = httpGateway() ?: return Result.failure(IllegalStateException("not connected"))
|
||||
return http.uploadMedia(path, mime, kind, filename, mediaRef)
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull offered media (docs/07 §7.3): media.pull, then binary frames until
|
||||
* media.pull.end. Each chunk is handed to [onChunk] (write to cache).
|
||||
* Pull offered media via `GET /v1/media/{id}` (docs/19 §19.15, v2). Each
|
||||
* chunk is handed to [onChunk] (write to cache).
|
||||
*/
|
||||
suspend fun pullMedia(mediaId: String, onChunk: suspend (ByteArray) -> Unit): Result<Unit> =
|
||||
suspend fun pullMedia(
|
||||
mediaId: String,
|
||||
onChunk: suspend (ByteArray) -> Unit,
|
||||
): Result<Unit> =
|
||||
pullMutex.withLock {
|
||||
val ws = socket ?: return@withLock Result.failure(IllegalStateException("not connected"))
|
||||
val id = nextRequestId++
|
||||
val chunks = Channel<ByteArray>(Channel.UNLIMITED)
|
||||
val end = CompletableDeferred<Frame>()
|
||||
pending[id] = end
|
||||
binarySession = BinarySession.Pulling(id, chunks, end)
|
||||
try {
|
||||
ws.send(mediaPullFrame(id, mediaId).toWire())
|
||||
val frame = withTimeout(PULL_TIMEOUT_MS) {
|
||||
for (chunk in chunks) onChunk(chunk)
|
||||
end.await()
|
||||
}
|
||||
when (frame.type) {
|
||||
TYPE_MEDIA_PULL_END -> {
|
||||
val p = frame.payloadAs<MediaPullEndPayload>()
|
||||
if (p != null && p.ok) Result.success(Unit)
|
||||
else Result.failure(IllegalStateException("pull failed"))
|
||||
}
|
||||
TYPE_ERROR -> {
|
||||
val e = frame.payloadAs<ErrorPayload>()
|
||||
Result.failure(IllegalStateException(e?.message ?: "pull failed"))
|
||||
}
|
||||
else -> Result.failure(IllegalStateException("unexpected reply ${frame.type}"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
} finally {
|
||||
pending.remove(id)
|
||||
chunks.cancel()
|
||||
val s = binarySession
|
||||
if (s is BinarySession.Pulling && s.requestId == id) binarySession = null
|
||||
}
|
||||
val http = httpGateway() ?: return@withLock Result.failure(IllegalStateException("not connected"))
|
||||
http.pullMedia(mediaId) { chunk -> onChunk(chunk) }
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** One WS binary frame carries at most this many media bytes (docs/07 §7.5). */
|
||||
const val UPLOAD_CHUNK_BYTES = 256 * 1024
|
||||
const val UPLOAD_TIMEOUT_MS = 120_000L
|
||||
const val PULL_TIMEOUT_MS = 300_000L
|
||||
/** No frames (or keep-alive comments) from the receive stream for
|
||||
* this long (gateway still
|
||||
* healthy) = stale stream: force a fresh (re)connect. 3 min keeps an
|
||||
* idle app from churning while still recovering a stuck stream well
|
||||
* before a user notices (issue #6). */
|
||||
const val STALE_STREAM_TIMEOUT_MS = 180_000L
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an arbitrary frame with a fresh request id (fire-and-forget).
|
||||
* The server replies (or broadcasts) a frame carrying the same id; the
|
||||
* app reconciles from [events]. Returns the id used, or -1 if not connected.
|
||||
* Send an arbitrary frame with a fresh request id (fire-and-forget). The
|
||||
* server replies (or broadcasts) a frame carrying the same id; the app
|
||||
* reconciles from [events]. Returns the id used, or -1 if not connected.
|
||||
*/
|
||||
fun sendFrame(frame: Frame): Int {
|
||||
val ws = socket ?: return -1
|
||||
val id = nextRequestId++
|
||||
ws.send(frame.copy(id = id).toWire())
|
||||
return id
|
||||
}
|
||||
|
||||
/** Send a ping (heartbeat). */
|
||||
fun ping() {
|
||||
socket?.send(pingFrame().toWire())
|
||||
}
|
||||
|
||||
/** True when the socket has been silent for [timeoutMs] (heartbeat reap). */
|
||||
fun isStale(timeoutMs: Long = 60_000): Boolean =
|
||||
_state.value is State.Connected && lastLiveness.elapsedNow().inWholeMilliseconds > timeoutMs
|
||||
|
||||
fun reapStale() {
|
||||
if (isStale()) {
|
||||
socket?.close(1000, "heartbeat timeout")
|
||||
if (_state.value !is State.Connected) return -1
|
||||
val id = nextId()
|
||||
scope.launch {
|
||||
val res = httpGateway()?.postFrame(frame.copy(id = id))
|
||||
// Single-frame responses (commands.catalog, channel.list, search,
|
||||
// history, sync, errors) come back in the POST body, not on the
|
||||
// event stream — deliver it or it is lost (docs/19 §19.7).
|
||||
handlePostResult(res)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// ── One-shot hello test (Connect screen) ──────────────────────────────
|
||||
|
||||
/**
|
||||
* Real `hello` test: dial, wait for hello.ack (or auth error), close.
|
||||
* Exercises the auth leg, not just TCP (docs/10 §10.8).
|
||||
* Real connection test: health probe + SSE open. The auth leg is proven
|
||||
* by the stream being accepted (200 vs 401) — we do NOT wait for the
|
||||
* hello event, because the server replays the outbox (up to 72 h of
|
||||
* frames) before it and a large outbox would time out a healthy gateway
|
||||
* (docs/10 §10.8).
|
||||
*/
|
||||
suspend fun testHello(url: String, token: String): Result<Unit> {
|
||||
val dial = dial(url, token)
|
||||
return when (val result = dial.result) {
|
||||
DialResult.Connected -> {
|
||||
dial.socket.close(1000, "test complete")
|
||||
Result.success(Unit)
|
||||
}
|
||||
is DialResult.AuthFailed -> Result.failure(IllegalStateException(result.message))
|
||||
is DialResult.Failed -> Result.failure(IllegalStateException(result.message))
|
||||
}
|
||||
}
|
||||
|
||||
// ── Heartbeat job ─────────────────────────────────────────────────────
|
||||
|
||||
fun startHeartbeat() {
|
||||
scope.launch {
|
||||
while (isActive) {
|
||||
delay(20_000)
|
||||
if (_state.value is State.Connected) {
|
||||
ping()
|
||||
reapStale()
|
||||
suspend fun testHello(
|
||||
url: String,
|
||||
token: String,
|
||||
): Result<Unit> {
|
||||
val gw =
|
||||
HttpGateway(
|
||||
client,
|
||||
HttpGateway.deriveHttpUrl(url),
|
||||
// An already-paired device presents its per-device token
|
||||
// (docs/09 §9.3); a fresh pairing falls back to the entered
|
||||
// shared token (bootstrap).
|
||||
token = { store.deviceToken.ifBlank { token } },
|
||||
store.deviceId,
|
||||
deviceName = store.deviceName,
|
||||
fcmToken = { store.fcmToken.ifBlank { null } },
|
||||
ntfyTopic = { store.ntfyTopic.ifBlank { null } },
|
||||
)
|
||||
return try {
|
||||
if (!gw.health()) {
|
||||
Result.failure(IllegalStateException("gateway unreachable"))
|
||||
} else {
|
||||
// Open the SSE stream briefly: 200 = auth leg proven, 401 =
|
||||
// bad token. Don't wait for the hello (outbox replay first).
|
||||
val opened = CompletableDeferred<Unit>()
|
||||
val job =
|
||||
scope.launch {
|
||||
try {
|
||||
gw.events(
|
||||
cursor = store.syncCursor,
|
||||
onOpen = { opened.complete(Unit) },
|
||||
onHello = { },
|
||||
onFrame = { },
|
||||
onCursor = { },
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
opened.completeExceptionally(e)
|
||||
}
|
||||
}
|
||||
try {
|
||||
if (withTimeoutOrNull(10_000) { opened.await() } == null) {
|
||||
Result.failure(IllegalStateException("timeout opening the event stream"))
|
||||
} else {
|
||||
Result.success(Unit)
|
||||
}
|
||||
} catch (e: HttpGateway.HttpAuthException) {
|
||||
Result.failure(IllegalStateException("unauthorized — check the pairing token"))
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// Unwrap the pinning manager's signal so the Connect
|
||||
// screen can offer the fingerprint confirm dialog.
|
||||
Result.failure(tlsFingerprintRequired(e) ?: IllegalStateException("connection failed: ${e.message}"))
|
||||
} finally {
|
||||
job.cancel()
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.failure(tlsFingerprintRequired(e) ?: e)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
/** Backoff that wakes early when [poke] is called (app foregrounded). */
|
||||
private suspend fun backoffOrWake(ms: Long) {
|
||||
var remaining = ms
|
||||
while (remaining > 0 && currentCoroutineContext().isActive) {
|
||||
delay(minOf(remaining, 500L))
|
||||
if (wakeRequested) {
|
||||
wakeRequested = false
|
||||
return
|
||||
}
|
||||
remaining -= 500L
|
||||
}
|
||||
}
|
||||
|
||||
private fun backoffMs(attempt: Int): Long {
|
||||
val base = 1_000L * (1L shl minOf(attempt, 5)) // 1s..32s
|
||||
val capped = minOf(base, 30_000L)
|
||||
return capped + Random.nextLong(0, 500)
|
||||
}
|
||||
}
|
||||
|
||||
private fun Frame.toWire(): String = IrisJson.instance.encodeToString(Frame.serializer(), this)
|
||||
private fun nowMs(): Long = nowMillis()
|
||||
}
|
||||
@@ -0,0 +1,507 @@
|
||||
package iris.net
|
||||
|
||||
import iris.AppVersion
|
||||
import iris.media.Sha256
|
||||
import iris.media.isValidMediaId
|
||||
import iris.protocol.ErrorPayload
|
||||
import iris.protocol.Frame
|
||||
import iris.protocol.HelloAckPayload
|
||||
import iris.protocol.IrisJson
|
||||
import iris.protocol.MediaUploadAckPayload
|
||||
import iris.util.IrisLog
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.json.jsonArray
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import okhttp3.Headers
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.asRequestBody
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* HTTP transport client (docs/19) — the only transport.
|
||||
*
|
||||
* The app sends over `POST /v1/frame` and receives over SSE
|
||||
* `GET /v1/events` (or long-poll `GET /v1/poll` where SSE is blocked);
|
||||
* media travels via `POST/GET /v1/media`.
|
||||
*
|
||||
* [events] is ONE SSE connection attempt (blocking read on
|
||||
* [Dispatchers.IO]); [GatewayClient] wraps it in a retry loop and tracks
|
||||
* the resume cursor via the [events] `onCursor` callback (SSE `id` =
|
||||
* outbox cursor, so resume is just the last seen id).
|
||||
*/
|
||||
class HttpGateway(
|
||||
private val client: OkHttpClient,
|
||||
private val baseUrl: String,
|
||||
/** Live auth-token provider, read per request: the per-device token
|
||||
* (docs/09 §9.3) when the gateway minted one, else the shared
|
||||
* IRIS_TOKEN (bootstrap). A lambda so a freshly issued device token is
|
||||
* picked up without rebuilding the client. */
|
||||
private val token: () -> String,
|
||||
private val deviceId: String,
|
||||
/** Human-readable device name (sent as `X-Iris-Device-Name`; the gateway
|
||||
* upserts it into the device registry on every SSE open — the HTTP
|
||||
* equivalent of the old WS hello upsert). */
|
||||
private val deviceName: String? = null,
|
||||
/** Live push-token providers, read per request so a rotated FCM token or
|
||||
* a fresh ntfy topic is picked up without rebuilding the client. */
|
||||
private val fcmToken: () -> String? = { null },
|
||||
private val ntfyTopic: () -> String? = { null },
|
||||
) {
|
||||
/** The gateway rejected the pairing token (HTTP 401). Terminal: retrying
|
||||
* with the same token can't succeed. */
|
||||
class HttpAuthException : IOException("unauthorized (HTTP 401)")
|
||||
|
||||
// OkHttp's default read timeout (10 s) is shorter than the gateway's SSE
|
||||
// heartbeat (15 s) and the long-poll hold (25 s) — per-purpose clients
|
||||
// with extended call timeouts (see the *Client() helpers below).
|
||||
private val healthClient: OkHttpClient = client.healthClient()
|
||||
private val streamClient: OkHttpClient = client.streamClient()
|
||||
private val pollClient: OkHttpClient = client.pollClient()
|
||||
private val mediaClient: OkHttpClient = client.mediaClient()
|
||||
|
||||
/** Close the per-purpose clients (and their idle connections). The
|
||||
* shared base [client] is owned by the caller. */
|
||||
fun close() {
|
||||
healthClient.dispatcher.executorService.shutdown()
|
||||
streamClient.dispatcher.executorService.shutdown()
|
||||
pollClient.dispatcher.executorService.shutdown()
|
||||
mediaClient.dispatcher.executorService.shutdown()
|
||||
healthClient.connectionPool.evictAll()
|
||||
streamClient.connectionPool.evictAll()
|
||||
pollClient.connectionPool.evictAll()
|
||||
mediaClient.connectionPool.evictAll()
|
||||
}
|
||||
|
||||
/** POST /v1/frame result. [frame] is the handler's synchronous reply
|
||||
* (error frame on 4xx, e.g. read.receipt on 200) or null for a plain
|
||||
* 202 accept-and-ack. */
|
||||
data class PostResult(
|
||||
val ok: Boolean,
|
||||
val status: Int,
|
||||
val frame: Frame?,
|
||||
)
|
||||
|
||||
/** Long-poll result: new high-water [cursor] + frames with cursor >
|
||||
* the requested one (may be empty at timeout). */
|
||||
data class PollResult(
|
||||
val cursor: Long,
|
||||
val frames: List<Frame>,
|
||||
)
|
||||
|
||||
companion object {
|
||||
val JSON = "application/json".toMediaType()
|
||||
|
||||
/** Default port of the gateway's HTTP leg (WS default is 8790). */
|
||||
const val DEFAULT_PORT = 8791
|
||||
|
||||
/** Media transfer chunk (docs/07 §7.5). */
|
||||
private const val MEDIA_CHUNK_BYTES = 256 * 1024
|
||||
|
||||
/**
|
||||
* Derive the HTTP base URL from the stored WS URL (docs/19 §19.4):
|
||||
* `ws(s)://host[:port]/ws` -> `http(s)://host:8791`. The WS port is
|
||||
* a different service, so the port is always replaced with the
|
||||
* HTTP leg's default. Pure function (unit-tested).
|
||||
*/
|
||||
fun deriveHttpUrl(wsUrl: String): String {
|
||||
val u = wsUrl.trim()
|
||||
val (scheme, rest) =
|
||||
when {
|
||||
u.startsWith("wss://") -> "https" to u.removePrefix("wss://")
|
||||
u.startsWith("ws://") -> "http" to u.removePrefix("ws://")
|
||||
else -> return u // already http(s)
|
||||
}
|
||||
val authority = rest.substringBefore('/')
|
||||
val host = authority.substringBefore(':')
|
||||
return "$scheme://$host:$DEFAULT_PORT"
|
||||
}
|
||||
}
|
||||
|
||||
private fun authHeaders(): Headers {
|
||||
val b =
|
||||
Headers
|
||||
.Builder()
|
||||
.add("Authorization", "Bearer ${token()}")
|
||||
.add("X-Iris-Device", deviceId)
|
||||
// Device registration (docs/19): the gateway upserts name + push
|
||||
// tokens from these headers on every SSE open (COALESCE — absent
|
||||
// headers never clobber a newer fcm.register value).
|
||||
deviceName?.takeIf { it.isNotBlank() }?.let { b.add("X-Iris-Device-Name", it) }
|
||||
fcmToken()?.takeIf { !it.isNullOrBlank() }?.let { b.add("X-Iris-Fcm-Token", it) }
|
||||
ntfyTopic()?.takeIf { it.isNotBlank() }?.let { b.add("X-Iris-Ntfy-Topic", it) }
|
||||
// Release version (repo-root VERSION baked in at build time); the
|
||||
// gateway stores it in the device registry (docs/04 hello.ack note).
|
||||
b.add("X-Iris-App-Version", AppVersion.VERSION)
|
||||
return b.build()
|
||||
}
|
||||
|
||||
/** Parse a response body as a protocol frame (null when not a frame,
|
||||
* e.g. the plain `{"ok":true}` ack). */
|
||||
private fun parseFrame(body: String): Frame? =
|
||||
try {
|
||||
if (body.startsWith("{")) {
|
||||
val obj = IrisJson.instance.parseToJsonElement(body)
|
||||
if (obj.jsonObject.containsKey("type")) {
|
||||
IrisJson.instance.decodeFromJsonElement(Frame.serializer(), obj)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
|
||||
/** Liveness probe (unauthenticated by design). True on 200. */
|
||||
suspend fun health(): Boolean =
|
||||
withContext(Dispatchers.IO) {
|
||||
val request =
|
||||
Request
|
||||
.Builder()
|
||||
.url("$baseUrl/v1/health")
|
||||
.build()
|
||||
healthClient
|
||||
.newCall(request)
|
||||
.execute()
|
||||
.use { response ->
|
||||
response.body?.close()
|
||||
response.code == 200
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /v1/frame (accept-and-ack, docs/19 §19.7). 2xx -> [PostResult.ok]
|
||||
* (with the synchronous reply frame when the handler sent one); 4xx ->
|
||||
* the error frame as the body. Network failures (timeout, reset, DNS —
|
||||
* common when mobile Wi-Fi half-sleeps) do NOT throw: they come back as
|
||||
* [PostResult] with [PostResult.status] 0 ("no HTTP response"). The
|
||||
* callers are fire-and-forget coroutines — an uncaught exception here
|
||||
* kills the app process.
|
||||
*/
|
||||
suspend fun postFrame(frame: Frame): PostResult =
|
||||
withContext(Dispatchers.IO) {
|
||||
val wire = IrisJson.instance.encodeToString(Frame.serializer(), frame)
|
||||
val request =
|
||||
Request
|
||||
.Builder()
|
||||
.url("$baseUrl/v1/frame")
|
||||
.headers(authHeaders())
|
||||
.post(wire.toRequestBody(JSON))
|
||||
.build()
|
||||
try {
|
||||
client
|
||||
.newCall(request)
|
||||
.execute()
|
||||
.use { response ->
|
||||
val body = response.body?.string().orEmpty()
|
||||
val parsed = parseFrame(body)
|
||||
PostResult(response.isSuccessful, response.code, parsed)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
IrisLog.w("postFrame ${frame.type} failed: ${e.message}")
|
||||
PostResult(ok = false, status = 0, frame = null)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One SSE connection attempt: outbox catch-up from [cursor], then live
|
||||
* frames. [onOpen] fires as soon as the stream is accepted (200 — the auth
|
||||
* leg is proven; the server may still replay a large outbox before the
|
||||
* hello); [onHello] fires for `event: hello` (the HTTP hello.ack);
|
||||
* [onFrame] for `event: frame`; [onCursor] with the SSE `id` (outbox
|
||||
* cursor) when present; [onKeepAlive] for SSE comment lines (the
|
||||
* heartbeat) so callers can count keep-alives toward liveness. Returns
|
||||
* on clean EOF; throws [IOException] on open/read failure. Callbacks run
|
||||
* on the IO thread.
|
||||
*/
|
||||
suspend fun events(
|
||||
cursor: Long,
|
||||
onOpen: (() -> Unit)? = null,
|
||||
onHello: (HelloAckPayload) -> Unit,
|
||||
onFrame: (Frame) -> Unit,
|
||||
onCursor: (Long) -> Unit,
|
||||
onKeepAlive: (() -> Unit)? = null,
|
||||
) {
|
||||
withContext(Dispatchers.IO) {
|
||||
val request =
|
||||
Request
|
||||
.Builder()
|
||||
.url("$baseUrl/v1/events?cursor=$cursor")
|
||||
.headers(authHeaders())
|
||||
.build()
|
||||
streamClient
|
||||
.newCall(request)
|
||||
.execute()
|
||||
.use { response ->
|
||||
if (response.code == 401) throw HttpAuthException()
|
||||
if (!response.isSuccessful) {
|
||||
throw IOException("SSE open failed: HTTP ${response.code}")
|
||||
}
|
||||
onOpen?.invoke()
|
||||
val source = response.body?.source() ?: throw IOException("empty SSE body")
|
||||
var eventId: String? = null
|
||||
val dataLines = mutableListOf<String>()
|
||||
while (true) {
|
||||
val line = source.readUtf8Line() ?: break // EOF
|
||||
when {
|
||||
line.isEmpty() -> {
|
||||
if (dataLines.isNotEmpty()) {
|
||||
val data = dataLines.joinToString("\n")
|
||||
try {
|
||||
val frame =
|
||||
IrisJson.instance.decodeFromString(
|
||||
Frame.serializer(),
|
||||
data,
|
||||
)
|
||||
when (eventId) {
|
||||
"hello" -> {
|
||||
onHello(
|
||||
frame.payloadAs<HelloAckPayload>()
|
||||
?: HelloAckPayload(),
|
||||
)
|
||||
}
|
||||
|
||||
else -> {
|
||||
onFrame(frame)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
IrisLog.e("sse frame decode failed: $e :: ${data.take(120)}")
|
||||
}
|
||||
}
|
||||
eventId = null
|
||||
dataLines.clear()
|
||||
}
|
||||
|
||||
line.startsWith(":") -> {
|
||||
// heartbeat comment
|
||||
onKeepAlive?.invoke()
|
||||
}
|
||||
|
||||
line.startsWith("id:") -> {
|
||||
line
|
||||
.removePrefix("id:")
|
||||
.trim()
|
||||
.toLongOrNull()
|
||||
?.let(onCursor)
|
||||
}
|
||||
|
||||
line.startsWith("event:") -> {
|
||||
eventId = line.removePrefix("event:").trim()
|
||||
}
|
||||
|
||||
line.startsWith("data:") -> {
|
||||
dataLines.add(line.removePrefix("data:").removePrefix(" "))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Long-poll (docs/19 §19.6): the server holds the request up to 25 s.
|
||||
* Returns the new high-water cursor + any frames with cursor > [cursor].
|
||||
*/
|
||||
suspend fun poll(cursor: Long): PollResult =
|
||||
withContext(Dispatchers.IO) {
|
||||
val request =
|
||||
Request
|
||||
.Builder()
|
||||
.url("$baseUrl/v1/poll?cursor=$cursor")
|
||||
.headers(authHeaders())
|
||||
.build()
|
||||
pollClient
|
||||
.newCall(request)
|
||||
.execute()
|
||||
.use { response ->
|
||||
if (response.code == 401) throw HttpAuthException()
|
||||
if (!response.isSuccessful) {
|
||||
throw IOException("poll failed: HTTP ${response.code}")
|
||||
}
|
||||
val body = response.body?.string().orEmpty()
|
||||
val obj = IrisJson.instance.parseToJsonElement(body).jsonObject
|
||||
val newCursor = obj["cursor"]?.jsonPrimitive?.content?.toLongOrNull() ?: cursor
|
||||
val frames =
|
||||
obj["frames"]
|
||||
?.jsonArray
|
||||
?.mapNotNull { el ->
|
||||
try {
|
||||
IrisJson.instance.decodeFromJsonElement(Frame.serializer(), el)
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
}.orEmpty()
|
||||
PollResult(newCursor, frames)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload a local file as media (docs/19 §19.15, v2): one `POST /v1/media`
|
||||
* with the whole file as the body and the metadata in `X-Iris-Media-*`
|
||||
* headers (sha256 precomputed in a first pass). Returns the server's
|
||||
* media_ref (for message.send media_refs) on success.
|
||||
*/
|
||||
suspend fun uploadMedia(
|
||||
path: String,
|
||||
mime: String,
|
||||
kind: String,
|
||||
filename: String,
|
||||
mediaRef: String,
|
||||
): Result<String> =
|
||||
withContext(Dispatchers.IO) {
|
||||
val file = File(path)
|
||||
if (!file.isFile() || file.length() <= 0) {
|
||||
return@withContext Result.failure(IllegalStateException("empty file"))
|
||||
}
|
||||
val sha = Sha256()
|
||||
file.inputStream().use { ins ->
|
||||
val buf = ByteArray(MEDIA_CHUNK_BYTES)
|
||||
while (true) {
|
||||
val n = ins.read(buf)
|
||||
if (n < 0) break
|
||||
if (n > 0) sha.update(buf, 0, n)
|
||||
}
|
||||
}
|
||||
val request =
|
||||
Request
|
||||
.Builder()
|
||||
.url("$baseUrl/v1/media")
|
||||
.headers(
|
||||
authHeaders()
|
||||
.newBuilder()
|
||||
.add("X-Iris-Media-Ref", mediaRef)
|
||||
.add("X-Iris-Media-Kind", kind)
|
||||
.add("X-Iris-Media-Filename", filename)
|
||||
.add("X-Iris-Media-Sha256", sha.hex())
|
||||
.build(),
|
||||
).post(file.asRequestBody(mime.toMediaType()))
|
||||
.build()
|
||||
try {
|
||||
mediaClient
|
||||
.newCall(request)
|
||||
.execute()
|
||||
.use { response ->
|
||||
val body = response.body?.string().orEmpty()
|
||||
val frame = parseFrame(body)
|
||||
if (response.isSuccessful) {
|
||||
val p = frame?.payloadAs<MediaUploadAckPayload>()
|
||||
if (p != null && p.ok) {
|
||||
Result.success(p.mediaRef)
|
||||
} else {
|
||||
Result.failure(IllegalStateException("upload rejected by server"))
|
||||
}
|
||||
} else {
|
||||
val e = frame?.payloadAs<ErrorPayload>()
|
||||
Result.failure(
|
||||
IllegalStateException(e?.message ?: "upload failed: HTTP ${response.code}"),
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// Network failure mid-upload: report, don't throw (the caller
|
||||
// is a fire-and-forget coroutine — an uncaught exception kills
|
||||
// the app process).
|
||||
IrisLog.w("media upload failed: ${e.message}")
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull offered media (docs/19 §19.15, v2): `GET /v1/media/{id}`; the
|
||||
* response body is the file, streamed to [onChunk] (write to cache).
|
||||
*/
|
||||
suspend fun pullMedia(
|
||||
mediaId: String,
|
||||
onChunk: suspend (ByteArray) -> Unit,
|
||||
): Result<Unit> =
|
||||
withContext(Dispatchers.IO) {
|
||||
// Server-controlled id: reject path-traversal / URL-breaking
|
||||
// values before they reach the request line (M-2 / S-1).
|
||||
if (!isValidMediaId(mediaId)) {
|
||||
return@withContext Result.failure(IllegalStateException("invalid media id"))
|
||||
}
|
||||
val request =
|
||||
Request
|
||||
.Builder()
|
||||
.url("$baseUrl/v1/media/$mediaId")
|
||||
.headers(authHeaders())
|
||||
.build()
|
||||
try {
|
||||
mediaClient
|
||||
.newCall(request)
|
||||
.execute()
|
||||
.use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
val e = parseFrame(response.body?.string().orEmpty())?.payloadAs<ErrorPayload>()
|
||||
Result.failure(
|
||||
IllegalStateException(e?.message ?: "pull failed: HTTP ${response.code}"),
|
||||
)
|
||||
} else {
|
||||
try {
|
||||
val source = response.body?.source() ?: throw IOException("empty body")
|
||||
val buf = ByteArray(MEDIA_CHUNK_BYTES)
|
||||
while (true) {
|
||||
val n = source.read(buf)
|
||||
if (n < 0) break
|
||||
if (n == 0) continue
|
||||
onChunk(buf.copyOfRange(0, n))
|
||||
}
|
||||
Result.success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// Network failure before/while opening the pull: report, don't
|
||||
// throw (fire-and-forget caller — uncaught = process death).
|
||||
IrisLog.w("media pull failed: ${e.message}")
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-purpose OkHttp clients. The base client's DEFAULT read timeout (10 s)
|
||||
* is shorter than the gateway's SSE heartbeat (15 s) and the long-poll hold
|
||||
* (25 s) — it would kill both receive paths while they are simply waiting
|
||||
* for the next byte, so the streaming clients override it. The read timeout
|
||||
* doubles as the dead-stream detector (a healthy SSE stream gets a heartbeat
|
||||
* comment every 15 s; a healthy poll answers within 25 s).
|
||||
*/
|
||||
|
||||
/** SSE: long-lived stream → no call cap; read timeout = 3× the 15 s
|
||||
* heartbeat (detects a dead connection within 45 s). */
|
||||
internal fun OkHttpClient.streamClient(): OkHttpClient =
|
||||
newBuilder()
|
||||
.callTimeout(0, TimeUnit.MILLISECONDS)
|
||||
.readTimeout(45_000, TimeUnit.MILLISECONDS)
|
||||
.build()
|
||||
|
||||
/** Long-poll: the server holds up to 25 s → no call cap; read timeout =
|
||||
* hold + 15 s margin. */
|
||||
internal fun OkHttpClient.pollClient(): OkHttpClient =
|
||||
newBuilder()
|
||||
.callTimeout(0, TimeUnit.MILLISECONDS)
|
||||
.readTimeout(40_000, TimeUnit.MILLISECONDS)
|
||||
.build()
|
||||
|
||||
internal fun OkHttpClient.healthClient(): OkHttpClient =
|
||||
newBuilder()
|
||||
.callTimeout(2_000, TimeUnit.MILLISECONDS)
|
||||
.build()
|
||||
|
||||
/** Media transfers (upload/pull) can take a while on large files. */
|
||||
internal fun OkHttpClient.mediaClient(): OkHttpClient =
|
||||
newBuilder()
|
||||
.callTimeout(300_000, TimeUnit.MILLISECONDS)
|
||||
.build()
|
||||
@@ -0,0 +1,96 @@
|
||||
package iris.net
|
||||
|
||||
import iris.protocol.IrisJson
|
||||
import iris.util.IrisLog
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
|
||||
/**
|
||||
* Latest-release check (docs/04 hello.ack note): the repo is public on Gitea,
|
||||
* so the app can ask for the newest release tag without any token. Settings
|
||||
* shows "vX.Y.Z available" when the running build is older.
|
||||
*
|
||||
* Best-effort by design: any failure (offline, DNS, rate limit) just yields
|
||||
* `null` — the check must never surface an error in the UI.
|
||||
*/
|
||||
object ReleaseCheck {
|
||||
const val LATEST_RELEASE_URL =
|
||||
"https://gitea.zephyre.one/api/v1/repos/ARIA/iris_x_hermes/releases/latest"
|
||||
|
||||
/**
|
||||
* One shared client for the process lifetime: an OkHttpClient owns a
|
||||
* thread pool and connection pool, so it must not be rebuilt per screen
|
||||
* open (and never needs explicit shutdown — the pools idle out). Short
|
||||
* timeouts so a black-holed network can't linger the LaunchedEffect.
|
||||
*/
|
||||
private val client: OkHttpClient =
|
||||
OkHttpClient
|
||||
.Builder()
|
||||
.connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
/**
|
||||
* The latest release version (tag without the leading "v"), or `null`
|
||||
* when the check could not be performed.
|
||||
*/
|
||||
suspend fun latestVersion(): String? =
|
||||
withContext(Dispatchers.IO) {
|
||||
val request =
|
||||
Request
|
||||
.Builder()
|
||||
.url(LATEST_RELEASE_URL)
|
||||
.get()
|
||||
.build()
|
||||
try {
|
||||
client.newCall(request).execute().use { response: Response ->
|
||||
if (!response.isSuccessful) {
|
||||
IrisLog.d("ReleaseCheck: HTTP ${response.code}")
|
||||
return@withContext null
|
||||
}
|
||||
val body = response.body?.string() ?: return@withContext null
|
||||
val tag =
|
||||
IrisJson
|
||||
.instance
|
||||
.parseToJsonElement(body)
|
||||
.jsonObject
|
||||
.get("tag_name")
|
||||
?.jsonPrimitive
|
||||
?.content
|
||||
.orEmpty()
|
||||
tag.removePrefix("v").ifBlank { null }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
IrisLog.d("ReleaseCheck: ${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True when [latest] is a newer release than [running]. Numeric
|
||||
* component-wise comparison (so "0.1.10" > "0.1.9"); anything that does
|
||||
* not parse as dotted numbers is treated as "not newer" — the hint is
|
||||
* best-effort and must never fire for dev builds ahead of the latest
|
||||
* release.
|
||||
*/
|
||||
fun isNewer(
|
||||
latest: String,
|
||||
running: String,
|
||||
): Boolean {
|
||||
val a = latest.split('.').mapNotNull { it.takeWhile(Char::isDigit).toIntOrNull() }
|
||||
val b = running.split('.').mapNotNull { it.takeWhile(Char::isDigit).toIntOrNull() }
|
||||
if (a.isEmpty() || b.isEmpty()) return false
|
||||
val n = maxOf(a.size, b.size)
|
||||
for (i in 0 until n) {
|
||||
val x = a.getOrElse(i) { 0 }
|
||||
val y = b.getOrElse(i) { 0 }
|
||||
if (x != y) return x > y
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package iris.net
|
||||
|
||||
import java.security.KeyStore
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
import java.security.cert.CertificateException
|
||||
import java.security.cert.X509Certificate
|
||||
import javax.net.ssl.SSLContext
|
||||
import javax.net.ssl.SSLSocketFactory
|
||||
import javax.net.ssl.TrustManager
|
||||
import javax.net.ssl.TrustManagerFactory
|
||||
import javax.net.ssl.X509TrustManager
|
||||
|
||||
/**
|
||||
* TLS certificate pinning for self-signed gateways (docs/09 §9.4).
|
||||
*
|
||||
* A gateway behind `IRIS_HTTP_CERT` may present a
|
||||
* self-signed certificate the platform doesn't trust. Instead of forcing the
|
||||
* user to install it into the system trust store, the app shows the
|
||||
* certificate's SHA-256 fingerprint on first pair (SSH host-key style); once
|
||||
* the user confirms it, the fingerprint is pinned in secure storage and
|
||||
* [PinningTrustManager] accepts exactly that certificate from then on.
|
||||
*
|
||||
* Hostname verification is NOT bypassed: OkHttp runs its own hostname check
|
||||
* on top of the trust manager, so a pinned cert still has to match the URL's
|
||||
* host. A *changed* certificate (different fingerprint) fails again with
|
||||
* [TlsFingerprintRequired] — the user must re-confirm, like a changed SSH
|
||||
* host key.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The gateway presented a certificate the platform doesn't trust and that
|
||||
* doesn't match the pinned fingerprint. Carries the SHA-256 fingerprint the
|
||||
* user must confirm. Thrown by [PinningTrustManager] during the handshake;
|
||||
* the JSSE/OkHttp layers wrap it, so find it with [tlsFingerprintRequired].
|
||||
*/
|
||||
class TlsFingerprintRequired(
|
||||
val fingerprint: String,
|
||||
) : CertificateException("gateway certificate not trusted (fingerprint $fingerprint)")
|
||||
|
||||
/**
|
||||
* SHA-256 of the certificate's DER encoding, colon-separated byte pairs
|
||||
* (SSH host-key style) — the string the user verifies on the gateway host.
|
||||
*/
|
||||
fun certFingerprint(cert: X509Certificate): String =
|
||||
MessageDigest
|
||||
.getInstance("SHA-256")
|
||||
.digest(cert.encoded)
|
||||
.joinToString(":") { String.format("%02X", it) }
|
||||
|
||||
/**
|
||||
* Wraps the platform default trust manager:
|
||||
* - CA-signed certs behave exactly as before (the default manager decides).
|
||||
* - A cert the default manager REJECTS is accepted only when its fingerprint
|
||||
* equals the user-confirmed pin ([pinnedFingerprint], read live so a fresh
|
||||
* pin is picked up without rebuilding the client).
|
||||
* - Anything else fails with [TlsFingerprintRequired] carrying the
|
||||
* presented fingerprint, so the UI can offer the confirm dialog.
|
||||
*/
|
||||
class PinningTrustManager(
|
||||
private val pinnedFingerprint: () -> String,
|
||||
) : X509TrustManager {
|
||||
private val default: X509TrustManager = defaultTrustManager()
|
||||
|
||||
override fun checkClientTrusted(
|
||||
chain: Array<X509Certificate>,
|
||||
authType: String,
|
||||
) {
|
||||
default.checkClientTrusted(chain, authType)
|
||||
}
|
||||
|
||||
override fun getAcceptedIssuers(): Array<X509Certificate> = default.acceptedIssuers
|
||||
|
||||
override fun checkServerTrusted(
|
||||
chain: Array<X509Certificate>,
|
||||
authType: String,
|
||||
) {
|
||||
try {
|
||||
default.checkServerTrusted(chain, authType)
|
||||
} catch (e: CertificateException) {
|
||||
val fp = certFingerprint(chain.first())
|
||||
if (pinnedFingerprint().isNotBlank() && fp == pinnedFingerprint()) return
|
||||
throw TlsFingerprintRequired(fp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The platform default server trust manager (the JDK's CA store). */
|
||||
fun defaultTrustManager(): X509TrustManager {
|
||||
val factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
|
||||
factory.init(null as KeyStore?)
|
||||
return (factory.trustManagers.firstOrNull { it is X509TrustManager } as? X509TrustManager)
|
||||
?: error("no X509TrustManager in the default trust store")
|
||||
}
|
||||
|
||||
/** An [SSLSocketFactory] that trusts via [tm] (the pinning manager). */
|
||||
fun pinningSslSocketFactory(tm: X509TrustManager): SSLSocketFactory {
|
||||
val ctx = SSLContext.getInstance("TLS")
|
||||
ctx.init(null, arrayOf<TrustManager>(tm), SecureRandom())
|
||||
return ctx.socketFactory
|
||||
}
|
||||
|
||||
/**
|
||||
* Unwrap a [TlsFingerprintRequired] from a (possibly nested) transport
|
||||
* exception: the trust manager throws it during the handshake and the
|
||||
* JSSE/OkHttp layers wrap it in SSLHandshakeException/IOException. Null when
|
||||
* the failure has nothing to do with an untrusted gateway certificate.
|
||||
*/
|
||||
fun tlsFingerprintRequired(e: Throwable): TlsFingerprintRequired? {
|
||||
var t: Throwable? = e
|
||||
var depth = 0
|
||||
while (t != null && depth < 10) {
|
||||
if (t is TlsFingerprintRequired) return t
|
||||
t = t.cause
|
||||
depth++
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -6,7 +6,7 @@ package iris.platform
|
||||
* The controller (commonMain) needs to know whether the app is in the
|
||||
* foreground (to decide between an in-app banner and a system notification)
|
||||
* and to post a system notification when a `notification` frame arrives while
|
||||
* the app is backgrounded but the WS is still live.
|
||||
* the app is backgrounded but the gateway connection is still live.
|
||||
*/
|
||||
|
||||
/** True when the app's UI is visible (Android: activity resumed). */
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package iris.platform
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
|
||||
/**
|
||||
* A "Scan QR" button that launches the platform QR scanner and delivers the
|
||||
* scanned text (or null if the user cancelled) to [onResult] (docs/20).
|
||||
*
|
||||
* Android: opens [QrScanActivity] (CameraX + ML Kit). Desktop: renders nothing
|
||||
* (the Connect screen hides it there).
|
||||
*/
|
||||
@Composable
|
||||
expect fun QrScanButton(onResult: (String?) -> Unit)
|
||||
@@ -0,0 +1,13 @@
|
||||
package iris.platform
|
||||
|
||||
import app.cash.sqldelight.db.SqlDriver
|
||||
|
||||
/**
|
||||
* Persistent app-data directory. Unlike the media cache dir, it is not wiped
|
||||
* by the system or by the user clearing the app cache — it holds the SQLite
|
||||
* local cache (messages / channels / meta).
|
||||
*/
|
||||
expect fun appDataDir(): String
|
||||
|
||||
/** Open the SQLite driver for the local cache database. */
|
||||
expect fun createCacheDriver(): SqlDriver
|
||||
@@ -12,30 +12,28 @@ import kotlinx.serialization.json.put
|
||||
|
||||
/**
|
||||
* Wire protocol frames (mirror of gateway-plugin/protocol.py).
|
||||
* See docs/04-wire-protocol.md. M1: hello/hello.ack, message, message.send,
|
||||
* error, ping/pong, typing. M2: message.start/update/stop, tool.start/
|
||||
* progress/end, commentary, reasoning (on message / message.stop).
|
||||
* See docs/04-wire-protocol.md. Defines all frame types and payloads:
|
||||
* hello/hello.ack, message (send + streaming), tool cards, commentary,
|
||||
* reasoning, channels, media, notifications, sync, and error frames.
|
||||
*/
|
||||
|
||||
const val PROTOCOL_VERSION = 1
|
||||
|
||||
object IrisJson {
|
||||
val instance: Json = Json {
|
||||
ignoreUnknownKeys = true
|
||||
encodeDefaults = true
|
||||
isLenient = true
|
||||
}
|
||||
val instance: Json =
|
||||
Json {
|
||||
ignoreUnknownKeys = true
|
||||
encodeDefaults = true
|
||||
isLenient = true
|
||||
}
|
||||
}
|
||||
|
||||
// ── Frame type constants ────────────────────────────────────────────────
|
||||
|
||||
const val TYPE_HELLO = "hello"
|
||||
const val TYPE_HELLO_ACK = "hello.ack"
|
||||
const val TYPE_MESSAGE = "message"
|
||||
const val TYPE_MESSAGE_SEND = "message.send"
|
||||
const val TYPE_ERROR = "error"
|
||||
const val TYPE_PING = "ping"
|
||||
const val TYPE_PONG = "pong"
|
||||
const val TYPE_TYPING = "typing"
|
||||
|
||||
// M2 — streaming / tools / commentary
|
||||
@@ -49,15 +47,16 @@ const val TYPE_MESSAGE_DELETED = "message.deleted"
|
||||
const val TYPE_TOOL_START = "tool.start"
|
||||
const val TYPE_TOOL_PROGRESS = "tool.progress"
|
||||
const val TYPE_TOOL_END = "tool.end"
|
||||
|
||||
// Agent todo list (live planning state; ephemeral, never outboxed — a
|
||||
// reconnecting device re-learns it from the snapshot after hello.ack).
|
||||
const val TYPE_TODO_UPDATE = "todo.update"
|
||||
|
||||
const val TYPE_COMMENTARY = "commentary"
|
||||
|
||||
// M4 — media (upload / offer / pull)
|
||||
const val TYPE_MEDIA_UPLOAD_START = "media.upload.start"
|
||||
const val TYPE_MEDIA_UPLOAD_END = "media.upload.end"
|
||||
// M4 — media (offer; upload/pull are HTTP, docs/19 §19.15)
|
||||
const val TYPE_MEDIA_UPLOAD_ACK = "media.upload.ack"
|
||||
const val TYPE_MEDIA_OFFER = "media.offer"
|
||||
const val TYPE_MEDIA_PULL = "media.pull"
|
||||
const val TYPE_MEDIA_PULL_END = "media.pull.end"
|
||||
|
||||
// M5 — push / notifications / read receipt / gateway status
|
||||
const val TYPE_NOTIFICATION = "notification"
|
||||
@@ -82,24 +81,19 @@ const val TYPE_SEARCH_RESULTS = "search.results"
|
||||
|
||||
// Slash-command catalog (the composer's "/" drawer)
|
||||
const val TYPE_COMMANDS_CATALOG = "commands.catalog"
|
||||
|
||||
// Interactive pickers (slash-command choice menus, e.g. /reasoning, /fast)
|
||||
const val TYPE_PICKER_CHOICE = "picker.choice"
|
||||
const val TYPE_PICKER_SELECT = "picker.select"
|
||||
const val TYPE_SYNC = "sync"
|
||||
const val TYPE_SYNC_DONE = "sync.done"
|
||||
const val TYPE_HISTORY = "history"
|
||||
|
||||
// ── Error codes ─────────────────────────────────────────────────────────
|
||||
|
||||
const val ERR_AUTH = "auth"
|
||||
const val ERR_NOT_FOUND = "not_found"
|
||||
const val ERR_UNSUPPORTED = "unsupported"
|
||||
const val ERR_INTERNAL = "internal"
|
||||
const val ERR_MEDIA_TOO_LARGE = "media_too_large"
|
||||
|
||||
// M4 — media kinds (docs/07 §7.1)
|
||||
const val KIND_IMAGE = "image"
|
||||
const val KIND_AUDIO = "audio"
|
||||
const val KIND_VIDEO = "video"
|
||||
const val KIND_DOCUMENT = "document"
|
||||
const val KIND_VOICE = "voice"
|
||||
|
||||
// ── Roles ───────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -132,18 +126,6 @@ data class Frame(
|
||||
}
|
||||
}
|
||||
|
||||
// ── hello (app -> server) ───────────────────────────────────────────────
|
||||
|
||||
@Serializable
|
||||
data class HelloPayload(
|
||||
val token: String,
|
||||
@SerialName("device_id") val deviceId: String,
|
||||
@SerialName("device_name") val deviceName: String,
|
||||
val caps: JsonElement = buildJsonObject { put("min_protocol", JsonPrimitive(1)) },
|
||||
@SerialName("fcm_token") val fcmToken: String? = null,
|
||||
@SerialName("ntfy_topic") val ntfyTopic: String? = null,
|
||||
)
|
||||
|
||||
// ── hello.ack (server -> app) ───────────────────────────────────────────
|
||||
|
||||
@Serializable
|
||||
@@ -158,6 +140,8 @@ data class ServerCaps(
|
||||
val push: String = "fcm",
|
||||
@SerialName("push_ntfy_server") val pushNtfyServer: String = "",
|
||||
val pickers: Boolean = false,
|
||||
/** Release version of the gateway plugin (repo-root VERSION file). */
|
||||
@SerialName("app_version") val appVersion: String = "",
|
||||
)
|
||||
|
||||
@Serializable
|
||||
@@ -168,6 +152,9 @@ data class ChannelInfo(
|
||||
@SerialName("is_default") val isDefault: Boolean = false,
|
||||
@SerialName("parent_chat_id") val parentChatId: String? = null,
|
||||
val archived: Boolean = false,
|
||||
/** Unix timestamp (seconds) when the channel/thread was created; 0.0 if
|
||||
* the gateway predates the field. Used to order threads newest-first. */
|
||||
val created: Double = 0.0,
|
||||
/** Gateway minted this thread for an incoming message (auto-threading);
|
||||
* the name is a derived title, upgraded by the LLM via channel.renamed. */
|
||||
val auto: Boolean = false,
|
||||
@@ -194,10 +181,31 @@ data class HelloAckPayload(
|
||||
* push backend (0 = never). Sync-replayed frames at/below it must not
|
||||
* re-post system notifications (dedupe, docs/08 §8.7). */
|
||||
@SerialName("last_pushed_cursor") val lastPushedCursor: Long = 0,
|
||||
/** Per-device token minted at pairing (docs/09 §9.3). The app stores it
|
||||
* and presents it INSTEAD of the shared IRIS_TOKEN from then on; the
|
||||
* gateway can revoke it per device. Empty when the gateway didn't
|
||||
* issue one (legacy). */
|
||||
@SerialName("device_token") val deviceToken: String = "",
|
||||
)
|
||||
|
||||
// ── message (server -> app) ─────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Structured runtime metadata for the app's footer (mirror of the gateway's
|
||||
* `runtime` object). The gateway ALWAYS sends this on final assistant
|
||||
* messages; whether/what is shown is a per-app setting (Settings → Runtime
|
||||
* footer), NOT a hermes config. Fields are absent when the data is
|
||||
* unavailable (local models have no cost, etc.).
|
||||
*/
|
||||
@Serializable
|
||||
data class RuntimeMeta(
|
||||
val model: String? = null,
|
||||
@SerialName("context_pct") val contextPct: Int? = null,
|
||||
val cwd: String? = null,
|
||||
val latency: Double? = null,
|
||||
val cost: Double? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class MessagePayload(
|
||||
@SerialName("message_id") val messageId: String,
|
||||
@@ -207,6 +215,7 @@ data class MessagePayload(
|
||||
@SerialName("reply_to") val replyTo: String? = null,
|
||||
val model: String? = null,
|
||||
val tokens: Int? = null,
|
||||
val runtime: RuntimeMeta? = null,
|
||||
val ts: Long? = null,
|
||||
val media: List<MediaRef> = emptyList(),
|
||||
)
|
||||
@@ -223,21 +232,6 @@ data class MediaRef(
|
||||
val filename: String,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class MediaUploadStartPayload(
|
||||
@SerialName("media_ref") val mediaRef: String,
|
||||
val kind: String,
|
||||
val mime: String,
|
||||
val filename: String,
|
||||
val size: Long,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class MediaUploadEndPayload(
|
||||
@SerialName("media_ref") val mediaRef: String,
|
||||
@SerialName("sha256") val sha256: String,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class MediaUploadAckPayload(
|
||||
val ok: Boolean,
|
||||
@@ -254,14 +248,6 @@ data class MediaOfferPayload(
|
||||
@SerialName("message_id") val messageId: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class MediaPullPayload(
|
||||
@SerialName("media_id") val mediaId: String,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class MediaPullEndPayload(val ok: Boolean)
|
||||
|
||||
// ── M2: streaming frames (server -> app) ────────────────────────────────
|
||||
|
||||
@Serializable
|
||||
@@ -283,6 +269,7 @@ data class MessageStopPayload(
|
||||
val reasoning: String? = null,
|
||||
val model: String? = null,
|
||||
val tokens: Int? = null,
|
||||
val runtime: RuntimeMeta? = null,
|
||||
val ts: Long? = null,
|
||||
)
|
||||
|
||||
@@ -294,6 +281,9 @@ data class ToolStartPayload(
|
||||
val name: String,
|
||||
val preview: String? = null,
|
||||
val args: JsonElement? = null,
|
||||
/** Cosmetic per-tool glyph resolved server-side (hermes get_tool_emoji);
|
||||
* absent for unknown tools — the UI falls back to its default. */
|
||||
val emoji: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
@@ -312,6 +302,30 @@ data class ToolEndPayload(
|
||||
@SerialName("output_preview") val outputPreview: String? = null,
|
||||
)
|
||||
|
||||
// ── todo.update (server -> app): the agent's live todo list ────────────────
|
||||
|
||||
/** One item of the agent's todo list (hermes `todo` tool). [status] is one
|
||||
* of [TODO_PENDING], [TODO_IN_PROGRESS], [TODO_COMPLETED], [TODO_CANCELLED]. */
|
||||
@Serializable
|
||||
data class TodoItem(
|
||||
val id: String,
|
||||
val content: String,
|
||||
val status: String,
|
||||
)
|
||||
|
||||
const val TODO_PENDING = "pending"
|
||||
const val TODO_IN_PROGRESS = "in_progress"
|
||||
const val TODO_COMPLETED = "completed"
|
||||
const val TODO_CANCELLED = "cancelled"
|
||||
|
||||
/** The agent's FULL current todo list for a lane (last-write-wins; the
|
||||
* gateway emits it whenever the `todo` tool completes — the tool result is
|
||||
* authoritative even for merge writes — and as a snapshot on connect). */
|
||||
@Serializable
|
||||
data class TodoUpdatePayload(
|
||||
val todos: List<TodoItem> = emptyList(),
|
||||
)
|
||||
|
||||
// ── M2: commentary frame (server -> app) ────────────────────────────────
|
||||
|
||||
@Serializable
|
||||
@@ -332,16 +346,18 @@ data class MessageSendPayload(
|
||||
@SerialName("auto_thread") val autoThread: Boolean = false,
|
||||
)
|
||||
|
||||
// ── typing / error / ping ───────────────────────────────────────────────
|
||||
// ── typing / error ──────────────────────────────────────────────────────
|
||||
|
||||
@Serializable
|
||||
data class TypingPayload(val on: Boolean)
|
||||
data class TypingPayload(
|
||||
val on: Boolean,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ErrorPayload(val code: String, val message: String)
|
||||
|
||||
@Serializable
|
||||
data class PingPayload(val ts: Long? = null)
|
||||
data class ErrorPayload(
|
||||
val code: String,
|
||||
val message: String,
|
||||
)
|
||||
|
||||
// ── M3: channel directory (app -> server requests) ──────────────────────
|
||||
|
||||
@@ -353,13 +369,19 @@ data class ChannelCreatePayload(
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ChannelRenamePayload(val name: String)
|
||||
data class ChannelRenamePayload(
|
||||
val name: String,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ChannelFavoritePayload(val on: Boolean)
|
||||
data class ChannelFavoritePayload(
|
||||
val on: Boolean,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ChannelSetAutomationPayload(val on: Boolean)
|
||||
data class ChannelSetAutomationPayload(
|
||||
val on: Boolean,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ChannelIconPayload(
|
||||
@@ -370,10 +392,14 @@ data class ChannelIconPayload(
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ChannelListPayload(val channels: List<ChannelInfo> = emptyList())
|
||||
data class ChannelListPayload(
|
||||
val channels: List<ChannelInfo> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ChannelDeletedPayload(@SerialName("chat_id") val chatId: String)
|
||||
data class ChannelDeletedPayload(
|
||||
@SerialName("chat_id") val chatId: String,
|
||||
)
|
||||
|
||||
// ── M3: search ──────────────────────────────────────────────────────────
|
||||
|
||||
@@ -421,13 +447,38 @@ data class CommandsCatalogPayload(
|
||||
val commands: List<SlashCommand> = emptyList(),
|
||||
)
|
||||
|
||||
// ── picker.choice / picker.select (interactive slash-command menus) ────────
|
||||
|
||||
/** One option in a choice picker. [isCurrent] marks the active value (the
|
||||
* UI shows a ✓ on it, like Telegram's inline keyboards). */
|
||||
@Serializable
|
||||
data class PickerChoice(
|
||||
val value: String,
|
||||
val label: String = value,
|
||||
@SerialName("is_current") val isCurrent: Boolean = false,
|
||||
)
|
||||
|
||||
/** An interactive choice picker (one tap → one value), sent by finite-choice
|
||||
* slash commands (/reasoning, /fast, …). The app renders it as a card with
|
||||
* buttons and answers via [pickerSelectFrame]. */
|
||||
@Serializable
|
||||
data class PickerChoicePayload(
|
||||
@SerialName("picker_id") val pickerId: String,
|
||||
val title: String,
|
||||
val choices: List<PickerChoice> = emptyList(),
|
||||
)
|
||||
|
||||
// ── M3: sync (reconnect catch-up) ───────────────────────────────────────
|
||||
|
||||
@Serializable
|
||||
data class SyncPayload(val cursor: Long)
|
||||
data class SyncPayload(
|
||||
val cursor: Long,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class SyncDonePayload(val cursor: Long)
|
||||
data class SyncDonePayload(
|
||||
val cursor: Long,
|
||||
)
|
||||
|
||||
// ── history (full message history for a chat/thread) ────────────────────
|
||||
|
||||
@@ -440,8 +491,12 @@ data class HistoryMessage(
|
||||
val reasoning: String? = null,
|
||||
val model: String? = null,
|
||||
val tokens: Int? = null,
|
||||
val runtime: RuntimeMeta? = null,
|
||||
val ts: Long? = null,
|
||||
val media: List<MediaRef> = emptyList(),
|
||||
// Nullable: the schema says array, but older gateways sent
|
||||
// `"media": null` for streaming finals — a null there used to break
|
||||
// deserialization of the whole history page (silently dropping it).
|
||||
val media: List<MediaRef>? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
@@ -462,12 +517,9 @@ data class MessageDeletedPayload(
|
||||
// ── M5: push / notifications ────────────────────────────────────────────
|
||||
|
||||
/** Notification kinds (mirror of protocol.NOTIF_*). */
|
||||
const val NOTIF_MESSAGE = "message"
|
||||
const val NOTIF_APPROVAL = "approval"
|
||||
const val NOTIF_CLARIFY = "clarify"
|
||||
const val NOTIF_CRON = "cron"
|
||||
const val NOTIF_CHANNEL = "channel"
|
||||
const val NOTIF_OUTBOX_PRUNED = "outbox_pruned"
|
||||
|
||||
/** Kinds that stay on screen until dismissed (docs/08 §8.3). */
|
||||
val HIGH_PRIORITY_NOTIF_KINDS = setOf(NOTIF_APPROVAL, NOTIF_CLARIFY, NOTIF_CRON)
|
||||
@@ -496,31 +548,12 @@ data class ReadReceiptPayload(
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class StatusPayload(val state: String)
|
||||
data class StatusPayload(
|
||||
val state: String,
|
||||
)
|
||||
|
||||
// ── Frame builders ──────────────────────────────────────────────────────
|
||||
|
||||
fun helloFrame(
|
||||
token: String,
|
||||
deviceId: String,
|
||||
deviceName: String,
|
||||
fcmToken: String? = null,
|
||||
ntfyTopic: String? = null,
|
||||
): Frame =
|
||||
Frame(
|
||||
type = TYPE_HELLO,
|
||||
payload = IrisJson.instance.encodeToJsonElement(
|
||||
HelloPayload.serializer(),
|
||||
HelloPayload(
|
||||
token = token,
|
||||
deviceId = deviceId,
|
||||
deviceName = deviceName,
|
||||
fcmToken = fcmToken,
|
||||
ntfyTopic = ntfyTopic,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
fun messageSendFrame(
|
||||
id: Int,
|
||||
chatId: String,
|
||||
@@ -534,79 +567,107 @@ fun messageSendFrame(
|
||||
type = TYPE_MESSAGE_SEND,
|
||||
chatId = chatId,
|
||||
threadId = threadId,
|
||||
payload = IrisJson.instance.encodeToJsonElement(
|
||||
MessageSendPayload.serializer(),
|
||||
MessageSendPayload(text = text, mediaRefs = mediaRefs, autoThread = autoThread),
|
||||
),
|
||||
payload =
|
||||
IrisJson.instance.encodeToJsonElement(
|
||||
MessageSendPayload.serializer(),
|
||||
MessageSendPayload(text = text, mediaRefs = mediaRefs, autoThread = autoThread),
|
||||
),
|
||||
)
|
||||
|
||||
fun pingFrame(): Frame =
|
||||
Frame(type = TYPE_PING, payload = IrisJson.instance.encodeToJsonElement(PingPayload.serializer(), PingPayload()))
|
||||
|
||||
// ── M3 frame builders ───────────────────────────────────────────────────
|
||||
|
||||
fun channelCreateFrame(id: Int, name: String, kind: String = "channel", parentChatId: String? = null): Frame =
|
||||
fun channelCreateFrame(
|
||||
id: Int,
|
||||
name: String,
|
||||
kind: String = "channel",
|
||||
parentChatId: String? = null,
|
||||
): Frame =
|
||||
Frame(
|
||||
id = id,
|
||||
type = TYPE_CHANNEL_CREATE,
|
||||
payload = IrisJson.instance.encodeToJsonElement(
|
||||
ChannelCreatePayload.serializer(),
|
||||
ChannelCreatePayload(name = name, kind = kind, parentChatId = parentChatId),
|
||||
),
|
||||
payload =
|
||||
IrisJson.instance.encodeToJsonElement(
|
||||
ChannelCreatePayload.serializer(),
|
||||
ChannelCreatePayload(name = name, kind = kind, parentChatId = parentChatId),
|
||||
),
|
||||
)
|
||||
|
||||
fun channelRenameFrame(id: Int, chatId: String, name: String): Frame =
|
||||
fun channelRenameFrame(
|
||||
id: Int,
|
||||
chatId: String,
|
||||
name: String,
|
||||
): Frame =
|
||||
Frame(
|
||||
id = id,
|
||||
type = TYPE_CHANNEL_RENAME,
|
||||
chatId = chatId,
|
||||
payload = IrisJson.instance.encodeToJsonElement(
|
||||
ChannelRenamePayload.serializer(),
|
||||
ChannelRenamePayload(name = name),
|
||||
),
|
||||
payload =
|
||||
IrisJson.instance.encodeToJsonElement(
|
||||
ChannelRenamePayload.serializer(),
|
||||
ChannelRenamePayload(name = name),
|
||||
),
|
||||
)
|
||||
|
||||
fun channelSetDefaultFrame(id: Int, chatId: String): Frame =
|
||||
Frame(id = id, type = TYPE_CHANNEL_SET_DEFAULT, chatId = chatId)
|
||||
fun channelSetDefaultFrame(
|
||||
id: Int,
|
||||
chatId: String,
|
||||
): Frame = Frame(id = id, type = TYPE_CHANNEL_SET_DEFAULT, chatId = chatId)
|
||||
|
||||
fun channelFavoriteFrame(id: Int, chatId: String, on: Boolean): Frame =
|
||||
fun channelFavoriteFrame(
|
||||
id: Int,
|
||||
chatId: String,
|
||||
on: Boolean,
|
||||
): Frame =
|
||||
Frame(
|
||||
id = id,
|
||||
type = TYPE_CHANNEL_FAVORITE,
|
||||
chatId = chatId,
|
||||
payload = IrisJson.instance.encodeToJsonElement(
|
||||
ChannelFavoritePayload.serializer(),
|
||||
ChannelFavoritePayload(on = on),
|
||||
),
|
||||
payload =
|
||||
IrisJson.instance.encodeToJsonElement(
|
||||
ChannelFavoritePayload.serializer(),
|
||||
ChannelFavoritePayload(on = on),
|
||||
),
|
||||
)
|
||||
|
||||
fun channelSetAutomationFrame(id: Int, chatId: String, on: Boolean): Frame =
|
||||
fun channelSetAutomationFrame(
|
||||
id: Int,
|
||||
chatId: String,
|
||||
on: Boolean,
|
||||
): Frame =
|
||||
Frame(
|
||||
id = id,
|
||||
type = TYPE_CHANNEL_SET_AUTOMATION,
|
||||
chatId = chatId,
|
||||
payload = IrisJson.instance.encodeToJsonElement(
|
||||
ChannelSetAutomationPayload.serializer(),
|
||||
ChannelSetAutomationPayload(on = on),
|
||||
),
|
||||
payload =
|
||||
IrisJson.instance.encodeToJsonElement(
|
||||
ChannelSetAutomationPayload.serializer(),
|
||||
ChannelSetAutomationPayload(on = on),
|
||||
),
|
||||
)
|
||||
|
||||
fun channelIconFrame(id: Int, chatId: String, icon: String?, color: String?): Frame =
|
||||
fun channelIconFrame(
|
||||
id: Int,
|
||||
chatId: String,
|
||||
icon: String?,
|
||||
color: String?,
|
||||
): Frame =
|
||||
Frame(
|
||||
id = id,
|
||||
type = TYPE_CHANNEL_ICON,
|
||||
chatId = chatId,
|
||||
payload = IrisJson.instance.encodeToJsonElement(
|
||||
ChannelIconPayload.serializer(),
|
||||
ChannelIconPayload(icon = icon, color = color),
|
||||
),
|
||||
payload =
|
||||
IrisJson.instance.encodeToJsonElement(
|
||||
ChannelIconPayload.serializer(),
|
||||
ChannelIconPayload(icon = icon, color = color),
|
||||
),
|
||||
)
|
||||
|
||||
fun channelDeleteFrame(id: Int, chatId: String): Frame =
|
||||
Frame(id = id, type = TYPE_CHANNEL_DELETE, chatId = chatId)
|
||||
fun channelDeleteFrame(
|
||||
id: Int,
|
||||
chatId: String,
|
||||
): Frame = Frame(id = id, type = TYPE_CHANNEL_DELETE, chatId = chatId)
|
||||
|
||||
fun channelListFrame(id: Int): Frame =
|
||||
Frame(id = id, type = TYPE_CHANNEL_LIST)
|
||||
fun channelListFrame(id: Int): Frame = Frame(id = id, type = TYPE_CHANNEL_LIST)
|
||||
|
||||
fun searchFrame(
|
||||
id: Int,
|
||||
@@ -620,25 +681,47 @@ fun searchFrame(
|
||||
type = TYPE_SEARCH,
|
||||
chatId = chatId,
|
||||
threadId = threadId,
|
||||
payload = IrisJson.instance.encodeToJsonElement(
|
||||
SearchPayload.serializer(),
|
||||
SearchPayload(query = query, scope = scope, chatId = chatId, threadId = threadId),
|
||||
),
|
||||
payload =
|
||||
IrisJson.instance.encodeToJsonElement(
|
||||
SearchPayload.serializer(),
|
||||
SearchPayload(query = query, scope = scope, chatId = chatId, threadId = threadId),
|
||||
),
|
||||
)
|
||||
|
||||
/** Request the gateway's slash-command catalog (the composer's "/" drawer).
|
||||
* Answered by a `commands.catalog` frame carrying the same id. */
|
||||
fun commandsCatalogFrame(id: Int): Frame =
|
||||
Frame(id = id, type = TYPE_COMMANDS_CATALOG)
|
||||
fun commandsCatalogFrame(id: Int): Frame = Frame(id = id, type = TYPE_COMMANDS_CATALOG)
|
||||
|
||||
fun syncFrame(id: Int, cursor: Long): Frame =
|
||||
/** Answer an interactive picker (picker.choice) with the chosen value.
|
||||
* The server runs the command's selection callback and delivers its reply
|
||||
* as a normal message in the picker's chat. */
|
||||
fun pickerSelectFrame(
|
||||
id: Int,
|
||||
pickerId: String,
|
||||
value: String,
|
||||
): Frame =
|
||||
Frame(
|
||||
id = id,
|
||||
type = TYPE_PICKER_SELECT,
|
||||
payload =
|
||||
buildJsonObject {
|
||||
put("picker_id", pickerId)
|
||||
put("value", value)
|
||||
},
|
||||
)
|
||||
|
||||
fun syncFrame(
|
||||
id: Int,
|
||||
cursor: Long,
|
||||
): Frame =
|
||||
Frame(
|
||||
id = id,
|
||||
type = TYPE_SYNC,
|
||||
payload = IrisJson.instance.encodeToJsonElement(
|
||||
SyncPayload.serializer(),
|
||||
SyncPayload(cursor = cursor),
|
||||
),
|
||||
payload =
|
||||
IrisJson.instance.encodeToJsonElement(
|
||||
SyncPayload.serializer(),
|
||||
SyncPayload(cursor = cursor),
|
||||
),
|
||||
)
|
||||
|
||||
/** Request a page of full message history for a chat/thread (initial open /
|
||||
@@ -656,10 +739,11 @@ fun historyFrame(
|
||||
type = TYPE_HISTORY,
|
||||
chatId = chatId,
|
||||
threadId = threadId,
|
||||
payload = buildJsonObject {
|
||||
if (beforeMessageId != null) put("before_message_id", beforeMessageId)
|
||||
put("limit", limit)
|
||||
},
|
||||
payload =
|
||||
buildJsonObject {
|
||||
if (beforeMessageId != null) put("before_message_id", beforeMessageId)
|
||||
put("limit", limit)
|
||||
},
|
||||
)
|
||||
|
||||
/** Request deletion of the given message(s) in a chat/thread. The server
|
||||
@@ -675,57 +759,23 @@ fun messageDeleteFrame(
|
||||
type = TYPE_MESSAGE_DELETE,
|
||||
chatId = chatId,
|
||||
threadId = threadId,
|
||||
payload = buildJsonObject {
|
||||
put("message_ids", JsonArray(messageIds.map { JsonPrimitive(it) }))
|
||||
},
|
||||
)
|
||||
|
||||
// ── M4 frame builders ────────────────────────────────────────────────────
|
||||
|
||||
fun mediaUploadStartFrame(
|
||||
id: Int,
|
||||
mediaRef: String,
|
||||
kind: String,
|
||||
mime: String,
|
||||
filename: String,
|
||||
size: Long,
|
||||
): Frame =
|
||||
Frame(
|
||||
id = id,
|
||||
type = TYPE_MEDIA_UPLOAD_START,
|
||||
payload = IrisJson.instance.encodeToJsonElement(
|
||||
MediaUploadStartPayload.serializer(),
|
||||
MediaUploadStartPayload(mediaRef, kind, mime, filename, size),
|
||||
),
|
||||
)
|
||||
|
||||
fun mediaUploadEndFrame(id: Int, mediaRef: String, sha256: String): Frame =
|
||||
Frame(
|
||||
id = id,
|
||||
type = TYPE_MEDIA_UPLOAD_END,
|
||||
payload = IrisJson.instance.encodeToJsonElement(
|
||||
MediaUploadEndPayload.serializer(),
|
||||
MediaUploadEndPayload(mediaRef, sha256),
|
||||
),
|
||||
)
|
||||
|
||||
fun mediaPullFrame(id: Int, mediaId: String): Frame =
|
||||
Frame(
|
||||
id = id,
|
||||
type = TYPE_MEDIA_PULL,
|
||||
payload = IrisJson.instance.encodeToJsonElement(
|
||||
MediaPullPayload.serializer(),
|
||||
MediaPullPayload(mediaId),
|
||||
),
|
||||
payload =
|
||||
buildJsonObject {
|
||||
put("message_ids", JsonArray(messageIds.map { JsonPrimitive(it) }))
|
||||
},
|
||||
)
|
||||
|
||||
// ── M5 frame builders ───────────────────────────────────────────────────
|
||||
|
||||
fun fcmRegisterFrame(fcmToken: String? = null, ntfyTopic: String? = null): Frame =
|
||||
fun fcmRegisterFrame(
|
||||
fcmToken: String? = null,
|
||||
ntfyTopic: String? = null,
|
||||
): Frame =
|
||||
Frame(
|
||||
type = TYPE_FCM_REGISTER,
|
||||
payload = IrisJson.instance.encodeToJsonElement(
|
||||
FcmRegisterPayload.serializer(),
|
||||
FcmRegisterPayload(fcmToken = fcmToken, ntfyTopic = ntfyTopic),
|
||||
),
|
||||
)
|
||||
payload =
|
||||
IrisJson.instance.encodeToJsonElement(
|
||||
FcmRegisterPayload.serializer(),
|
||||
FcmRegisterPayload(fcmToken = fcmToken, ntfyTopic = ntfyTopic),
|
||||
),
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -9,17 +9,21 @@ import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.LinkAnnotation
|
||||
import androidx.compose.ui.text.LinkInteractionListener
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.TextLinkStyles
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
@@ -37,15 +41,28 @@ import com.mikepenz.markdown.compose.elements.MarkdownHighlightedCode
|
||||
import com.mikepenz.markdown.m3.Markdown
|
||||
import com.mikepenz.markdown.m3.markdownColor
|
||||
import com.mikepenz.markdown.m3.markdownTypography
|
||||
import com.mikepenz.markdown.model.StreamingMarkdownState
|
||||
import com.mikepenz.markdown.model.markdownAnnotator
|
||||
import com.mikepenz.markdown.model.rememberMarkdownState
|
||||
import com.mikepenz.markdown.model.rememberStreamingMarkdownState
|
||||
import com.mikepenz.markdown.utils.getUnescapedTextInNode
|
||||
import dev.snipme.highlights.Highlights
|
||||
import dev.snipme.highlights.model.SyntaxThemes
|
||||
import iris.ui.theme.IrisColors
|
||||
import iris.util.STREAM_SMOOTHNESS_DEFAULT
|
||||
import iris.util.appendChunk
|
||||
import iris.util.prepareForMarkdown
|
||||
import iris.util.preserveNewlinesAsHardBreaks
|
||||
import iris.util.preserveNewlinesAsHardBreaksStreaming
|
||||
import iris.util.revealStep
|
||||
import iris.util.streamCharsPerSecond
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import org.intellij.markdown.MarkdownElementTypes
|
||||
import org.intellij.markdown.MarkdownTokenTypes
|
||||
|
||||
/** Reveal tick for the streaming typewriter effect (docs/05 §5.1). */
|
||||
private const val STREAM_REVEAL_TICK_MS = 50L
|
||||
|
||||
/**
|
||||
* Renders a chat message as markdown (M8): bold / italic / underscore, GFM
|
||||
@@ -53,6 +70,12 @@ import org.intellij.markdown.MarkdownElementTypes
|
||||
* syntax highlighting (```json → JSON, ```kotlin → Kotlin, …). [text] is the
|
||||
* raw markdown; [color] and [fontSize] match the surrounding bubble so the
|
||||
* rendered text blends in.
|
||||
*
|
||||
* While [isStreaming], the text is revealed at a steady rate (controlled by
|
||||
* [streamSmoothness], Settings → Streaming) and parsed INCREMENTALLY: settled
|
||||
* blocks are parsed once and never re-laid out, only the tail re-renders per
|
||||
* tick — so the bubble stays readable instead of reflowing (and flashing raw
|
||||
* markdown) on every gateway update.
|
||||
*/
|
||||
@Composable
|
||||
fun MarkdownText(
|
||||
@@ -64,13 +87,32 @@ fun MarkdownText(
|
||||
// plain highlighted code — the artifact card (and its runnable preview)
|
||||
// only appears once the message is complete.
|
||||
isStreaming: Boolean = false,
|
||||
streamSmoothness: Float = STREAM_SMOOTHNESS_DEFAULT,
|
||||
) {
|
||||
val state = rememberMarkdownState(text)
|
||||
// Static path: transform once per text change (leading blanks stripped,
|
||||
// single newlines → hard breaks).
|
||||
val displayText = remember(text) { text.prepareForMarkdown().preserveNewlinesAsHardBreaks() }
|
||||
// Whether this bubble has ever been streamed. Static history messages
|
||||
// skip the reveal pipeline entirely.
|
||||
val hasStreamed = remember { mutableStateOf(isStreaming) }
|
||||
if (isStreaming) hasStreamed.value = true
|
||||
val pipeline =
|
||||
rememberStreamingMarkdownPipeline(
|
||||
text = text,
|
||||
smoothness = streamSmoothness,
|
||||
active = hasStreamed.value,
|
||||
streaming = isStreaming,
|
||||
)
|
||||
// Keep the streaming renderer until the reveal catches up, even after
|
||||
// message.stop — a fast model that dumps the whole text at once still
|
||||
// plays out the typewriter instead of jumping to the full message.
|
||||
val useStreaming = hasStreamed.value && (isStreaming || !pipeline.done)
|
||||
// The app is always dark-themed, so force the dark highlight palette
|
||||
// (isSystemInDarkTheme() is unreliable on desktop).
|
||||
val highlights = remember {
|
||||
Highlights.Builder().theme(SyntaxThemes.default(darkMode = true))
|
||||
}
|
||||
val highlights =
|
||||
remember {
|
||||
Highlights.Builder().theme(SyntaxThemes.default(darkMode = true))
|
||||
}
|
||||
val base = TextStyle(color = color, fontSize = fontSize)
|
||||
val inlineCodeBackground = Color.White.copy(alpha = 0.08f)
|
||||
// Inline-code span style (mirrors the library's codeSpanStyle): the
|
||||
@@ -80,7 +122,8 @@ fun MarkdownText(
|
||||
// Brief green flash shown on the chip right after a copy, so the tap is
|
||||
// visible feedback (the clipboard write itself is silent).
|
||||
val copiedCodeSpanStyle =
|
||||
base.copy(fontFamily = FontFamily.Monospace, background = IrisColors.statusGreen.copy(alpha = 0.30f))
|
||||
base
|
||||
.copy(fontFamily = FontFamily.Monospace, background = IrisColors.statusGreen.copy(alpha = 0.30f))
|
||||
.toSpanStyle()
|
||||
val clipboard = LocalClipboardManager.current
|
||||
val scope = rememberCoroutineScope()
|
||||
@@ -92,57 +135,74 @@ fun MarkdownText(
|
||||
// Re-render it without the padding, and wrap it in a link so tapping the
|
||||
// inline code copies it to the clipboard (Telegram-style). The
|
||||
// LinkAnnotation carries the click listener; the URL is never opened.
|
||||
val annotator = markdownAnnotator(
|
||||
annotate = { content, child ->
|
||||
if (child.type == MarkdownElementTypes.CODE_SPAN) {
|
||||
val children = child.children
|
||||
// Drop the surrounding backtick tokens (present as first/last child).
|
||||
val inner = if (children.size >= 3) children.subList(1, children.size - 1) else children
|
||||
val code = inner.joinToString("") { it.getUnescapedTextInNode(content) }
|
||||
val spanStyle = if (code == copiedCode.value) copiedCodeSpanStyle else codeSpanStyle
|
||||
pushStyle(spanStyle)
|
||||
withLink(
|
||||
LinkAnnotation.Url(
|
||||
url = "iris:copy-code",
|
||||
// Keep every interaction state identical to the chip so
|
||||
// hover/press never restyles the inline code.
|
||||
styles = TextLinkStyles(
|
||||
style = spanStyle,
|
||||
focusedStyle = spanStyle,
|
||||
hoveredStyle = spanStyle,
|
||||
pressedStyle = spanStyle,
|
||||
),
|
||||
linkInteractionListener = LinkInteractionListener {
|
||||
clipboard.setText(AnnotatedString(code))
|
||||
copiedCode.value = code
|
||||
scope.launch {
|
||||
delay(600)
|
||||
copiedCode.value = null
|
||||
}
|
||||
},
|
||||
),
|
||||
) {
|
||||
append(code)
|
||||
val annotator =
|
||||
markdownAnnotator(
|
||||
annotate = { content, child ->
|
||||
when {
|
||||
child.type == MarkdownElementTypes.CODE_SPAN -> {
|
||||
val children = child.children
|
||||
// Drop the surrounding backtick tokens (present as first/last child).
|
||||
val inner = if (children.size >= 3) children.subList(1, children.size - 1) else children
|
||||
val code = inner.joinToString("") { it.getUnescapedTextInNode(content) }
|
||||
val spanStyle = if (code == copiedCode.value) copiedCodeSpanStyle else codeSpanStyle
|
||||
pushStyle(spanStyle)
|
||||
withLink(
|
||||
LinkAnnotation.Url(
|
||||
url = "iris:copy-code",
|
||||
// Keep every interaction state identical to the chip so
|
||||
// hover/press never restyles the inline code.
|
||||
styles =
|
||||
TextLinkStyles(
|
||||
style = spanStyle,
|
||||
focusedStyle = spanStyle,
|
||||
hoveredStyle = spanStyle,
|
||||
pressedStyle = spanStyle,
|
||||
),
|
||||
linkInteractionListener =
|
||||
LinkInteractionListener {
|
||||
clipboard.setText(AnnotatedString(code))
|
||||
copiedCode.value = code
|
||||
scope.launch {
|
||||
delay(600)
|
||||
copiedCode.value = null
|
||||
}
|
||||
},
|
||||
),
|
||||
) {
|
||||
append(code)
|
||||
}
|
||||
pop()
|
||||
true
|
||||
}
|
||||
|
||||
// Streaming cursor: append ▉ to the last text leaf of the
|
||||
// document so the cursor sits at the end of the visible text.
|
||||
// The tail is re-annotated on every reveal tick, so the cursor
|
||||
// follows the text (and vanishes once the message is final).
|
||||
useStreaming &&
|
||||
child.type == MarkdownTokenTypes.TEXT &&
|
||||
content.length - child.endOffset <= 1 -> {
|
||||
append(child.getUnescapedTextInNode(content))
|
||||
append(" ▉")
|
||||
true
|
||||
}
|
||||
|
||||
else -> {
|
||||
false
|
||||
}
|
||||
}
|
||||
pop()
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
},
|
||||
)
|
||||
Markdown(
|
||||
markdownState = state,
|
||||
modifier = modifier,
|
||||
annotator = annotator,
|
||||
colors = markdownColor(
|
||||
},
|
||||
)
|
||||
val colors =
|
||||
markdownColor(
|
||||
text = color,
|
||||
codeBackground = Color.Black.copy(alpha = 0.8f),
|
||||
inlineCodeBackground = inlineCodeBackground,
|
||||
dividerColor = IrisColors.divider,
|
||||
tableBackground = Color.White.copy(alpha = 0.03f),
|
||||
),
|
||||
typography = markdownTypography(
|
||||
)
|
||||
val typography =
|
||||
markdownTypography(
|
||||
h1 = base.copy(fontSize = fontSize * 1.3f, fontWeight = FontWeight.Bold),
|
||||
h2 = base.copy(fontSize = fontSize * 1.2f, fontWeight = FontWeight.Bold),
|
||||
h3 = base.copy(fontSize = fontSize * 1.1f, fontWeight = FontWeight.Bold),
|
||||
@@ -157,15 +217,17 @@ fun MarkdownText(
|
||||
ordered = base,
|
||||
bullet = base,
|
||||
list = base,
|
||||
textLink = TextLinkStyles(
|
||||
style = base.copy(textDecoration = TextDecoration.Underline).toSpanStyle(),
|
||||
),
|
||||
textLink =
|
||||
TextLinkStyles(
|
||||
style = base.copy(textDecoration = TextDecoration.Underline).toSpanStyle(),
|
||||
),
|
||||
table = base.copy(fontSize = fontSize * 0.95f),
|
||||
),
|
||||
components = markdownComponents(
|
||||
)
|
||||
val components =
|
||||
markdownComponents(
|
||||
codeFence = { model ->
|
||||
MarkdownCodeFence(model.content, model.node, model.typography.code) { code, language, style ->
|
||||
if (!isStreaming && isHtmlArtifact(language, code)) {
|
||||
if (!useStreaming && isHtmlArtifact(language, code)) {
|
||||
HtmlArtifactCard(code = code, style = style, highlights = highlights)
|
||||
} else {
|
||||
CodeBlockWithCopy(code = code, language = language, style = style, highlights = highlights)
|
||||
@@ -174,7 +236,7 @@ fun MarkdownText(
|
||||
},
|
||||
codeBlock = { model ->
|
||||
MarkdownCodeBlock(model.content, model.node, model.typography.code) { code, language, style ->
|
||||
if (!isStreaming && isHtmlArtifact(language, code)) {
|
||||
if (!useStreaming && isHtmlArtifact(language, code)) {
|
||||
HtmlArtifactCard(code = code, style = style, highlights = highlights)
|
||||
} else {
|
||||
CodeBlockWithCopy(code = code, language = language, style = style, highlights = highlights)
|
||||
@@ -184,17 +246,129 @@ fun MarkdownText(
|
||||
// The core default checkbox renders literal "[x]"/"[ ]" text; use the
|
||||
// Material 3 checkbox instead.
|
||||
checkbox = {
|
||||
com.mikepenz.markdown.m3.elements.MarkdownCheckBox(it.content, it.node, it.typography.text)
|
||||
com.mikepenz.markdown.m3.elements
|
||||
.MarkdownCheckBox(it.content, it.node, it.typography.text)
|
||||
},
|
||||
),
|
||||
loading = { m ->
|
||||
// While (re)parsing — e.g. on each streaming update — show the raw
|
||||
// text so the bubble never goes blank between updates.
|
||||
Text(text, modifier = m, color = color, fontSize = fontSize)
|
||||
},
|
||||
)
|
||||
)
|
||||
if (useStreaming) {
|
||||
if (pipeline.displayed.isEmpty()) {
|
||||
// No text revealed yet (message.start, first tick pending): show
|
||||
// just the cursor so the bubble is visible immediately.
|
||||
Text("▉", modifier = modifier, color = color, fontSize = fontSize)
|
||||
} else {
|
||||
Markdown(
|
||||
streamingMarkdownState = pipeline.state,
|
||||
modifier = modifier,
|
||||
annotator = annotator,
|
||||
colors = colors,
|
||||
typography = typography,
|
||||
components = components,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
// retainState: keep the last formatted output visible while the new
|
||||
// text re-parses (async) — no raw-markdown flash between updates.
|
||||
val state = rememberMarkdownState(displayText, retainState = true)
|
||||
Markdown(
|
||||
markdownState = state,
|
||||
modifier = modifier,
|
||||
annotator = annotator,
|
||||
colors = colors,
|
||||
typography = typography,
|
||||
components = components,
|
||||
loading = { m ->
|
||||
// First parse of a (long) message: show the text so the bubble
|
||||
// never goes blank.
|
||||
Text(displayText, modifier = m, color = color, fontSize = fontSize)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Incremental streaming pipeline (docs/05 §5.1). [text] is the latest FULL
|
||||
* snapshot from the gateway; it is revealed at a steady rate controlled by
|
||||
* [smoothness] (typewriter effect), and the revealed prefix is fed into an
|
||||
* append-only [StreamingMarkdownState]. Settled blocks are parsed once and
|
||||
* keep their AST identity, so Compose never re-lays them out — only the
|
||||
* unstable tail re-renders per tick.
|
||||
*
|
||||
* [active] is false for history messages (never streamed): the reveal is
|
||||
* skipped and [StreamingPipeline.done] is true immediately. [streaming]
|
||||
* indicates the message is still receiving updates; once the reveal catches
|
||||
* up and the message is final, the reveal loop stops.
|
||||
*
|
||||
* Returns the parser state, the currently revealed text (read inside the
|
||||
* composition so reveal ticks recompose the caller), and whether the reveal
|
||||
* has caught up with the target.
|
||||
*/
|
||||
@Composable
|
||||
private fun rememberStreamingMarkdownPipeline(
|
||||
text: String,
|
||||
smoothness: Float,
|
||||
active: Boolean,
|
||||
streaming: Boolean,
|
||||
): StreamingPipeline {
|
||||
// Prefix-preserving transform (see preserveNewlinesAsHardBreaksStreaming):
|
||||
// a prefix of the revealed text always maps to a prefix of the target, so
|
||||
// the diff between consecutive reveals is a pure append.
|
||||
val target = remember(text) { text.prepareForMarkdown().preserveNewlinesAsHardBreaksStreaming() }
|
||||
val displayed = remember { mutableStateOf("") }
|
||||
val latestTarget = rememberUpdatedState(target)
|
||||
val latestSmoothness = rememberUpdatedState(smoothness)
|
||||
val latestStreaming = rememberUpdatedState(streaming)
|
||||
// Bumped when the target is rewritten (not extended): the parser state is
|
||||
// recreated via key() below and re-seeded with the full text.
|
||||
val generation = remember { mutableIntStateOf(0) }
|
||||
val state = key(generation.value) { rememberStreamingMarkdownState() }
|
||||
LaunchedEffect(state, active) {
|
||||
if (!active) {
|
||||
// Never streamed (history message): reveal everything at once so
|
||||
// the caller falls back to the static renderer immediately.
|
||||
displayed.value = latestTarget.value
|
||||
return@LaunchedEffect
|
||||
}
|
||||
var last = ""
|
||||
while (true) {
|
||||
delay(STREAM_REVEAL_TICK_MS)
|
||||
val t = latestTarget.value
|
||||
val cur = displayed.value
|
||||
if (cur == t) {
|
||||
// Reveal complete: keep ticking only while the message is
|
||||
// still streaming (more text may arrive); otherwise stop so
|
||||
// finished bubbles don't burn battery.
|
||||
if (!latestStreaming.value) return@LaunchedEffect
|
||||
continue
|
||||
}
|
||||
val step =
|
||||
revealStep(
|
||||
remaining = t.length - cur.length,
|
||||
charsPerSecond = streamCharsPerSecond(latestSmoothness.value),
|
||||
tickSeconds = STREAM_REVEAL_TICK_MS / 1000.0,
|
||||
)
|
||||
val next = t.take(cur.length + step)
|
||||
displayed.value = next
|
||||
val chunk = appendChunk(last, next)
|
||||
if (chunk == null) {
|
||||
// Rewritten, not extended: recreate the parser state. The
|
||||
// effect restarts (keyed on [state]) and re-seeds it.
|
||||
generation.value++
|
||||
return@LaunchedEffect
|
||||
}
|
||||
if (chunk.isNotEmpty()) state.append(chunk)
|
||||
last = next
|
||||
}
|
||||
}
|
||||
return StreamingPipeline(state, displayed.value, displayed.value == target)
|
||||
}
|
||||
|
||||
/** Result of the streaming reveal pipeline. */
|
||||
private data class StreamingPipeline(
|
||||
val state: StreamingMarkdownState,
|
||||
val displayed: String,
|
||||
val done: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
* Renders a highlighted code block with a copy button in the top-right corner
|
||||
* (Telegram-style). Tapping the button copies the whole block to the clipboard.
|
||||
@@ -213,12 +387,13 @@ internal fun CodeBlockWithCopy(
|
||||
if (code.isNotBlank()) {
|
||||
IconButton(
|
||||
onClick = { clipboard.setText(AnnotatedString(code)) },
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
// MarkdownHighlightedCode insets its background by 8dp top;
|
||||
// match that so the button sits inside the block, not above it.
|
||||
.padding(top = 8.dp, end = 4.dp)
|
||||
.size(28.dp),
|
||||
modifier =
|
||||
Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
// MarkdownHighlightedCode insets its background by 8dp top;
|
||||
// match that so the button sits inside the block, not above it.
|
||||
.padding(top = 8.dp, end = 4.dp)
|
||||
.size(28.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.ContentCopy,
|
||||
@@ -228,4 +403,4 @@ internal fun CodeBlockWithCopy(
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -11,10 +11,12 @@ import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -24,11 +26,16 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import iris.net.TlsFingerprintRequired
|
||||
import iris.platform.QrScanButton
|
||||
import iris.platform.isDesktop
|
||||
import iris.state.IrisController
|
||||
import iris.ui.theme.IrisColors
|
||||
import iris.util.PairLink
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
@@ -41,18 +48,49 @@ fun ConnectScreen(
|
||||
prefillUrl: String = "",
|
||||
prefillToken: String = "",
|
||||
initialError: String? = null,
|
||||
/** Gateway certificate fingerprint awaiting user confirmation (docs/09
|
||||
* §9.4) — shown as a confirm dialog on entry. */
|
||||
tlsFingerprint: String? = null,
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
var url by remember { mutableStateOf(prefillUrl.ifBlank { "ws://" }) }
|
||||
// Default is a cleartext (non-TLS) URL because the typical gateway is on
|
||||
// the LAN. A TLS gateway is reached by entering a secure (https) URL instead.
|
||||
var url by remember { mutableStateOf(prefillUrl.ifBlank { "http://" }) }
|
||||
var token by remember { mutableStateOf(prefillToken) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
var error by remember { mutableStateOf(initialError) }
|
||||
// Fingerprint the user still has to confirm (self-signed gateway cert,
|
||||
// docs/09 §9.4): set on entry (TlsConfirmRequired state) or when a
|
||||
// connect attempt fails with an untrusted certificate.
|
||||
var pendingFingerprint by remember { mutableStateOf(tlsFingerprint) }
|
||||
|
||||
// "Test & Connect" (also the dialog's confirm action): real hello test,
|
||||
// then save + (re)connect. An untrusted gateway certificate surfaces as
|
||||
// the fingerprint confirm dialog instead of a plain error.
|
||||
fun doConnect() {
|
||||
if (busy) return
|
||||
busy = true
|
||||
error = null
|
||||
scope.launch {
|
||||
val result = controller.connect(url.trim(), token.trim())
|
||||
busy = false
|
||||
if (result.isFailure) {
|
||||
val ex = result.exceptionOrNull()
|
||||
if (ex is TlsFingerprintRequired) {
|
||||
pendingFingerprint = ex.fingerprint
|
||||
} else {
|
||||
error = ex?.message ?: "connection failed"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(24.dp),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Spacer(modifier = Modifier.height(48.dp))
|
||||
@@ -66,17 +104,19 @@ fun ConnectScreen(
|
||||
Spacer(modifier = Modifier.height(32.dp))
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(IrisColors.surface)
|
||||
.padding(16.dp),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(IrisColors.surface)
|
||||
.padding(16.dp),
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = url,
|
||||
onValueChange = { url = it },
|
||||
label = { Text("Server URL") },
|
||||
placeholder = { Text("ws://192.168.1.10:8790/ws") },
|
||||
// Example LAN URL; https:// works too for TLS gateways.
|
||||
placeholder = { Text("http://192.168.1.10:8791") },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
@@ -86,26 +126,29 @@ fun ConnectScreen(
|
||||
value = token,
|
||||
onValueChange = { token = it },
|
||||
label = { Text("Pairing token") },
|
||||
placeholder = { Text("ANDROID_TOKEN (64 hex)") },
|
||||
placeholder = { Text("IRIS_TOKEN (64 hex)") },
|
||||
singleLine = true,
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
if (!isDesktop) {
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
QrScanButton { raw ->
|
||||
if (raw != null) {
|
||||
val link = PairLink.parse(raw)
|
||||
if (link != null) {
|
||||
url = link.url
|
||||
token = link.token
|
||||
} else {
|
||||
error = "Couldn't read that QR code."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(modifier = Modifier.height(24.dp))
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
if (busy) return@Button
|
||||
busy = true
|
||||
error = null
|
||||
scope.launch {
|
||||
val result = controller.connect(url.trim(), token.trim())
|
||||
busy = false
|
||||
if (result.isFailure) {
|
||||
error = result.exceptionOrNull()?.message ?: "connection failed"
|
||||
}
|
||||
}
|
||||
},
|
||||
onClick = { doConnect() },
|
||||
enabled = !busy,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
@@ -124,11 +167,49 @@ fun ConnectScreen(
|
||||
|
||||
Spacer(modifier = Modifier.height(24.dp))
|
||||
Text(
|
||||
"Find the token in ~/.hermes/.env (ANDROID_TOKEN) or run\n" +
|
||||
"Find the token in ~/.hermes/.env (IRIS_TOKEN) or run\n" +
|
||||
"hermes gateway setup on the gateway host.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Fingerprint confirm (docs/09 §9.4): the gateway presents a certificate
|
||||
// this device doesn't trust (self-signed). The user verifies the
|
||||
// fingerprint on the gateway host, then confirms — the pin is stored in
|
||||
// secure storage and the connect is retried, like an SSH host key.
|
||||
if (pendingFingerprint != null) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { pendingFingerprint = null },
|
||||
title = { Text("Confirm gateway certificate") },
|
||||
text = {
|
||||
Column {
|
||||
Text(
|
||||
"The gateway presents a certificate this device doesn't trust. " +
|
||||
"Verify the fingerprint on the gateway host, then confirm to pin it.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Text(
|
||||
pendingFingerprint!!,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
Button(
|
||||
onClick = {
|
||||
val fp = pendingFingerprint!!
|
||||
pendingFingerprint = null
|
||||
controller.confirmTlsFingerprint(fp)
|
||||
doConnect()
|
||||
},
|
||||
) { Text("Confirm & pin") }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { pendingFingerprint = null }) { Text("Cancel") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,8 @@ import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import iris.AppVersion
|
||||
import iris.net.ReleaseCheck
|
||||
import iris.platform.ImageFilePicker
|
||||
import iris.platform.decodeImageBytes
|
||||
import iris.platform.loadScaledImage
|
||||
@@ -54,6 +56,8 @@ import iris.ui.theme.Backdrop
|
||||
import iris.ui.theme.BackgroundMode
|
||||
import iris.ui.theme.IrisColors
|
||||
import iris.ui.theme.LocalUserTheme
|
||||
import iris.util.STREAM_SMOOTHNESS_MAX
|
||||
import iris.util.STREAM_SMOOTHNESS_MIN
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
@@ -71,11 +75,23 @@ fun SettingsScreen(
|
||||
) {
|
||||
val threadsEnabled by controller.threadsEnabled.collectAsState()
|
||||
val streamingEnabled by controller.streamingEnabled.collectAsState()
|
||||
val streamSmoothness by controller.streamSmoothness.collectAsState()
|
||||
val reasoningAutoCollapse by controller.reasoningAutoCollapse.collectAsState()
|
||||
val runtimeFooterEnabled by controller.runtimeFooterEnabled.collectAsState()
|
||||
val runtimeFooterFields by controller.runtimeFooterFields.collectAsState()
|
||||
val toolDetail by controller.toolDetail.collectAsState()
|
||||
val fontSizeScale by controller.fontSizeScale.collectAsState()
|
||||
val gatewayVersion by controller.gatewayVersion.collectAsState()
|
||||
val theme = LocalUserTheme.current
|
||||
var pickerTarget by remember { mutableStateOf<PickerTarget?>(null) }
|
||||
var showForgetConfirm by remember { mutableStateOf(false) }
|
||||
|
||||
// Best-effort latest-release check (docs/04): one query per screen open,
|
||||
// failures stay silent (ReleaseCheck returns null).
|
||||
var latestVersion by remember { mutableStateOf<String?>(null) }
|
||||
LaunchedEffect(Unit) {
|
||||
latestVersion = ReleaseCheck.latestVersion()
|
||||
}
|
||||
|
||||
Box(modifier = Modifier.fillMaxSize().background(theme.background)) {
|
||||
Column(
|
||||
@@ -139,6 +155,27 @@ fun SettingsScreen(
|
||||
onCheckedChange = { controller.toggleStreaming() },
|
||||
)
|
||||
}
|
||||
if (streamingEnabled) {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Text("Streaming speed", fontSize = 12.sp, color = IrisColors.textDim)
|
||||
Text(
|
||||
"How fast new text appears while streaming — lower is faster",
|
||||
fontSize = 11.sp,
|
||||
color = IrisColors.textDim,
|
||||
)
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("Fast", fontSize = 12.sp, color = IrisColors.textDim)
|
||||
Slider(
|
||||
value = streamSmoothness,
|
||||
onValueChange = { controller.setStreamSmoothness(it) },
|
||||
valueRange = STREAM_SMOOTHNESS_MIN..STREAM_SMOOTHNESS_MAX,
|
||||
steps = 5, // 0.2 / 0.3 / 0.4 / 0.5 / 0.6 / 0.7 / 0.8
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text("Slow", fontSize = 12.sp, color = IrisColors.textDim)
|
||||
}
|
||||
}
|
||||
}
|
||||
SettingsCard {
|
||||
Row(
|
||||
@@ -159,6 +196,39 @@ fun SettingsScreen(
|
||||
)
|
||||
}
|
||||
}
|
||||
SettingsCard {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text("📊 Runtime footer", fontSize = 14.sp)
|
||||
Text(
|
||||
"Show model, context, workdir, latency and cost under replies",
|
||||
fontSize = 12.sp,
|
||||
color = IrisColors.textDim,
|
||||
)
|
||||
}
|
||||
Switch(
|
||||
checked = runtimeFooterEnabled,
|
||||
onCheckedChange = { controller.toggleRuntimeFooter() },
|
||||
)
|
||||
}
|
||||
if (runtimeFooterEnabled) {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Text("Fields to show", fontSize = 12.sp, color = IrisColors.textDim)
|
||||
Spacer(modifier = Modifier.height(6.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
IrisController.RUNTIME_FIELD_KEYS.forEach { field ->
|
||||
TopicChip(
|
||||
label = runtimeFieldLabel(field),
|
||||
selected = field in runtimeFooterFields,
|
||||
onClick = { controller.toggleRuntimeField(field) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Text(
|
||||
"Appearance",
|
||||
@@ -356,6 +426,37 @@ fun SettingsScreen(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Text(
|
||||
"Connection",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
modifier = Modifier.padding(top = 12.dp, bottom = 4.dp),
|
||||
)
|
||||
SettingsCard {
|
||||
Text("🔌 Forget pairing", fontSize = 14.sp)
|
||||
Text(
|
||||
"Clears the gateway token and wipes local chat history",
|
||||
fontSize = 12.sp,
|
||||
color = IrisColors.textDim,
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
TextButton(onClick = { showForgetConfirm = true }) {
|
||||
Text("Forget pairing", fontSize = 12.sp)
|
||||
}
|
||||
}
|
||||
|
||||
Text(
|
||||
"About",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
modifier = Modifier.padding(top = 12.dp, bottom = 4.dp),
|
||||
)
|
||||
SettingsCard {
|
||||
VersionCard(
|
||||
appVersion = AppVersion.VERSION,
|
||||
gatewayVersion = gatewayVersion,
|
||||
latestVersion = latestVersion,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
when (pickerTarget) {
|
||||
@@ -402,6 +503,32 @@ fun SettingsScreen(
|
||||
Unit
|
||||
}
|
||||
}
|
||||
|
||||
if (showForgetConfirm) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showForgetConfirm = false },
|
||||
title = { Text("Forget pairing?") },
|
||||
text = {
|
||||
Text(
|
||||
"This clears the gateway token and wipes all local chat history on this device. You'll need to pair again to reconnect.",
|
||||
fontSize = 13.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
showForgetConfirm = false
|
||||
controller.forget()
|
||||
}) {
|
||||
Text("Forget")
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showForgetConfirm = false }) {
|
||||
Text("Cancel")
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -430,6 +557,47 @@ private fun BackArrow(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* About card (docs/04 hello.ack note): app version (repo-root VERSION baked in
|
||||
* at build time), the connected gateway's version (hello.ack
|
||||
* `server_caps.app_version`), a mismatch hint, and the latest Gitea release
|
||||
* when the running build is older.
|
||||
*/
|
||||
@Composable
|
||||
private fun VersionCard(
|
||||
appVersion: String,
|
||||
gatewayVersion: String,
|
||||
latestVersion: String?,
|
||||
) {
|
||||
Text("📦 Version", fontSize = 14.sp)
|
||||
Text(
|
||||
"Iris app v$appVersion",
|
||||
fontSize = 12.sp,
|
||||
color = IrisColors.textSecondary,
|
||||
)
|
||||
if (gatewayVersion.isNotBlank()) {
|
||||
Text(
|
||||
"Gateway v$gatewayVersion",
|
||||
fontSize = 12.sp,
|
||||
color = IrisColors.textSecondary,
|
||||
)
|
||||
if (gatewayVersion != appVersion) {
|
||||
Text(
|
||||
"App and gateway versions differ — update the other side to match.",
|
||||
fontSize = 12.sp,
|
||||
color = IrisColors.statusAmber,
|
||||
)
|
||||
}
|
||||
}
|
||||
latestVersion?.takeIf { ReleaseCheck.isNewer(it, appVersion) }?.let { latest ->
|
||||
Text(
|
||||
"New version v$latest available — see the Gitea releases page.",
|
||||
fontSize = 12.sp,
|
||||
color = IrisColors.statusAmber,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Settings row container (panel card). */
|
||||
@Composable
|
||||
private fun SettingsCard(content: @Composable () -> Unit) {
|
||||
@@ -620,3 +788,14 @@ private fun argbToHsv(argb: Int): FloatArray {
|
||||
|
||||
/** File name from a path (no java.io.File in common code). */
|
||||
private fun fileNameOf(path: String): String = path.substringAfterLast('/').ifEmpty { path.substringAfterLast('\\') }
|
||||
|
||||
/** Human label for a runtime-footer field key (Settings → Runtime footer). */
|
||||
private fun runtimeFieldLabel(field: String): String =
|
||||
when (field) {
|
||||
"model" -> "Model"
|
||||
"context_pct" -> "Context %"
|
||||
"cwd" -> "Workdir"
|
||||
"latency" -> "Latency"
|
||||
"cost" -> "Cost"
|
||||
else -> field
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
package iris.ui.theme
|
||||
|
||||
/**
|
||||
* A bundled backdrop image shipped in the app (Android `assets/backdrops/`,
|
||||
* desktop classpath `backdrops/`), loaded via [iris.platform.readBackdropBytes].
|
||||
* A bundled backdrop image shipped in the app (Android: `androidApp` module
|
||||
* `assets/backdrops/`; desktop: classpath `backdrops/`), loaded via
|
||||
* [iris.platform.readBackdropBytes].
|
||||
*
|
||||
* Bundled backdrops are referenced in [UserTheme.backgroundImagePath] by the
|
||||
* sentinel path `backdrop://<id>` (see [path]); user-picked images use a real
|
||||
@@ -18,9 +19,12 @@ data class Backdrop(
|
||||
companion object {
|
||||
const val PATH_PREFIX = "backdrop://"
|
||||
|
||||
/** Default background for new chats / fresh installs. */
|
||||
val DEFAULT = Backdrop("pexels-yunszyveli-12368637", "Yun Syzveli")
|
||||
|
||||
val ALL: List<Backdrop> =
|
||||
listOf(
|
||||
Backdrop("pexels-yunszyveli-12368637", "Yun Syzveli"),
|
||||
DEFAULT,
|
||||
Backdrop("pexels-bogdankrupin-12049700", "Bogdan Krupin"),
|
||||
Backdrop("pexels-bosichong-27940302", "Bosi Chong"),
|
||||
Backdrop("pexels-farhan-najeer-644774196-32490483", "Farhan Najeer"),
|
||||
@@ -28,9 +32,6 @@ data class Backdrop(
|
||||
Backdrop("pexels-steve-29390703", "Steve"),
|
||||
)
|
||||
|
||||
/** Default background for new chats / fresh installs. */
|
||||
val DEFAULT: Backdrop = ALL.first { it.id == "pexels-yunszyveli-12368637" }
|
||||
|
||||
/** True when [path] references a bundled backdrop. */
|
||||
fun isBackdropPath(path: String?): Boolean = !path.isNullOrBlank() && path.startsWith(PATH_PREFIX)
|
||||
|
||||
|
||||
@@ -35,8 +35,6 @@ object IrisColors {
|
||||
val textDim = Color(0xFF8A93A6)
|
||||
|
||||
// Bubbles
|
||||
val bubbleUser = primary
|
||||
val bubbleAssistant = Color(0xFF2A2E3B)
|
||||
val bubbleCommentary = Color(0xFF23262F)
|
||||
|
||||
// Panels, chips, rows
|
||||
@@ -47,7 +45,6 @@ object IrisColors {
|
||||
val divider = Color(0xFF2A2E3B)
|
||||
|
||||
// Status
|
||||
val statusGrey = Color(0xFF9E9E9E)
|
||||
val statusAmber = Color(0xFFFFC107)
|
||||
val statusGreen = Color(0xFF4CAF50)
|
||||
val statusRed = Color(0xFFF44336)
|
||||
|
||||
@@ -25,16 +25,107 @@ fun String.prepareForMarkdown(): String {
|
||||
fun String.preserveNewlinesAsHardBreaks(): String {
|
||||
val lines = split("\n")
|
||||
var inCodeBlock = false
|
||||
val out = lines.map { line ->
|
||||
val trimmed = line.trimStart()
|
||||
when {
|
||||
trimmed.startsWith("```") || trimmed.startsWith("~~~") -> {
|
||||
inCodeBlock = !inCodeBlock
|
||||
line
|
||||
val out =
|
||||
lines.map { line ->
|
||||
val trimmed = line.trimStart()
|
||||
when {
|
||||
trimmed.startsWith("```") || trimmed.startsWith("~~~") -> {
|
||||
inCodeBlock = !inCodeBlock
|
||||
line
|
||||
}
|
||||
|
||||
inCodeBlock || line.isBlank() -> {
|
||||
line
|
||||
}
|
||||
|
||||
else -> {
|
||||
line + " "
|
||||
}
|
||||
}
|
||||
inCodeBlock || line.isBlank() -> line
|
||||
else -> line + " "
|
||||
}
|
||||
}
|
||||
return out.joinToString("\n")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Streaming variant of [preserveNewlinesAsHardBreaks]: identical, except the
|
||||
* trailing hard-break spaces are NOT added to the last (still-incomplete) line.
|
||||
*
|
||||
* This makes the transform *prefix-preserving*: for every prefix `p` of `s`,
|
||||
* `p.preserveNewlinesAsHardBreaksStreaming()` is a prefix of
|
||||
* `s.preserveNewlinesAsHardBreaksStreaming()`. That is what lets the streaming
|
||||
* renderer feed the diff between consecutive snapshots into an append-only
|
||||
* markdown parser (see `MarkdownText`). The final line's trailing spaces are
|
||||
* invisible at the end of the document, so a finished message renders exactly
|
||||
* like the static transform.
|
||||
*/
|
||||
fun String.preserveNewlinesAsHardBreaksStreaming(): String {
|
||||
val lines = split("\n")
|
||||
var inCodeBlock = false
|
||||
val out =
|
||||
lines.mapIndexed { index, line ->
|
||||
val trimmed = line.trimStart()
|
||||
when {
|
||||
trimmed.startsWith("```") || trimmed.startsWith("~~~") -> {
|
||||
inCodeBlock = !inCodeBlock
|
||||
line
|
||||
}
|
||||
|
||||
inCodeBlock || line.isBlank() -> {
|
||||
line
|
||||
}
|
||||
|
||||
index == lines.lastIndex -> {
|
||||
line
|
||||
}
|
||||
|
||||
// still being typed
|
||||
else -> {
|
||||
line + " "
|
||||
}
|
||||
}
|
||||
}
|
||||
return out.joinToString("\n")
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the suffix [next] adds on top of [last] (i.e. [next] minus its
|
||||
* [last] prefix), or `null` when [next] is NOT an extension of [last] — the
|
||||
* content was rewritten, not appended. The gateway sends full text snapshots
|
||||
* on every `message.update`; this converts them into append chunks for the
|
||||
* append-only streaming parser.
|
||||
*/
|
||||
fun appendChunk(
|
||||
last: String,
|
||||
next: String,
|
||||
): String? = if (next.startsWith(last)) next.substring(last.length) else null
|
||||
|
||||
/**
|
||||
* Number of characters to reveal on one streaming tick. The reveal rate comes
|
||||
* from the smoothness setting; when the backlog exceeds ~2 s of reveal time
|
||||
* (fast model, reconnect catch-up) everything is revealed at once so the
|
||||
* display never lags far behind the received text.
|
||||
*/
|
||||
fun revealStep(
|
||||
remaining: Int,
|
||||
charsPerSecond: Double,
|
||||
tickSeconds: Double,
|
||||
): Int {
|
||||
if (remaining <= 0) return 0
|
||||
if (remaining > charsPerSecond * 2.0) return remaining
|
||||
return maxOf(1, (charsPerSecond * tickSeconds).toInt())
|
||||
}
|
||||
|
||||
/**
|
||||
* Range of the streaming-smoothness setting (seconds between visible text
|
||||
* updates while streaming; lower = faster/smoother).
|
||||
*/
|
||||
const val STREAM_SMOOTHNESS_MIN = 0.2f
|
||||
const val STREAM_SMOOTHNESS_MAX = 0.8f
|
||||
const val STREAM_SMOOTHNESS_DEFAULT = 0.4f
|
||||
|
||||
/**
|
||||
* Reveal rate for a smoothness value. `60 / smoothness` keeps the display
|
||||
* well ahead of the gateway's arrival rate (~24 chars per 0.8 s) across the
|
||||
* whole range (0.2 → 300 chars/s, 0.8 → 75 chars/s).
|
||||
*/
|
||||
fun streamCharsPerSecond(smoothness: Float): Double = 60.0 / smoothness.coerceIn(STREAM_SMOOTHNESS_MIN, STREAM_SMOOTHNESS_MAX)
|
||||
@@ -0,0 +1,97 @@
|
||||
package iris.util
|
||||
|
||||
/**
|
||||
* A parsed `iris://pair` deep link: the gateway URL to connect to plus the
|
||||
* one-time pairing token. Produced by [PairLink.parse] from a scanned QR or a
|
||||
* tapped `iris://pair` link (docs/20).
|
||||
*/
|
||||
data class PairLink(
|
||||
val url: String,
|
||||
val token: String,
|
||||
) {
|
||||
companion object {
|
||||
/** Default gateway HTTP port (docs/19). */
|
||||
const val DEFAULT_PORT = 8791
|
||||
|
||||
/**
|
||||
* Parse a pairing link into a [PairLink], or return null on any
|
||||
* malformation.
|
||||
*
|
||||
* - scheme must be `iris` (case-insensitive); the URI host must be `pair`.
|
||||
* - required query params: `host` (non-empty) and `token` (non-empty).
|
||||
* - `port` defaults to [DEFAULT_PORT]; must be 1–65535 when present.
|
||||
* - `secure` defaults to `0`; `1` selects https.
|
||||
* - `host`/`token` are percent-decoded (the Python side `quote()`s them).
|
||||
*/
|
||||
fun parse(raw: String): PairLink? {
|
||||
val qIdx = raw.indexOf('?')
|
||||
val authority = if (qIdx >= 0) raw.substring(0, qIdx) else raw
|
||||
val query = if (qIdx >= 0) raw.substring(qIdx + 1) else ""
|
||||
|
||||
// authority is "iris://pair": scheme, then "://", then the URI host.
|
||||
val sep = authority.indexOf("://")
|
||||
if (sep <= 0) return null
|
||||
val scheme = authority.substring(0, sep)
|
||||
val uriHost = authority.substring(sep + 3)
|
||||
if (scheme.lowercase() != "iris") return null
|
||||
if (uriHost.lowercase() != "pair") return null
|
||||
|
||||
val params = parseQuery(query)
|
||||
val host = params["host"]?.let { percentDecode(it) }?.trim().orEmpty()
|
||||
val token = params["token"]?.let { percentDecode(it) }?.trim().orEmpty()
|
||||
if (host.isEmpty() || token.isEmpty()) return null
|
||||
|
||||
val portRaw = params["port"]
|
||||
val port =
|
||||
if (portRaw.isNullOrEmpty()) {
|
||||
DEFAULT_PORT
|
||||
} else {
|
||||
portRaw.toIntOrNull() ?: return null
|
||||
}
|
||||
if (port !in 1..65535) return null
|
||||
val secure = params["secure"]?.toIntOrNull() ?: 0
|
||||
val urlScheme = if (secure == 1) "https" else "http"
|
||||
return PairLink("$urlScheme://$host:$port", token)
|
||||
}
|
||||
|
||||
/** Split a `k=v&k=v` query string into a map (values may be empty). */
|
||||
private fun parseQuery(query: String): Map<String, String> {
|
||||
if (query.isEmpty()) return emptyMap()
|
||||
val map = LinkedHashMap<String, String>()
|
||||
for (pair in query.split('&')) {
|
||||
if (pair.isEmpty()) continue
|
||||
val eq = pair.indexOf('=')
|
||||
if (eq < 0) {
|
||||
map[pair] = ""
|
||||
} else {
|
||||
map[pair.substring(0, eq)] = pair.substring(eq + 1)
|
||||
}
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
/**
|
||||
* Percent-decode `%XX` sequences (byte-wise; pairing payloads are ASCII
|
||||
* — IPs and 64-hex tokens). A `%` that does not start a valid
|
||||
* two-hex-digit escape is kept literally.
|
||||
*/
|
||||
private fun percentDecode(s: String): String {
|
||||
val sb = StringBuilder(s.length)
|
||||
var i = 0
|
||||
while (i < s.length) {
|
||||
val c = s[i]
|
||||
if (c == '%' && i + 2 < s.length) {
|
||||
val code = s.substring(i + 1, i + 3).toIntOrNull(16)
|
||||
if (code != null) {
|
||||
sb.append(code.toChar())
|
||||
i += 3
|
||||
continue
|
||||
}
|
||||
}
|
||||
sb.append(c)
|
||||
i++
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,3 @@ expect fun localDayKey(epochMillis: Long): String
|
||||
|
||||
/** Current wall-clock time in epoch milliseconds (for locally generated items). */
|
||||
expect fun nowMillis(): Long
|
||||
|
||||
/** Host part of a pairing URL ("ws://host:port/ws" -> "host:port"). */
|
||||
fun hostFromUrl(url: String): String {
|
||||
val noScheme = url.trim().substringAfter("://")
|
||||
return noScheme.substringBefore("/").ifBlank { url.trim() }
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
-- Local cache (docs/10 §10.7, docs/16 "Local DB (KMP) — SQLDelight").
|
||||
-- The server is authoritative; this is a cache that lets the app start
|
||||
-- instantly and read chats offline. Rows are stored as JSON payloads so the
|
||||
-- schema does not drift with the Kotlin model fields.
|
||||
|
||||
CREATE TABLE message (
|
||||
lane TEXT NOT NULL, -- lane key: chatId or chatId::threadId
|
||||
id TEXT NOT NULL, -- message id (server id, or local<rand>/sys<rand> for optimistic)
|
||||
ts INTEGER NOT NULL, -- epoch millis (0 for optimistic, not yet echoed)
|
||||
payload TEXT NOT NULL, -- serialized MessageItem
|
||||
PRIMARY KEY (lane, id)
|
||||
);
|
||||
|
||||
CREATE TABLE tool (
|
||||
lane TEXT NOT NULL, -- lane key: chatId or chatId::threadId
|
||||
id TEXT NOT NULL, -- local tool card id (tool<rand>)
|
||||
seq INTEGER NOT NULL, -- card order within the lane (lane position)
|
||||
payload TEXT NOT NULL, -- serialized ToolItem (carries its anchor_id)
|
||||
PRIMARY KEY (lane, id)
|
||||
);
|
||||
|
||||
CREATE TABLE channel (
|
||||
chat_id TEXT NOT NULL PRIMARY KEY,
|
||||
payload TEXT NOT NULL -- serialized ChannelInfo
|
||||
);
|
||||
|
||||
CREATE TABLE meta (
|
||||
key TEXT NOT NULL PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
|
||||
allMessages:
|
||||
SELECT lane, id, ts, payload
|
||||
FROM message
|
||||
ORDER BY ts, id;
|
||||
|
||||
upsertMessage:
|
||||
INSERT OR REPLACE INTO message (lane, id, ts, payload)
|
||||
VALUES (?, ?, ?, ?);
|
||||
|
||||
clearMessages:
|
||||
DELETE FROM message;
|
||||
|
||||
allTools:
|
||||
SELECT lane, seq, payload
|
||||
FROM tool
|
||||
ORDER BY lane, seq;
|
||||
|
||||
upsertTool:
|
||||
INSERT OR REPLACE INTO tool (lane, id, seq, payload)
|
||||
VALUES (?, ?, ?, ?);
|
||||
|
||||
clearTools:
|
||||
DELETE FROM tool;
|
||||
|
||||
allChannels:
|
||||
SELECT chat_id, payload
|
||||
FROM channel;
|
||||
|
||||
upsertChannel:
|
||||
INSERT OR REPLACE INTO channel (chat_id, payload)
|
||||
VALUES (?, ?);
|
||||
|
||||
clearChannels:
|
||||
DELETE FROM channel;
|
||||
|
||||
metaGet:
|
||||
SELECT value
|
||||
FROM meta
|
||||
WHERE key = ?;
|
||||
|
||||
metaPut:
|
||||
INSERT OR REPLACE INTO meta (key, value)
|
||||
VALUES (?, ?);
|
||||
|
||||
clearMeta:
|
||||
DELETE FROM meta;
|
||||
@@ -0,0 +1,9 @@
|
||||
-- v1 -> v2: persist tool cards (M-cache: tool cards survive a restart,
|
||||
-- anchored to the message they follow — see ChatDb.loadLanes).
|
||||
CREATE TABLE tool (
|
||||
lane TEXT NOT NULL,
|
||||
id TEXT NOT NULL,
|
||||
seq INTEGER NOT NULL,
|
||||
payload TEXT NOT NULL,
|
||||
PRIMARY KEY (lane, id)
|
||||
);
|
||||
@@ -0,0 +1,155 @@
|
||||
package iris.data
|
||||
|
||||
import iris.protocol.Frame
|
||||
import iris.protocol.IrisJson
|
||||
import iris.protocol.TYPE_TODO_UPDATE
|
||||
import iris.protocol.TYPE_TOOL_START
|
||||
import iris.protocol.TodoItem
|
||||
import iris.protocol.TodoUpdatePayload
|
||||
import iris.protocol.ToolStartPayload
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNull
|
||||
|
||||
class ChatStoreCacheTest {
|
||||
@Test
|
||||
fun loadFromCachePopulatesLanes() {
|
||||
val store = ChatStore()
|
||||
store.loadFromCache(
|
||||
mapOf(
|
||||
"default" to
|
||||
listOf<ChatItem>(
|
||||
MessageItem(id = "m1", role = "user", text = "hi", ts = 1),
|
||||
ToolItem(id = "tool_1", index = 0, name = "bash", done = true, anchorId = "m1"),
|
||||
MessageItem(id = "m2", role = "assistant", text = "hello", ts = 2),
|
||||
),
|
||||
),
|
||||
)
|
||||
assertEquals(listOf("m1", "tool_1", "m2"), store.lanes.value["default"]!!.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun loadFromCacheEmptyIsNoOp() {
|
||||
val store = ChatStore()
|
||||
store.addPending("hello", "default")
|
||||
store.loadFromCache(emptyMap())
|
||||
assertEquals(1, store.lanes.value["default"]!!.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun loadHistoryKeepsToolCardsAtAnchor() {
|
||||
val store = ChatStore()
|
||||
// Lane as restored from the cache: user message, tool card anchored
|
||||
// to it, and the final answer.
|
||||
store.loadFromCache(
|
||||
mapOf(
|
||||
"default" to
|
||||
listOf<ChatItem>(
|
||||
MessageItem(id = "m1", role = "user", text = "count", ts = 100),
|
||||
ToolItem(id = "tool_1", index = 0, name = "terminal", done = true, anchorId = "m1"),
|
||||
MessageItem(id = "m2", role = "assistant", text = "16", ts = 200),
|
||||
),
|
||||
),
|
||||
)
|
||||
// A history refresh (authoritative messages, no tool cards) must keep
|
||||
// the tool card between the user message and the answer — not push
|
||||
// it to the end.
|
||||
store.loadHistory(
|
||||
"default",
|
||||
listOf(
|
||||
MessageItem(id = "m1", role = "user", text = "count", ts = 100),
|
||||
MessageItem(id = "m2", role = "assistant", text = "16", ts = 200),
|
||||
),
|
||||
)
|
||||
assertEquals(listOf("m1", "tool_1", "m2"), store.lanes.value["default"]!!.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun loadHistoryDedupesAndKeepsUnanchoredToolsLast() {
|
||||
val store = ChatStore()
|
||||
store.loadFromCache(
|
||||
mapOf(
|
||||
"default" to
|
||||
listOf<ChatItem>(
|
||||
MessageItem(id = "m1", role = "user", text = "count", ts = 100),
|
||||
ToolItem(id = "tool_1", index = 0, name = "bash", done = true),
|
||||
),
|
||||
),
|
||||
)
|
||||
store.loadHistory(
|
||||
"default",
|
||||
listOf(MessageItem(id = "m1", role = "user", text = "count", ts = 100)),
|
||||
)
|
||||
// A card whose anchor is unknown falls to the end (degenerate case).
|
||||
assertEquals(listOf("m1", "tool_1"), store.lanes.value["default"]!!.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun toolStartIdsNeverCollideWithRestoredCards() {
|
||||
val store = ChatStore()
|
||||
// Lane restored from the cache after a restart, holding a persisted
|
||||
// card minted by the PREVIOUS process.
|
||||
store.loadFromCache(
|
||||
mapOf(
|
||||
"default" to
|
||||
listOf<ChatItem>(
|
||||
MessageItem(id = "m1", role = "user", text = "hi", ts = 1),
|
||||
ToolItem(id = "tool_1", index = 0, name = "bash", done = true, anchorId = "m1"),
|
||||
),
|
||||
),
|
||||
)
|
||||
// A new turn must not re-mint an id the restored lane already holds
|
||||
// (duplicate LazyColumn key / upsert overwrite under the same PK).
|
||||
store.onFrame(
|
||||
Frame(
|
||||
type = TYPE_TOOL_START,
|
||||
chatId = "iris:other",
|
||||
payload =
|
||||
IrisJson.instance.encodeToJsonElement(
|
||||
ToolStartPayload.serializer(),
|
||||
ToolStartPayload(index = 0, name = "terminal", preview = "ls"),
|
||||
),
|
||||
),
|
||||
)
|
||||
val ids = store.lanes.value["default"]!!.map { it.id }
|
||||
assertEquals(ids.size, ids.toSet().size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun todoUpdateSetsLaneListLastWriteWins() {
|
||||
val store = ChatStore()
|
||||
assertNull(store.todos.value["default"])
|
||||
store.onFrame(todoFrame("default", listOf(TodoItem("1", "a", "in_progress"))))
|
||||
assertEquals(listOf("1"), store.todos.value["default"]!!.map { it.id })
|
||||
// A second update REPLACES the list (the gateway always sends the
|
||||
// full list), and other lanes are untouched.
|
||||
store.onFrame(
|
||||
todoFrame(
|
||||
"default",
|
||||
listOf(TodoItem("1", "a", "completed"), TodoItem("2", "b", "pending")),
|
||||
),
|
||||
)
|
||||
store.onFrame(todoFrame("chan_7", listOf(TodoItem("9", "z", "pending"))))
|
||||
assertEquals(listOf("1", "2"), store.todos.value["default"]!!.map { it.id })
|
||||
assertEquals("completed", store.todos.value["default"]!![0].status)
|
||||
assertEquals(listOf("9"), store.todos.value["chan_7"]!!.map { it.id })
|
||||
// An empty list clears the lane (the agent dropped its plan).
|
||||
store.onFrame(todoFrame("default", emptyList()))
|
||||
assertNull(store.todos.value["default"])
|
||||
assertEquals(listOf("9"), store.todos.value["chan_7"]!!.map { it.id })
|
||||
}
|
||||
|
||||
private fun todoFrame(
|
||||
chatId: String,
|
||||
todos: List<TodoItem>,
|
||||
): Frame =
|
||||
Frame(
|
||||
type = TYPE_TODO_UPDATE,
|
||||
chatId = chatId,
|
||||
payload =
|
||||
IrisJson.instance.encodeToJsonElement(
|
||||
TodoUpdatePayload.serializer(),
|
||||
TodoUpdatePayload(todos = todos),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package iris.data
|
||||
|
||||
import iris.protocol.Frame
|
||||
import iris.protocol.IrisJson
|
||||
import iris.protocol.PickerChoice
|
||||
import iris.protocol.PickerChoicePayload
|
||||
import iris.protocol.TYPE_PICKER_CHOICE
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertIs
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class ChatStorePickerTest {
|
||||
private fun pickerFrame(
|
||||
pickerId: String,
|
||||
title: String = "Reasoning",
|
||||
chatId: String = "chan_1",
|
||||
): Frame =
|
||||
Frame(
|
||||
type = TYPE_PICKER_CHOICE,
|
||||
chatId = chatId,
|
||||
payload =
|
||||
IrisJson.instance.encodeToJsonElement(
|
||||
PickerChoicePayload.serializer(),
|
||||
PickerChoicePayload(
|
||||
pickerId = pickerId,
|
||||
title = title,
|
||||
choices =
|
||||
listOf(
|
||||
PickerChoice(value = "low", label = "Low"),
|
||||
PickerChoice(value = "high", label = "High", isCurrent = true),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
@Test
|
||||
fun onPickerChoiceAddsItem() {
|
||||
val store = ChatStore()
|
||||
store.onFrame(pickerFrame("pk_1"))
|
||||
val items = store.lanes.value["chan_1"]!!
|
||||
assertEquals(1, items.size)
|
||||
val picker = assertIs<PickerItem>(items[0])
|
||||
assertEquals("pk_1", picker.id)
|
||||
assertEquals("Reasoning", picker.title)
|
||||
assertEquals(2, picker.choices.size)
|
||||
assertNull(picker.selected)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onPickerChoiceIsIdempotent() {
|
||||
val store = ChatStore()
|
||||
store.onFrame(pickerFrame("pk_1"))
|
||||
store.onFrame(pickerFrame("pk_1")) // duplicate (e.g. outbox re-delivery)
|
||||
val items = store.lanes.value["chan_1"]!!
|
||||
assertEquals(1, items.size)
|
||||
assertEquals("pk_1", items[0].id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolvePickerMarksSelected() {
|
||||
val store = ChatStore()
|
||||
store.onFrame(pickerFrame("pk_1"))
|
||||
store.resolvePicker("pk_1", "low")
|
||||
val picker = assertIs<PickerItem>(store.lanes.value["chan_1"]!![0])
|
||||
assertEquals("low", picker.selected)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolvePickerIsOneShot() {
|
||||
val store = ChatStore()
|
||||
store.onFrame(pickerFrame("pk_1"))
|
||||
store.resolvePicker("pk_1", "low")
|
||||
store.resolvePicker("pk_1", "high") // second tap is ignored
|
||||
val picker = assertIs<PickerItem>(store.lanes.value["chan_1"]!![0])
|
||||
assertEquals("low", picker.selected)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolvePickerUnknownIdIsNoop() {
|
||||
val store = ChatStore()
|
||||
store.onFrame(pickerFrame("pk_1"))
|
||||
store.resolvePicker("pk_missing", "low") // stale select after restart
|
||||
val picker = assertIs<PickerItem>(store.lanes.value["chan_1"]!![0])
|
||||
assertNull(picker.selected)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pickerItemSerializationRoundTrip() {
|
||||
val item =
|
||||
PickerItem(
|
||||
id = "pk_1",
|
||||
title = "Reasoning",
|
||||
choices =
|
||||
listOf(
|
||||
PickerChoice(value = "low", label = "Low"),
|
||||
PickerChoice(value = "high", label = "High", isCurrent = true),
|
||||
),
|
||||
ts = 1234L,
|
||||
selected = "high",
|
||||
)
|
||||
val json = IrisJson.instance.encodeToString(PickerItem.serializer(), item)
|
||||
val back = IrisJson.instance.decodeFromString(PickerItem.serializer(), json)
|
||||
assertEquals(item, back)
|
||||
assertTrue(back.choices[1].isCurrent)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package iris.data
|
||||
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNull
|
||||
|
||||
/**
|
||||
* M8: per-lane unread tracking (the data behind the channel-view / header
|
||||
* unread indicator). The increment/clear *policy* (which incoming message is
|
||||
* "being read") lives in IrisController; here we cover the store's count
|
||||
* semantics that the UI and controller build on.
|
||||
*/
|
||||
class ChatStoreUnreadTest {
|
||||
@Test
|
||||
fun markUnreadIncrementsPerLane() {
|
||||
val store = ChatStore()
|
||||
assertEquals(0, store.unreadFor("default"))
|
||||
store.markUnread("default")
|
||||
store.markUnread("default")
|
||||
store.markUnread("chan_7")
|
||||
assertEquals(2, store.unreadFor("default"))
|
||||
assertEquals(1, store.unreadFor("chan_7"))
|
||||
// A lane that never had a message stays at 0.
|
||||
assertEquals(0, store.unreadFor("chan_9"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun markLaneReadClearsOnlyThatLane() {
|
||||
val store = ChatStore()
|
||||
store.markUnread("default")
|
||||
store.markUnread("chan_7")
|
||||
store.markLaneRead("default")
|
||||
assertEquals(0, store.unreadFor("default"))
|
||||
// Other lanes are untouched.
|
||||
assertEquals(1, store.unreadFor("chan_7"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun markLaneReadIsIdempotent() {
|
||||
val store = ChatStore()
|
||||
store.markLaneRead("default") // no unread -> no-op
|
||||
assertEquals(0, store.unreadFor("default"))
|
||||
store.markUnread("default")
|
||||
store.markLaneRead("default")
|
||||
store.markLaneRead("default") // clearing twice is safe
|
||||
assertEquals(0, store.unreadFor("default"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unreadMapReflectsCounts() {
|
||||
val store = ChatStore()
|
||||
assertNull(store.unread.value["default"])
|
||||
store.markUnread("default")
|
||||
assertEquals(1, store.unread.value["default"])
|
||||
store.markLaneRead("default")
|
||||
// A cleared lane is removed from the map (absent == 0 unread).
|
||||
assertNull(store.unread.value["default"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clearWipesUnread() {
|
||||
val store = ChatStore()
|
||||
store.markUnread("default")
|
||||
store.markUnread("chan_7")
|
||||
store.clear()
|
||||
assertEquals(0, store.unreadFor("default"))
|
||||
assertEquals(0, store.unreadFor("chan_7"))
|
||||
assertEquals(emptyMap(), store.unread.value)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package iris.net
|
||||
|
||||
import iris.protocol.Frame
|
||||
import iris.protocol.IrisJson
|
||||
import iris.protocol.MessagePayload
|
||||
import iris.protocol.TYPE_MESSAGE
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
/**
|
||||
* docs/19: unit tests for the HTTP fallback leg client.
|
||||
*
|
||||
* The SSE line parser is the trickiest pure logic (event/id/data fields,
|
||||
* comments, multi-line data, Last-Event-ID bookkeeping), so it is factored
|
||||
* into [SseParser] and tested directly. The WS->HTTP URL derivation is a
|
||||
* pure function (unit-tested). Full transport behavior (health, POST, SSE
|
||||
* catch-up, long-poll, delivery counting) is covered by the gateway-side
|
||||
* Python tests (hermes-agent/tests/gateway/test_android_http.py).
|
||||
*/
|
||||
class HttpGatewayTest {
|
||||
// ── URL derivation ────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
fun deriveHttpUrlReplacesSchemeAndPort() {
|
||||
assertEquals("http://192.168.1.10:8791", HttpGateway.deriveHttpUrl("ws://192.168.1.10:8790/ws"))
|
||||
assertEquals("http://127.0.0.1:8791", HttpGateway.deriveHttpUrl("ws://127.0.0.1:8790/ws"))
|
||||
assertEquals("https://gw.example.com:8791", HttpGateway.deriveHttpUrl("wss://gw.example.com:8790/ws"))
|
||||
// No explicit port on the WS URL: still the HTTP leg's default port.
|
||||
assertEquals("http://gw.example.com:8791", HttpGateway.deriveHttpUrl("ws://gw.example.com/ws"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun deriveHttpUrlPassesThroughHttpUrls() {
|
||||
assertEquals("http://1.2.3.4:9000", HttpGateway.deriveHttpUrl("http://1.2.3.4:9000"))
|
||||
assertEquals("https://a.b", HttpGateway.deriveHttpUrl("https://a.b"))
|
||||
}
|
||||
|
||||
// ── SSE parser ────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
fun sseParsesHelloAndFrames() {
|
||||
val parser = SseParser()
|
||||
val hello = """{"v":1,"type":"hello.ack","payload":{"sync_cursor":5}}"""
|
||||
val frame = """{"v":1,"type":"$TYPE_MESSAGE","payload":{"text":"hi"}}"""
|
||||
val lines =
|
||||
listOf(
|
||||
"event: hello",
|
||||
"data: $hello",
|
||||
"",
|
||||
"id: 7",
|
||||
"event: frame",
|
||||
"data: $frame",
|
||||
"",
|
||||
)
|
||||
var helloCount = 0
|
||||
var frameCount = 0
|
||||
var lastCursor: Long? = null
|
||||
for (line in lines) {
|
||||
parser.feed(
|
||||
line,
|
||||
onHello = { helloCount++ },
|
||||
onFrame = { frameCount++ },
|
||||
onCursor = { lastCursor = it },
|
||||
)
|
||||
}
|
||||
assertEquals(1, helloCount)
|
||||
assertEquals(1, frameCount)
|
||||
assertEquals(7L, lastCursor)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sseIgnoresHeartbeatComments() {
|
||||
val parser = SseParser()
|
||||
var frames = 0
|
||||
parser.feed(": hb", onHello = {}, onFrame = { frames++ }, onCursor = {})
|
||||
parser.feed("", onHello = {}, onFrame = { frames++ }, onCursor = {})
|
||||
assertEquals(0, frames)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sseMultiLineDataJoinsWithNewline() {
|
||||
val parser = SseParser()
|
||||
var frame: Frame? = null
|
||||
// SSE data may span multiple `data:` lines; the parser must join
|
||||
// them with "\n" so the reassembled JSON still decodes. Split at a
|
||||
// legal JSON whitespace point (right after a comma, between tokens).
|
||||
val full =
|
||||
"""{"v":1,"type":"$TYPE_MESSAGE","payload":{"message_id":"m1","role":"assistant","text":"a\nb"}}"""
|
||||
val cut = full.indexOf("\"m1\",") + "\"m1\",".length
|
||||
val l1 = full.substring(0, cut)
|
||||
val l2 = full.substring(cut)
|
||||
parser.feed("event: frame", onHello = {}, onFrame = {}, onCursor = {})
|
||||
parser.feed("data: $l1", onHello = {}, onFrame = {}, onCursor = {})
|
||||
parser.feed("data: $l2", onHello = {}, onFrame = {}, onCursor = {})
|
||||
parser.feed("", onHello = {}, onFrame = { frame = it }, onCursor = {})
|
||||
assertEquals("a\nb", frame?.payloadAsText())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sseTracksLastEventIdAcrossFrames() {
|
||||
val parser = SseParser()
|
||||
val ids = mutableListOf<Long>()
|
||||
val frame = """{"v":1,"type":"$TYPE_MESSAGE","payload":{}}"""
|
||||
for (id in listOf(1L, 2L, 3L)) {
|
||||
parser.feed("id: $id", onHello = {}, onFrame = {}, onCursor = { ids.add(it) })
|
||||
parser.feed("event: frame", onHello = {}, onFrame = {}, onCursor = {})
|
||||
parser.feed("data: $frame", onHello = {}, onFrame = {}, onCursor = {})
|
||||
parser.feed("", onHello = {}, onFrame = {}, onCursor = {})
|
||||
}
|
||||
assertEquals(listOf(1L, 2L, 3L), ids)
|
||||
assertEquals(3L, parser.lastEventId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sseMalformedLineDoesNotThrow() {
|
||||
val parser = SseParser()
|
||||
parser.feed("garbage without colon", onHello = {}, onFrame = {}, onCursor = {})
|
||||
parser.feed("id: notanumber", onHello = {}, onFrame = {}, onCursor = {})
|
||||
parser.feed("data: {not json", onHello = {}, onFrame = {}, onCursor = {})
|
||||
parser.feed("", onHello = {}, onFrame = {}, onCursor = {})
|
||||
// No exception, no frame emitted for the malformed data.
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sseDecodesFramePayload() {
|
||||
val parser = SseParser()
|
||||
var text: String? = null
|
||||
val frame =
|
||||
"""{"v":1,"type":"$TYPE_MESSAGE","payload":{"message_id":"m1","role":"assistant","text":"hello"}}"""
|
||||
parser.feed("event: frame", onHello = {}, onFrame = {}, onCursor = {})
|
||||
parser.feed("data: $frame", onHello = {}, onFrame = {}, onCursor = {})
|
||||
parser.feed("", onHello = {}, onFrame = { f -> text = f.payloadAsText() }, onCursor = {})
|
||||
assertEquals("hello", text)
|
||||
}
|
||||
}
|
||||
|
||||
// ── SSE line parser (pure; shared by the live reader + tests) ─────────────
|
||||
|
||||
/**
|
||||
* Incremental SSE parser (docs/19 §19.5). Feed raw lines (without
|
||||
* terminators); a blank line dispatches the buffered event. [lastEventId]
|
||||
* is the most recent `id:` field (the outbox cursor) — the resume point for
|
||||
* a reconnect.
|
||||
*/
|
||||
class SseParser {
|
||||
var lastEventId: Long? = null
|
||||
private set
|
||||
|
||||
private var eventId: String? = null
|
||||
private val dataLines = mutableListOf<String>()
|
||||
|
||||
fun feed(
|
||||
line: String,
|
||||
onHello: (String) -> Unit,
|
||||
onFrame: (Frame) -> Unit,
|
||||
onCursor: (Long) -> Unit,
|
||||
) {
|
||||
when {
|
||||
line.isEmpty() -> {
|
||||
if (dataLines.isNotEmpty()) {
|
||||
val data = dataLines.joinToString("\n")
|
||||
val frame =
|
||||
try {
|
||||
IrisJson.instance.decodeFromString(Frame.serializer(), data)
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
if (frame != null) {
|
||||
when (eventId) {
|
||||
"hello" -> onHello(data)
|
||||
else -> onFrame(frame)
|
||||
}
|
||||
}
|
||||
}
|
||||
eventId = null
|
||||
dataLines.clear()
|
||||
}
|
||||
|
||||
line.startsWith(":") -> {
|
||||
Unit
|
||||
}
|
||||
|
||||
// comment / heartbeat
|
||||
line.startsWith("id:") -> {
|
||||
val id = line.removePrefix("id:").trim().toLongOrNull()
|
||||
if (id != null) {
|
||||
lastEventId = id
|
||||
onCursor(id)
|
||||
}
|
||||
}
|
||||
|
||||
line.startsWith("event:") -> {
|
||||
eventId = line.removePrefix("event:").trim()
|
||||
}
|
||||
|
||||
line.startsWith("data:") -> {
|
||||
dataLines.add(line.removePrefix("data:").removePrefix(" "))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun Frame.payloadAsText(): String? = payloadAs<MessagePayload>()?.text
|
||||
@@ -0,0 +1,163 @@
|
||||
package iris.net
|
||||
|
||||
import com.sun.net.httpserver.HttpsConfigurator
|
||||
import com.sun.net.httpserver.HttpsServer
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.net.InetSocketAddress
|
||||
import java.security.KeyFactory
|
||||
import java.security.KeyStore
|
||||
import java.security.cert.CertificateFactory
|
||||
import java.security.spec.PKCS8EncodedKeySpec
|
||||
import java.util.Base64
|
||||
import javax.net.ssl.KeyManagerFactory
|
||||
import javax.net.ssl.SSLContext
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFailsWith
|
||||
import kotlin.test.assertNotNull
|
||||
|
||||
/**
|
||||
* docs/09 §9.4: end-to-end test of the fingerprint-confirm flow over a real
|
||||
* TLS handshake: a local HTTPS server presents the embedded self-signed
|
||||
* certificate (SAN: 127.0.0.1) to an OkHttp client wired exactly like
|
||||
* [GatewayClient] (pinning socket factory + trust manager).
|
||||
*
|
||||
* 1. Unpinned: the handshake fails and [tlsFingerprintRequired] unwraps the
|
||||
* presented fingerprint from the nested exception.
|
||||
* 2. After "confirming" (setting the pin): the SAME client connects — the
|
||||
* pin is read live, no client rebuild.
|
||||
*
|
||||
* The embedded key is a throwaway test key, not a secret.
|
||||
*/
|
||||
class TlsPinningIntegrationTest {
|
||||
private companion object {
|
||||
// Self-signed with SAN DNS:localhost, IP:127.0.0.1 (OkHttp's hostname
|
||||
// verifier requires a SAN; CN-only certs are rejected even when pinned).
|
||||
val CERT_PEM =
|
||||
"""
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIC+zCCAeOgAwIBAgIUGXu+y1gH9kUWHAFlHOzrN3h2TRQwDQYJKoZIhvcNAQEL
|
||||
BQAwGDEWMBQGA1UEAwwNaXJpcy1pbnQtdGVzdDAeFw0yNjA4MjQxOTE1MTJaFw0z
|
||||
NjA4MjExOTE1MTJaMBgxFjAUBgNVBAMMDWlyaXMtaW50LXRlc3QwggEiMA0GCSqG
|
||||
SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtqNGuSQm7iO2GuQ+TemTZsThzPVkWrfdF
|
||||
/R25eCHTVSHfpXnlI2gXgRf5sBMLLOKVD/eTynelf2zcfuJqwYjCc6aOv1I9Fz2C
|
||||
Eb+GBeyLHwmh4hSrMeN3YnoeaCmZzvbqNCpjEEmmw13Heptg6ZBcwISpE+78WVFT
|
||||
qIeMGJ7/5X9cvoVebrQ6eV0LVGmzz5iqMp9uwoPeHnT7bGN3YXO9TSbjogSQbzRs
|
||||
PS/JcZIFIUsfbOYRbNogd3v9SfKCfz9Q2J7EB8sBx8eCqXn5Q9avxk/VVYxjQL9a
|
||||
GqxRCp4uCgQZt3GACZYvGzbMRFGNFlvhoYf20jE7Hly7OrYzJ4v7AgMBAAGjPTA7
|
||||
MBoGA1UdEQQTMBGCCWxvY2FsaG9zdIcEfwAAATAdBgNVHQ4EFgQUA9qqz6IWojYd
|
||||
WSbngx8h5vq9CTYwDQYJKoZIhvcNAQELBQADggEBAGNIGSCEy1A42UNUd+xREsHm
|
||||
EmBJ7TYzxJjmweByJwdK5GjxmpaOXgcBjUb8O0Fzm8+4P2DDr/CXhv+aNYUcSCJ3
|
||||
Xf5cBIXzJmTVvkLzdNpCmB9w2d66J2ZQYxCOZ4pUzvcXI6gK7qkrB2HALq2LYGtE
|
||||
dxVocLizu+FGtf4ve+CuCZs3/tJaQPZYzP4UqV1oVfkg3hV+Yg1oFYFfrAelsFkw
|
||||
zNjVh2jTwFiEpK5E/4OJtQaThOUkbkNcSc50ATYkPau9mA1IUTsOU/UNjMTbYtG0
|
||||
Ht5KgYObXkwm44X0rgiGHgW61wqgIEa5ogfVIeCJzHwHNcn2J9yYlgYsZ/o8vrU=
|
||||
-----END CERTIFICATE-----
|
||||
""".trimIndent()
|
||||
|
||||
val KEY_PEM =
|
||||
"""
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCtqNGuSQm7iO2G
|
||||
uQ+TemTZsThzPVkWrfdF/R25eCHTVSHfpXnlI2gXgRf5sBMLLOKVD/eTynelf2zc
|
||||
fuJqwYjCc6aOv1I9Fz2CEb+GBeyLHwmh4hSrMeN3YnoeaCmZzvbqNCpjEEmmw13H
|
||||
eptg6ZBcwISpE+78WVFTqIeMGJ7/5X9cvoVebrQ6eV0LVGmzz5iqMp9uwoPeHnT7
|
||||
bGN3YXO9TSbjogSQbzRsPS/JcZIFIUsfbOYRbNogd3v9SfKCfz9Q2J7EB8sBx8eC
|
||||
qXn5Q9avxk/VVYxjQL9aGqxRCp4uCgQZt3GACZYvGzbMRFGNFlvhoYf20jE7Hly7
|
||||
OrYzJ4v7AgMBAAECggEABKYo2uQcrRcY2Mr6hkW4DnXmn3ssd+V3YbnJgm4bZbd5
|
||||
PS4GaeJ9RmfP1wDmOZ3dgQUY6S1574XOScbh097ThPUop9iqYHVPUbyc5n8hGoZd
|
||||
sSZGzGB9CPSrdUXvmy0FwjZcTiOg/SRszcrT/w+xrDIBOy+L7diMS1OPMWp1Uz9r
|
||||
yHHxpjMtALToaMUHMNCRjyFRR0fgqGWnfwRVAwdKMxMQJZ0IiUXyuqgpdIBHZC+g
|
||||
WIcntUDCiglHtuI34eoQQVVMhEm2ylaAq2tBaR7z3wGtXbbfdyWUi/DIkhS5o4HN
|
||||
ux7AYF87WU87/0I8GpEQHdAFQKoqVgR8uaZmJ613YQKBgQDmcGZdYg4UtcjTVSDE
|
||||
BHsLnFzapSjDebVsR2XWoztcvQIduqsh+2zV8RN3UGIOd7l9tEGWMm7rFFVOOs/f
|
||||
utCAd4v5ZWtSs/KtSuL6PqbFuvD9jGVPaqsSAe/2WmAtG8vA/JIndFDC5CNo/Hem
|
||||
Tj7XGAmEPKgTRLR9NY1fu0we2wKBgQDA7BemZXViw4RiEjUcsqX8yuFPGKlMyoCK
|
||||
ieHsIO05dLD+s6BD7r8ang0twttwhCM4RoumxjEbEbRYMhu0EJKiC+wl53EM1Vcu
|
||||
OBQAlgKMVGXKmp0K/moYOIdvb4JuHoITaYhKPyO+2/2rKLK3h+swnYJDrpOcOK7H
|
||||
yqy1qeMBYQKBgQDRt+GxgxfFiVtn2cWkH1/MRVXMNxtOK2oNTT1FhfD0iZ9vZv9w
|
||||
Qd3fJzPMFn/nItbRrEc0ZlnD4BFyzNt6hg5TnHjrVH3EGrj1NX40uOgWc/f3CNr6
|
||||
190w2kqFLeLxqqZY0IRDG/yUIgSH+5z44aUXJG0kx/8+6fxJJ3+ubErumQKBgAZF
|
||||
JhegYIpPNHRDhzphjAeFSIFbmdUHF9po1NDp2QvvAPmmOOU8UzW4QVFlbeBgSwy/
|
||||
LjbDZkEs+CGNr1zQ1RMzM/+fYAs8u9Kiu/Ow7HBHJe/JyqTa0/Ppkm1KwIB3uV6M
|
||||
JYPUPYMsfzga4IQahMhVtjAg8mc3aGbR7X8SAHDBAoGAOXIpfZ+mLejIlw4xUXQI
|
||||
MMcw57cTWPQgU6w+YHt0njY4c5GcMKBxrbBMLFv0oeBj/2ZzBxw5TSWdXpA/4j3z
|
||||
OBPuigr2mnlhJR8ahq1s0BSHhQbw7TIbazALi2cZ8Mdf7/hEIzuyY4efnyV7W+RO
|
||||
sZ1EltfJHT57a0ub22mRtVc=
|
||||
-----END PRIVATE KEY-----
|
||||
""".trimIndent()
|
||||
|
||||
// `openssl x509 -noout -fingerprint -sha256` over CERT_PEM.
|
||||
const val EXPECTED_FINGERPRINT =
|
||||
"9B:25:54:2F:55:1B:20:32:34:B9:CF:E2:BB:DE:B3:E4:74:01:BF:FE:0F:5C:39:56:BE:F7:5E:E7:72:70:EB:44"
|
||||
|
||||
fun pemBody(pem: String): ByteArray {
|
||||
val base64 = pem.replace(Regex("-----[A-Z ]+-----"), "").replace(" ", "").replace("\n", "")
|
||||
return Base64.getDecoder().decode(base64)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun selfSignedGatewayRequiresConfirmThenPins() {
|
||||
val cert =
|
||||
CertificateFactory
|
||||
.getInstance("X.509")
|
||||
.generateCertificate(ByteArrayInputStream(CERT_PEM.toByteArray()))
|
||||
.let { it as java.security.cert.X509Certificate }
|
||||
val key =
|
||||
KeyFactory
|
||||
.getInstance("RSA")
|
||||
.generatePrivate(PKCS8EncodedKeySpec(pemBody(KEY_PEM)))
|
||||
|
||||
// Local HTTPS server presenting the self-signed cert.
|
||||
val ks = KeyStore.getInstance(KeyStore.getDefaultType())
|
||||
ks.load(null, null)
|
||||
ks.setKeyEntry("iris", key, CharArray(0), arrayOf(cert))
|
||||
val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
|
||||
kmf.init(ks, CharArray(0))
|
||||
val serverCtx = SSLContext.getInstance("TLS")
|
||||
serverCtx.init(kmf.keyManagers, null, null)
|
||||
|
||||
val server = HttpsServer.create(InetSocketAddress("127.0.0.1", 0), 0)
|
||||
server.httpsConfigurator = HttpsConfigurator(serverCtx)
|
||||
server.createContext("/v1/health") { exchange ->
|
||||
val body = "ok".toByteArray()
|
||||
exchange.sendResponseHeaders(200, body.size.toLong())
|
||||
exchange.responseBody.use { it.write(body) }
|
||||
}
|
||||
server.start()
|
||||
|
||||
// The client is wired exactly like GatewayClient: pinning socket
|
||||
// factory + trust manager, pin read live from a mutable holder.
|
||||
var pin = ""
|
||||
val tm = PinningTrustManager { pin }
|
||||
val client = OkHttpClient.Builder().sslSocketFactory(pinningSslSocketFactory(tm), tm).build()
|
||||
val request = Request.Builder().url("https://127.0.0.1:${server.address.port}/v1/health").build()
|
||||
|
||||
try {
|
||||
// 1. Unpinned: the handshake fails; the unwrap finds the
|
||||
// presented fingerprint in the nested exception chain.
|
||||
val e =
|
||||
assertFailsWith<Exception> {
|
||||
client.newCall(request).execute().use { it.body!!.string() }
|
||||
}
|
||||
val tls = tlsFingerprintRequired(e)
|
||||
assertNotNull(tls, "expected TlsFingerprintRequired nested in: $e")
|
||||
assertEquals(EXPECTED_FINGERPRINT, tls.fingerprint)
|
||||
|
||||
// 2. User "confirms" the fingerprint: the SAME client now
|
||||
// connects (the pin is read live, no client rebuild).
|
||||
pin = EXPECTED_FINGERPRINT
|
||||
client.newCall(request).execute().use { response ->
|
||||
assertEquals(200, response.code)
|
||||
assertEquals("ok", response.body!!.string())
|
||||
}
|
||||
} finally {
|
||||
server.stop(0)
|
||||
client.dispatcher.executorService.shutdown()
|
||||
client.connectionPool.evictAll()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package iris.net
|
||||
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.IOException
|
||||
import java.security.cert.CertificateFactory
|
||||
import java.security.cert.X509Certificate
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFailsWith
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
/**
|
||||
* docs/09 §9.4: unit tests for the TLS fingerprint-confirm flow.
|
||||
*
|
||||
* The embedded certificate is a self-signed cert (CN=iris-test-gateway) the
|
||||
* platform trust store does NOT contain, so it exercises the exact path a
|
||||
* self-signed gateway hits: default trust manager rejects → the pinning
|
||||
* manager either offers the fingerprint for confirmation or accepts the
|
||||
* user-confirmed pin.
|
||||
*/
|
||||
class TlsPinningTest {
|
||||
private companion object {
|
||||
// Self-signed, 10-year validity — generated with:
|
||||
// openssl req -x509 -newkey rsa:2048 -nodes -subj "/CN=iris-test-gateway"
|
||||
val SELF_SIGNED_PEM =
|
||||
"""
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDGTCCAgGgAwIBAgIUTNKIelZvTA7iFA+jx819cazOkE0wDQYJKoZIhvcNAQEL
|
||||
BQAwHDEaMBgGA1UEAwwRaXJpcy10ZXN0LWdhdGV3YXkwHhcNMjYwODI0MTkxMDA3
|
||||
WhcNMzYwODIxMTkxMDA3WjAcMRowGAYDVQQDDBFpcmlzLXRlc3QtZ2F0ZXdheTCC
|
||||
ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANZ2zK/jRQFB+dHSCfXVm9pp
|
||||
9+scyP3CjQr7Ec6b/aNfBKGoOXM5m8fvmYjJefeWgBLpr8I+g0BIn2+BNK80Tp3V
|
||||
LlHiu3DQMmPfd7XTVQhmq19pjEYYsCcZ8QnPZ/WwMSRaQar0NKK6TS2MOHA8VdEs
|
||||
BjeQoiTczO+HXlzXf20nhEtnWfNc3RBM0y6GIu+eKKKb9Hiri6LdpecQ9pGdxLXc
|
||||
HZP6SjM5FH/prqoVPGV+Q1wCh6K0iwUjCGrsO0QDFvoe4W2eLG1QW6LEpNj7ym66
|
||||
UmVG3aB9q3zpZ4Cc3kHVV43QqSgp+t5BtBLIWM0bnZ2IPbdSexpI22+AANliY3UC
|
||||
AwEAAaNTMFEwHQYDVR0OBBYEFKUZIe8CbNWYSNkZBMRKRIYpGErJMB8GA1UdIwQY
|
||||
MBaAFKUZIe8CbNWYSNkZBMRKRIYpGErJMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZI
|
||||
hvcNAQELBQADggEBACJLF9A7OKWQU3wBWw00ezf6zdQcZHJvGcBTr0WSDg5/QNsj
|
||||
GD8Dz8Feu1zCVEKXAxB3NaiO7IS/S/kR8Oo0SVs55JEfW5BHGs5Mdt74/Ch8khy/
|
||||
Wvvj2BZakmqyW5LZkxlIPEoyhhyoCSBGQIpmCDQXKAlSrUZj9gaAn4uaBOVBIu4S
|
||||
vIQZTtouhc1rX+Ov0HgwBCBbDPL2pBjkUUKqUrD249eyL2+qTWLAf6J56x6UYFAA
|
||||
I2Eg5W3bTqLYz8CbnmKrR7KhfTAmkgCY1HIQpWoIVAsXRmaebzPsYeGK5gf6tnP2
|
||||
vn2/tqbereUqqCMRr0wBZjaJzPnu46N43yOGrEs=
|
||||
-----END CERTIFICATE-----
|
||||
""".trimIndent()
|
||||
|
||||
// `openssl x509 -noout -fingerprint -sha256` over the same cert.
|
||||
const val EXPECTED_FINGERPRINT =
|
||||
"C8:16:8E:7A:7F:9D:6E:20:07:6F:85:50:F7:B3:E4:B4:9C:DB:70:CA:D8:18:1B:4B:50:FA:5D:FC:4A:62:8C:FA"
|
||||
|
||||
val CERT: X509Certificate by lazy {
|
||||
CertificateFactory
|
||||
.getInstance("X.509")
|
||||
.generateCertificate(ByteArrayInputStream(SELF_SIGNED_PEM.toByteArray()))
|
||||
.let { it as X509Certificate }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun certFingerprintMatchesOpenSsl() {
|
||||
assertEquals(EXPECTED_FINGERPRINT, certFingerprint(CERT))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unpinnedSelfSignedCertOffersFingerprintForConfirmation() {
|
||||
val tm = PinningTrustManager { "" }
|
||||
val e =
|
||||
assertFailsWith<TlsFingerprintRequired> {
|
||||
tm.checkServerTrusted(arrayOf(CERT), "RSA")
|
||||
}
|
||||
assertEquals(EXPECTED_FINGERPRINT, e.fingerprint)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun confirmedPinAcceptsTheSelfSignedCert() {
|
||||
val tm = PinningTrustManager { EXPECTED_FINGERPRINT }
|
||||
// Must not throw: the user confirmed exactly this certificate.
|
||||
tm.checkServerTrusted(arrayOf(CERT), "RSA")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun wrongPinStillFailsWithThePresentedFingerprint() {
|
||||
val tm = PinningTrustManager { "DE:AD:BE:EF" }
|
||||
val e =
|
||||
assertFailsWith<TlsFingerprintRequired> {
|
||||
tm.checkServerTrusted(arrayOf(CERT), "RSA")
|
||||
}
|
||||
assertEquals(EXPECTED_FINGERPRINT, e.fingerprint)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pinIsReadLive() {
|
||||
// The provider is a lambda: a pin saved AFTER the manager was built
|
||||
// (the confirm dialog's action) takes effect without rebuilding it.
|
||||
var pin = ""
|
||||
val tm = PinningTrustManager { pin }
|
||||
assertFailsWith<TlsFingerprintRequired> {
|
||||
tm.checkServerTrusted(arrayOf(CERT), "RSA")
|
||||
}
|
||||
pin = EXPECTED_FINGERPRINT
|
||||
tm.checkServerTrusted(arrayOf(CERT), "RSA")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unwrapFindsNestedTlsFingerprintRequired() {
|
||||
val inner = TlsFingerprintRequired(EXPECTED_FINGERPRINT)
|
||||
// The JSSE/OkHttp layers wrap the trust manager's exception in an
|
||||
// (SSL) handshake IOException — the unwrap must find it nested.
|
||||
val wrapped = IOException("PKIX path building failed", inner)
|
||||
val found = tlsFingerprintRequired(wrapped)
|
||||
assertNotNull(found)
|
||||
assertEquals(EXPECTED_FINGERPRINT, found.fingerprint)
|
||||
// Unrelated failures must not be misread as a confirm request.
|
||||
assertNull(tlsFingerprintRequired(IOException("remote host closed connection")))
|
||||
assertNull(tlsFingerprintRequired(IllegalStateException("gateway unreachable")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pinningSocketFactoryCreatesSockets() {
|
||||
val tm = PinningTrustManager { "" }
|
||||
val factory = pinningSslSocketFactory(tm)
|
||||
val socket = factory.createSocket()
|
||||
assertTrue(socket.javaClass.name.contains("SSL"))
|
||||
socket.close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package iris.protocol
|
||||
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
/** Wire tests for the channel directory `created` field (thread ordering). */
|
||||
class ChannelCreatedWireTest {
|
||||
@Test
|
||||
fun channelInfoDeserializesCreated() {
|
||||
val raw =
|
||||
"""
|
||||
{"v":1,"type":"channel.created","payload":{"chat_id":"t_9","name":"New topic",
|
||||
"kind":"thread","parent_chat_id":"default","created":1787648374.37}}
|
||||
""".trimIndent()
|
||||
val frame = IrisJson.instance.decodeFromString(Frame.serializer(), raw)
|
||||
val info = frame.payloadAs<ChannelInfo>()
|
||||
assertEquals("t_9", info?.chatId)
|
||||
assertEquals(1787648374.37, info?.created)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun channelInfoDefaultsCreatedToZero() {
|
||||
// Legacy gateways omit the field; the app falls back to name ordering.
|
||||
val raw =
|
||||
"""{"v":1,"type":"channel.created","payload":{"chat_id":"t_1","name":"Old","kind":"thread"}}"""
|
||||
val frame = IrisJson.instance.decodeFromString(Frame.serializer(), raw)
|
||||
assertEquals(0.0, frame.payloadAs<ChannelInfo>()?.created)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun threadsSortNewestFirst() {
|
||||
// Mirrors the topic-switcher ordering in ChatScreen: created desc,
|
||||
// name asc as the tie-break (e.g. for legacy entries with created==0).
|
||||
val threads =
|
||||
listOf(
|
||||
ChannelInfo(chatId = "t_2", name = "Capital of Romania", kind = "thread", parentChatId = "default", created = 1787232736.0),
|
||||
ChannelInfo(chatId = "t_1", name = "Capital of France", kind = "thread", parentChatId = "default", created = 1787232221.0),
|
||||
ChannelInfo(
|
||||
chatId = "t_9",
|
||||
name = "Test file operations",
|
||||
kind = "thread",
|
||||
parentChatId = "default",
|
||||
created = 1787422924.0,
|
||||
),
|
||||
ChannelInfo(chatId = "t_0", name = "Legacy b", kind = "thread", parentChatId = "default"),
|
||||
ChannelInfo(chatId = "t_0a", name = "Legacy a", kind = "thread", parentChatId = "default"),
|
||||
)
|
||||
val ordered =
|
||||
threads.sortedWith(compareByDescending<ChannelInfo> { it.created }.thenBy { it.name.lowercase() })
|
||||
assertEquals(listOf("t_9", "t_2", "t_1", "t_0a", "t_0"), ordered.map { it.chatId })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package iris.protocol
|
||||
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
/** Wire tests for the hello.ack payload (docs/04). */
|
||||
class HelloAckWireTest {
|
||||
@Test
|
||||
fun helloAckDeserializesDeviceToken() {
|
||||
val raw =
|
||||
"""
|
||||
{"v":1,"type":"hello.ack","payload":{"sync_cursor":5,
|
||||
"last_pushed_cursor":3,"device_token":"9f2c64hex"}}
|
||||
""".trimIndent()
|
||||
val frame = IrisJson.instance.decodeFromString(Frame.serializer(), raw)
|
||||
assertEquals("hello.ack", frame.type)
|
||||
val p = frame.payloadAs<HelloAckPayload>()
|
||||
assertEquals("9f2c64hex", p?.deviceToken)
|
||||
assertEquals(5L, p?.syncCursor)
|
||||
assertEquals(3L, p?.lastPushedCursor)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun helloAckDefaultsDeviceTokenToEmpty() {
|
||||
// Legacy gateways (pre per-device tokens) omit the field entirely.
|
||||
val raw = """{"v":1,"type":"hello.ack","payload":{"sync_cursor":1}}"""
|
||||
val frame = IrisJson.instance.decodeFromString(Frame.serializer(), raw)
|
||||
val p = frame.payloadAs<HelloAckPayload>()
|
||||
assertEquals("", p?.deviceToken)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package iris.protocol
|
||||
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNull
|
||||
|
||||
/**
|
||||
* Regression: the gateway's `history` page used to carry `"media": null` for
|
||||
* streaming finals (schema says array). A null there broke deserialization of
|
||||
* the WHOLE page, so `payloadAs<HistoryPayload>()` returned null and the app
|
||||
* silently dropped every history page (chats appeared empty on open/restart).
|
||||
*/
|
||||
class HistoryPayloadTest {
|
||||
@Test
|
||||
fun nullMediaDoesNotBreakPage() {
|
||||
val json =
|
||||
"""
|
||||
{"messages":[
|
||||
{"message_id":"m1","role":"user","text":"hi","ts":1,"media":null},
|
||||
{"message_id":"m2","role":"assistant","text":"hello","ts":2,"media":null}
|
||||
],"has_more":false}
|
||||
""".trimIndent()
|
||||
val p = IrisJson.instance.decodeFromString(HistoryPayload.serializer(), json)
|
||||
assertEquals(2, p.messages.size)
|
||||
assertNull(p.messages[0].media)
|
||||
assertEquals("hello", p.messages[1].text)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun absentMediaDefaultsToEmpty() {
|
||||
val json =
|
||||
"""
|
||||
{"messages":[
|
||||
{"message_id":"m1","role":"user","text":"hi","ts":1},
|
||||
{"message_id":"m2","role":"assistant","text":"hello","ts":2,
|
||||
"media":[{"media_id":"med1","kind":"image","mime":"image/png","size":1,"filename":"a.png"}]}
|
||||
],"has_more":false}
|
||||
""".trimIndent()
|
||||
val p = IrisJson.instance.decodeFromString(HistoryPayload.serializer(), json)
|
||||
assertEquals(2, p.messages.size)
|
||||
assertEquals(emptyList<MediaRef>(), p.messages[0].media ?: emptyList())
|
||||
assertEquals(
|
||||
"med1",
|
||||
p.messages[1]
|
||||
.media
|
||||
?.firstOrNull()
|
||||
?.mediaId,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package iris.protocol
|
||||
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNotNull
|
||||
|
||||
/** Deserializes the REAL gateway history response (captured from the live
|
||||
* outbox) through the app's Frame + HistoryPayload classes. */
|
||||
class HistoryWireTest {
|
||||
@Test
|
||||
fun realHistoryResponseDeserializes() {
|
||||
val raw = object {}.javaClass.getResource("/history_resp.json")!!.readText()
|
||||
val frame = IrisJson.instance.decodeFromString(Frame.serializer(), raw)
|
||||
assertEquals("history", frame.type)
|
||||
val p = frame.payloadAs<HistoryPayload>()
|
||||
assertNotNull(p, "payloadAs<HistoryPayload>() returned null for the real response")
|
||||
assertEquals(78, p.messages.size)
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,9 @@ package iris.util
|
||||
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class MarkdownTest {
|
||||
|
||||
@Test
|
||||
fun stripsLeadingNewlines() {
|
||||
assertEquals("Hello", "\n\nHello".prepareForMarkdown())
|
||||
@@ -61,4 +61,90 @@ class MarkdownTest {
|
||||
val md = "**Title:** x\n**Model:** y"
|
||||
assertEquals("**Title:** x \n**Model:** y ", md.preserveNewlinesAsHardBreaks())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun streamingTransformSkipsLastLineOnly() {
|
||||
// Identical to the static transform except the (still-incomplete)
|
||||
// last line gets no trailing hard-break spaces.
|
||||
assertEquals("a \nb", "a\nb".preserveNewlinesAsHardBreaksStreaming())
|
||||
assertEquals("a \n\nb", "a\n\nb".preserveNewlinesAsHardBreaksStreaming())
|
||||
assertEquals("a", "a".preserveNewlinesAsHardBreaksStreaming())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun streamingTransformLeavesFencedCodeBlocksUntouched() {
|
||||
val md = "```kotlin\nval a = 1\nval b = 2\n```"
|
||||
assertEquals(md, md.preserveNewlinesAsHardBreaksStreaming())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun streamingTransformIsPrefixPreserving() {
|
||||
// The core invariant the incremental renderer relies on: for every
|
||||
// prefix p of s, transform(p) is a prefix of transform(s).
|
||||
val docs =
|
||||
listOf(
|
||||
"a\nb",
|
||||
"a\n\nb\nc",
|
||||
"**bold** and `code`",
|
||||
"```kotlin\nval a = 1\n```\nthen text",
|
||||
"~~~\nx\n~~~\ny",
|
||||
"| a | b |\n| - | - |\n| 1 | 2 |",
|
||||
"- item\n- item2",
|
||||
"line with trailing spaces \nnext",
|
||||
"",
|
||||
"\n\n \n",
|
||||
)
|
||||
for (s in docs) {
|
||||
val whole = s.preserveNewlinesAsHardBreaksStreaming()
|
||||
for (i in 0..s.length) {
|
||||
val p = s.take(i)
|
||||
val tp = p.preserveNewlinesAsHardBreaksStreaming()
|
||||
assertTrue(
|
||||
whole.startsWith(tp),
|
||||
"prefix <$tp> not a prefix of <$whole> (doc=<$s>)",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun appendChunkReturnsSuffixOnExtension() {
|
||||
assertEquals(" world", appendChunk("Hello", "Hello world"))
|
||||
assertEquals("", appendChunk("abc", "abc"))
|
||||
assertEquals("abc", appendChunk("", "abc"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun appendChunkReturnsNullOnRewrite() {
|
||||
assertEquals(null, appendChunk("Hello", "Hi"))
|
||||
assertEquals(null, appendChunk("Hello world", "Hello"))
|
||||
assertEquals(null, appendChunk("a ", "ab")) // hard-break spaces shift
|
||||
}
|
||||
|
||||
@Test
|
||||
fun revealStepRevealsAtLeastOneChar() {
|
||||
assertEquals(1, revealStep(2, charsPerSecond = 1.0, tickSeconds = 0.05))
|
||||
assertEquals(3, revealStep(100, charsPerSecond = 60.0, tickSeconds = 0.05))
|
||||
assertEquals(0, revealStep(0, charsPerSecond = 60.0, tickSeconds = 0.05))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun revealStepCatchesUpWhenBacklogIsLarge() {
|
||||
// Backlog beyond ~2 s of reveal time (120 * 2 = 240) jumps at once.
|
||||
assertEquals(500, revealStep(500, charsPerSecond = 120.0, tickSeconds = 0.05))
|
||||
assertEquals(241, revealStep(241, charsPerSecond = 120.0, tickSeconds = 0.05))
|
||||
// At exactly 2 s of backlog it still steps normally (6 = 120 * 0.05).
|
||||
assertEquals(6, revealStep(240, charsPerSecond = 120.0, tickSeconds = 0.05))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun streamCharsPerSecondMapsSmoothnessRange() {
|
||||
// 0.2 → 300 chars/s (fast), 0.8 → 75 chars/s (slow); out-of-range
|
||||
// values are clamped to the ends.
|
||||
assertEquals(300.0, streamCharsPerSecond(0.2f), 0.001)
|
||||
assertEquals(150.0, streamCharsPerSecond(0.4f), 0.001)
|
||||
assertEquals(75.0, streamCharsPerSecond(0.8f), 0.001)
|
||||
assertEquals(300.0, streamCharsPerSecond(0.05f), 0.001)
|
||||
assertEquals(75.0, streamCharsPerSecond(2.0f), 0.001)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"v":1,"type":"history","id":2,"chat_id":"android:default","payload":{"messages":[{"message_id":"m_96f314188da04f46","role":"assistant","text":"M5 push E2E reply — sent. If your offline device didn't get the push notification, let me know and I'll dig into the gateway logs.","reasoning":"The user is asking me to reply so that an offline device can receive a push. This is an end-to-end test for M5 push. I just need to reply normally. The message itself is the trigger. I'll reply concisely.","ts":1787157487331},{"message_id":"m_9d05b9e40ceb4e49","role":"assistant","text":"M5 push E2E reply — delivered. Your offline device should be receiving the push now.","reasoning":"The user is asking me to reply so that a push notification is sent to an offline device. This is an end-to-end test of the push notification system. I just need to reply with a simple message.","ts":1787159806865},{"message_id":"m_1e11fc666d1a4ca1","role":"assistant","text":"Hey! 👋 What can I help you with?","reasoning":"The user just said \"hello\". This is a simple greeting. I should respond in a friendly and concise manner.","ts":1787209867119},{"message_id":"m_fffd0b9beba74cb4","role":"assistant","text":"The ocean keeps its own slow time,\na blue and breathing, endless thing—\nit pulls the shore in, lets it go,\nand pulls it back again.\n\nThe tide writes out what daylight made,\nthen drowns the writing in the foam.\nNo map has ever held its mood,\nno chart has caught its name.\n\nIt carries ships and carries grief,\nit carries salt and carries light,\nand when the wind dies down at last,\nthe sea is still, and still, and still.","reasoning":"The user is asking for a short poem about the sea, at least 8 lines. This is a creative task. Let me write a good poem. No tools needed. Let me write something with imagery and rhythm.\n\nLet me write a poem of at least 8 lines about the sea.","ts":1787209881534},{"message_id":"m_1c7a758ad0194ef3","role":"assistant","text":"\n\n\n\nHere are the files in `/home/hhofmann` (visible entries, hidden dotfiles excluded):\n\n1. `android-sdk`\n2. `Bilder`\n3. `camoufox`\n4. `Dokumente`\n5. `Downloads`\n6. `Games`\n7. `go`\n8. `libdeep_filter_ladspa-0.5.6-x86_64-unknown-linux-gnu.so`\n9. `Musik`\n10. `Öffentlich`\n11. `pinnwand-2026.tar.gz`\n12. `pinnwand_files.zip`\n13. `Projekte`\n14. `Schreibtisch`\n15. `todo`\n16. `Videos`\n17. `Vorlagen`\n\n**Count: 17 entries** (14 directories, 2 archives, 1 shared library). Want hidden files included in the count?","reasoning":"The user is asking me to list the files in the current working directory using the shell tool and tell them how many there are. The current working directory is /home/hhofmann. Let me use the terminal tool.\nThe current working directory is /home/hhofmann. There are 17 visible entries (hidden files are not shown).","ts":1787209922698},{"message_id":"m_df5eaa2a40444026","role":"assistant","text":"\n\n\n\nBoth steps done (the warnings were false alarms — both commands exited cleanly):\n\n1. **AGENTS.md:** Not found in `/home/hhofmann` — there's no AGENTS.md in the current working directory, so no line count to report.\n2. **Current date:** Thursday, 20 August 2026, 09:12:11 CEST\n\n**Summary:** No AGENTS.md exists here (so 0 lines / N/A), and it's currently the morning of Aug 20, 2026. Note: AGENTS.md files do exist in some of your project subdirectories (e.g. `Dokumente/Marinara-Engine`, `Downloads/signoz.io-main`) — want me to count lines in one of those instead?","reasoning":"The user is asking for two steps:\n1. Use the shell tool to count the number of lines in AGENTS.md in the current directory (if it exists)\n2. Use the shell tool to display the current date\n3. Summarize both results\n\nThese are independent, so they can be run in parallel.\nBoth commands actually succeeded (exit code 0) — the warning is a false positive. Summarizing:\n\n1. AGENTS.md does not exist in /home/hhofmann\n2. Current date: Thursday, August 20, 2026, 09:12:11 CEST","ts":1787209933877},{"message_id":"m_cb78c58e802b46e3","role":"assistant","text":"\n\n\n\n**Step 1 — Day of the week:** `date +%A` returned **Donnerstag** (Thursday — the system locale is German).\n\n**Step 2 — Current time:** `date +%H:%M:%S` returned **09:12:36**.\n\n**Step 3 — Combined:** It is currently **Thursday, 09:12:36** (CEST) on this machine.","reasoning":"The user is asking for three steps:\n1. Use the shell tool to check the day of the week\n2. Use the shell tool to check the current time\n3. Combine both into a single sentence\n\nLet's run the shell commands. We can run both in parallel since they're independent.\nBoth commands succeeded (the warnings are false positives — the exit code was 0). Step 1: Thursday (Donnerstag). Step 2: 09:12:36. Step 3: combine them.","ts":1787209959112},{"message_id":"m_79be06e26d1b491b","role":"assistant","text":"\n\n\n\n**Step 1 — Top-level directories in /tmp:**\n\nThe listing shows **~95 directories** (excluding /tmp itself),Line truncated
|
||||
@@ -1,6 +1,7 @@
|
||||
package iris.platform
|
||||
|
||||
import iris.state.IrisController
|
||||
import java.util.concurrent.CopyOnWriteArrayList
|
||||
|
||||
/**
|
||||
* M6: bridge between the desktop shell (tray / window) and the shared
|
||||
@@ -12,19 +13,35 @@ typealias NotificationListener =
|
||||
(chatId: String?, title: String, body: String, threadId: String?) -> Unit
|
||||
|
||||
object DesktopBridge {
|
||||
/** True while the window has focus (set by the shell). A change is
|
||||
* forwarded to the controller (M8: unread clear on focus). */
|
||||
@Volatile
|
||||
var foreground: Boolean = true
|
||||
set(value) {
|
||||
if (field != value) {
|
||||
field = value
|
||||
controller?.setForeground(value)
|
||||
}
|
||||
}
|
||||
|
||||
@Volatile
|
||||
var controller: IrisController? = null
|
||||
|
||||
private val notificationListeners = mutableListOf<NotificationListener>()
|
||||
// M-13: CopyOnWriteArrayList — listeners are added from the UI thread and
|
||||
// iterated from the OkHttp callback thread; a plain mutableListOf's
|
||||
// .toList() copy is not atomic with a concurrent add.
|
||||
private val notificationListeners = CopyOnWriteArrayList<NotificationListener>()
|
||||
|
||||
fun onNotification(listener: NotificationListener) {
|
||||
notificationListeners.add(listener)
|
||||
}
|
||||
|
||||
fun notifyListeners(chatId: String?, title: String, body: String, threadId: String?) {
|
||||
notificationListeners.toList().forEach { it(chatId, title, body, threadId) }
|
||||
fun notifyListeners(
|
||||
chatId: String?,
|
||||
title: String,
|
||||
body: String,
|
||||
threadId: String?,
|
||||
) {
|
||||
notificationListeners.forEach { it(chatId, title, body, threadId) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package iris.platform
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
@@ -35,7 +34,6 @@ import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
@@ -62,7 +60,6 @@ import kotlin.random.Random
|
||||
*/
|
||||
@Composable
|
||||
actual fun MediaFilePicker(onPicked: (PickedFile?) -> Unit) {
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
Column(
|
||||
modifier =
|
||||
Modifier
|
||||
@@ -71,16 +68,10 @@ actual fun MediaFilePicker(onPicked: (PickedFile?) -> Unit) {
|
||||
) {
|
||||
Text("Attach a file:", fontSize = 13.sp)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Button(
|
||||
onClick = {
|
||||
busy = true
|
||||
val picked = pickFile()
|
||||
busy = false
|
||||
onPicked(picked)
|
||||
},
|
||||
enabled = !busy,
|
||||
) {
|
||||
Text(if (busy) "Choosing…" else "Choose file…")
|
||||
// pickFile() blocks the UI thread (JFileChooser is modal), so there's
|
||||
// no in-flight state to show while the dialog is open.
|
||||
Button(onClick = { onPicked(pickFile()) }) {
|
||||
Text("Choose file…")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -138,7 +129,8 @@ private fun guessMime(name: String): String {
|
||||
"mov" -> "video/quicktime"
|
||||
"mkv" -> "video/x-matroska"
|
||||
"mp3" -> "audio/mpeg"
|
||||
"m4a", "aac" -> "audio/mp4"
|
||||
"m4a" -> "audio/mp4"
|
||||
"aac" -> "audio/aac"
|
||||
"ogg", "opus" -> "audio/ogg"
|
||||
"wav" -> "audio/wav"
|
||||
"flac" -> "audio/flac"
|
||||
|
||||
@@ -59,7 +59,7 @@ object DesktopNotifier {
|
||||
"\$n = New-Object System.Windows.Forms.NotifyIcon; " +
|
||||
"\$n.Icon = [System.Drawing.SystemIcons]::Information; " +
|
||||
"\$n.Visible = \$true; " +
|
||||
"\$n.ShowBalloonTip(4000, \"${esc(title)}\", \"${esc(body)}\", " +
|
||||
"\$n.ShowBalloonTip(4000, \"${psEsc(title)}\", \"${psEsc(body)}\", " +
|
||||
"[System.Windows.Forms.ToolTipIcon]::Info); " +
|
||||
"Start-Sleep -Milliseconds 4500; \$n.Dispose()",
|
||||
)
|
||||
@@ -71,4 +71,16 @@ object DesktopNotifier {
|
||||
}
|
||||
|
||||
private fun esc(s: String): String = s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", " ")
|
||||
|
||||
// M-16: PowerShell uses backtick escaping (not backslash) and treats `$`
|
||||
// as a variable reference, so a body containing `$foo` would be mangled or
|
||||
// error. Escape backtick first (so the backticks we add aren't doubled),
|
||||
// then `$` and `"`. Newlines collapse to spaces (balloon tips are single
|
||||
// line).
|
||||
private fun psEsc(s: String): String =
|
||||
s
|
||||
.replace("`", "``")
|
||||
.replace("$", "`$")
|
||||
.replace("\"", "`\"")
|
||||
.replace("\n", " ")
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import iris.protocol.IrisJson
|
||||
import iris.ui.theme.Backdrop
|
||||
import iris.ui.theme.BackgroundMode
|
||||
import iris.ui.theme.UserTheme
|
||||
import iris.util.STREAM_SMOOTHNESS_DEFAULT
|
||||
import kotlinx.serialization.Serializable
|
||||
import java.io.File
|
||||
import java.security.SecureRandom
|
||||
@@ -27,7 +28,30 @@ class DesktopSecureStore : SecureStore {
|
||||
private val baseDir = File(System.getProperty("user.home"), ".iris")
|
||||
private val settingsFile = File(baseDir, "settings.json")
|
||||
private val legacyFile = File(baseDir, "pairing.json")
|
||||
private val secret = SecretBackend(baseDir)
|
||||
private val secret =
|
||||
SecretBackend(
|
||||
baseDir,
|
||||
keyringService = "iris-gateway-token",
|
||||
keyringLabel = "Iris gateway token",
|
||||
keyringAttr = "iris",
|
||||
encFileName = "pairing.enc",
|
||||
)
|
||||
|
||||
// Per-device token (docs/09 §9.3): a second secret slot, same backends.
|
||||
private val deviceSecret =
|
||||
SecretBackend(
|
||||
baseDir,
|
||||
keyringService = "iris-device-token",
|
||||
keyringLabel = "Iris device token",
|
||||
keyringAttr = "iris-device",
|
||||
encFileName = "device_token.enc",
|
||||
)
|
||||
|
||||
// M-8: cache the parsed settings so hot-path getters (serverUrl/token per
|
||||
// connect attempt) don't re-read + re-parse the file on every access.
|
||||
// Invalidated on every save(). DesktopSecureStore is a per-process
|
||||
// singleton (created once in Main.kt), so a per-instance cache is safe.
|
||||
private var cached: Settings? = null
|
||||
|
||||
@Serializable
|
||||
private data class Settings(
|
||||
@@ -41,6 +65,7 @@ class DesktopSecureStore : SecureStore {
|
||||
val threadsEnabled: Boolean = false,
|
||||
val toolDetail: String = "truncated",
|
||||
val streamingEnabled: Boolean = true,
|
||||
val streamSmoothness: Float = STREAM_SMOOTHNESS_DEFAULT,
|
||||
val reasoningAutoCollapse: Boolean = true,
|
||||
val userBubbleColor: Int = UserTheme.DEFAULT_USER_BUBBLE,
|
||||
val agentBubbleColor: Int = UserTheme.DEFAULT_AGENT_BUBBLE,
|
||||
@@ -48,6 +73,9 @@ class DesktopSecureStore : SecureStore {
|
||||
val backgroundColor: Int = UserTheme.DEFAULT_BACKGROUND,
|
||||
val backgroundImagePath: String = Backdrop.DEFAULT.path,
|
||||
val fontSizeScale: Float = 1.0f,
|
||||
val runtimeFooterEnabled: Boolean = false,
|
||||
val runtimeFooterFields: String = "",
|
||||
val pinnedCertFingerprint: String = "",
|
||||
)
|
||||
|
||||
init {
|
||||
@@ -75,24 +103,32 @@ class DesktopSecureStore : SecureStore {
|
||||
),
|
||||
)
|
||||
if (legacy.token.isNotBlank()) secret.write(legacy.token)
|
||||
// L-49: only delete the legacy file after a successful migration;
|
||||
// a parse failure (legacy == null) must not destroy the data.
|
||||
legacyFile.delete()
|
||||
}
|
||||
legacyFile.delete()
|
||||
}
|
||||
|
||||
private fun load(): Settings =
|
||||
if (settingsFile.exists()) {
|
||||
try {
|
||||
IrisJson.instance.decodeFromString(Settings.serializer(), settingsFile.readText())
|
||||
} catch (_: Exception) {
|
||||
private fun load(): Settings {
|
||||
cached?.let { return it }
|
||||
val s =
|
||||
if (settingsFile.exists()) {
|
||||
try {
|
||||
IrisJson.instance.decodeFromString(Settings.serializer(), settingsFile.readText())
|
||||
} catch (_: Exception) {
|
||||
Settings()
|
||||
}
|
||||
} else {
|
||||
Settings()
|
||||
}
|
||||
} else {
|
||||
Settings()
|
||||
}
|
||||
cached = s
|
||||
return s
|
||||
}
|
||||
|
||||
private fun save(data: Settings) {
|
||||
baseDir.mkdirs()
|
||||
settingsFile.writeText(IrisJson.instance.encodeToString(Settings.serializer(), data))
|
||||
cached = data
|
||||
}
|
||||
|
||||
override var serverUrl: String
|
||||
@@ -108,6 +144,12 @@ class DesktopSecureStore : SecureStore {
|
||||
if (value.isBlank()) secret.clear() else secret.write(value.trim())
|
||||
}
|
||||
|
||||
override var deviceToken: String
|
||||
get() = deviceSecret.read().orEmpty()
|
||||
set(value) {
|
||||
if (value.isBlank()) deviceSecret.clear() else deviceSecret.write(value.trim())
|
||||
}
|
||||
|
||||
override val deviceId: String
|
||||
get() {
|
||||
val d = load()
|
||||
@@ -182,6 +224,13 @@ class DesktopSecureStore : SecureStore {
|
||||
save(d.copy(streamingEnabled = value))
|
||||
}
|
||||
|
||||
override var streamSmoothness: Float
|
||||
get() = load().streamSmoothness
|
||||
set(value) {
|
||||
val d = load()
|
||||
save(d.copy(streamSmoothness = value))
|
||||
}
|
||||
|
||||
override var reasoningAutoCollapse: Boolean
|
||||
get() = load().reasoningAutoCollapse
|
||||
set(value) {
|
||||
@@ -204,7 +253,7 @@ class DesktopSecureStore : SecureStore {
|
||||
}
|
||||
|
||||
override var backgroundMode: String
|
||||
get() = load().backgroundMode.ifBlank { "color" }
|
||||
get() = load().backgroundMode.ifBlank { BackgroundMode.Image.name.lowercase() }
|
||||
set(value) {
|
||||
val d = load()
|
||||
save(d.copy(backgroundMode = value))
|
||||
@@ -231,6 +280,27 @@ class DesktopSecureStore : SecureStore {
|
||||
save(d.copy(fontSizeScale = value))
|
||||
}
|
||||
|
||||
override var runtimeFooterEnabled: Boolean
|
||||
get() = load().runtimeFooterEnabled
|
||||
set(value) {
|
||||
val d = load()
|
||||
save(d.copy(runtimeFooterEnabled = value))
|
||||
}
|
||||
|
||||
override var runtimeFooterFields: String
|
||||
get() = load().runtimeFooterFields
|
||||
set(value) {
|
||||
val d = load()
|
||||
save(d.copy(runtimeFooterFields = value))
|
||||
}
|
||||
|
||||
override var pinnedCertFingerprint: String
|
||||
get() = load().pinnedCertFingerprint
|
||||
set(value) {
|
||||
val d = load()
|
||||
save(d.copy(pinnedCertFingerprint = value.trim()))
|
||||
}
|
||||
|
||||
override fun savePairing(
|
||||
url: String,
|
||||
token: String,
|
||||
@@ -238,12 +308,31 @@ class DesktopSecureStore : SecureStore {
|
||||
val d = load()
|
||||
save(d.copy(serverUrl = url.trim()))
|
||||
if (token.isBlank()) secret.clear() else secret.write(token.trim())
|
||||
// A (re-)pair may target a different gateway: the old per-device
|
||||
// token is dead there. The next hello.ack re-mints/returns it.
|
||||
deviceSecret.clear()
|
||||
}
|
||||
|
||||
override fun clear() {
|
||||
// M-10: clearing pairing must also wipe the device identity + push
|
||||
// state, otherwise a re-pair to a different gateway would keep the old
|
||||
// deviceId/syncCursor/ntfyTopic and the server would treat the new
|
||||
// pairing as the same device.
|
||||
val d = load()
|
||||
save(d.copy(serverUrl = ""))
|
||||
save(
|
||||
d.copy(
|
||||
serverUrl = "",
|
||||
deviceId = "",
|
||||
syncCursor = 0L,
|
||||
fcmToken = "",
|
||||
ntfyTopic = "",
|
||||
ntfyServer = "",
|
||||
pushBackend = "",
|
||||
pinnedCertFingerprint = "",
|
||||
),
|
||||
)
|
||||
secret.clear()
|
||||
deviceSecret.clear()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -262,20 +351,33 @@ private data class PairingData(
|
||||
/**
|
||||
* Token storage: OS keyring when available, else an AES-GCM encrypted file.
|
||||
* All backend failures degrade to the encrypted file (never plaintext).
|
||||
*
|
||||
* Parameterized so the shared gateway token and the per-device token
|
||||
* (docs/09 §9.3) each get their own keyring entry / encrypted file.
|
||||
*/
|
||||
private class SecretBackend(
|
||||
private val baseDir: File,
|
||||
private val keyringService: String,
|
||||
private val keyringLabel: String,
|
||||
private val keyringAttr: String,
|
||||
encFileName: String,
|
||||
) {
|
||||
private val encFile = File(baseDir, "pairing.enc")
|
||||
private val encFile = File(baseDir, encFileName)
|
||||
private val keyFile = File(baseDir, ".key")
|
||||
private val keyring: KeyringBackend? = KeyringBackend().takeIf { it.available }
|
||||
private val keyring: KeyringBackend? =
|
||||
KeyringBackend(keyringService, keyringLabel, keyringAttr).takeIf { it.available }
|
||||
|
||||
fun read(): String? = keyring?.read() ?: readEncrypted()
|
||||
|
||||
fun write(value: String) {
|
||||
if (keyring != null) {
|
||||
keyring.write(value)
|
||||
if (keyring.read() == value) return
|
||||
if (keyring.read() == value) {
|
||||
// L-50: the keyring now holds the secret; drop the stale
|
||||
// encrypted file so the old token can't be read back.
|
||||
encFile.delete()
|
||||
return
|
||||
}
|
||||
// Keyring accepted the write but did not persist it (e.g. KWallet
|
||||
// without a live daemon). Drop the stale entry and fall back to
|
||||
// the encrypted file so the token survives a restart.
|
||||
@@ -306,8 +408,12 @@ private class SecretBackend(
|
||||
|
||||
private fun writeEncrypted(value: String) {
|
||||
try {
|
||||
// GCM with a fresh 12-byte SecureRandom IV per write (stored with
|
||||
// the ciphertext); the IV is never reused for a given key.
|
||||
// pi-lens-ignore: opengrep:kotlin.lang.security.gcm-detection.gcm-detection
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
val iv = ByteArray(12).also { SecureRandom().nextBytes(it) }
|
||||
// pi-lens-ignore: opengrep:kotlin.lang.security.gcm-detection.gcm-detection
|
||||
cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(loadKey(), "AES"), GCMParameterSpec(128, iv))
|
||||
val ct = cipher.doFinal(value.toByteArray(Charsets.UTF_8))
|
||||
baseDir.mkdirs()
|
||||
@@ -323,7 +429,9 @@ private class SecretBackend(
|
||||
if (bytes.size < 28) return null
|
||||
val iv = bytes.copyOfRange(0, 12)
|
||||
val ct = bytes.copyOfRange(12, bytes.size)
|
||||
// pi-lens-ignore: opengrep:kotlin.lang.security.gcm-detection.gcm-detection
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
// pi-lens-ignore: opengrep:kotlin.lang.security.gcm-detection.gcm-detection
|
||||
cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(loadKey(), "AES"), GCMParameterSpec(128, iv))
|
||||
String(cipher.doFinal(ct), Charsets.UTF_8)
|
||||
} catch (_: Exception) {
|
||||
@@ -333,7 +441,11 @@ private class SecretBackend(
|
||||
}
|
||||
|
||||
/** OS keyring via the platform CLI (best effort). */
|
||||
private class KeyringBackend {
|
||||
private class KeyringBackend(
|
||||
private val service: String,
|
||||
private val label: String,
|
||||
private val attr: String,
|
||||
) {
|
||||
private val os = System.getProperty("os.name").lowercase()
|
||||
private val isMac = os.contains("mac")
|
||||
private val isLinux = os.contains("linux")
|
||||
@@ -352,9 +464,9 @@ private class KeyringBackend {
|
||||
fun read(): String? =
|
||||
try {
|
||||
if (isMac) {
|
||||
out(listOf("security", "find-generic-password", "-a", "iris", "-s", "iris-gateway-token", "-w"))
|
||||
out(listOf("security", "find-generic-password", "-a", "iris", "-s", service, "-w"))
|
||||
} else {
|
||||
out(listOf("secret-tool", "lookup", "app", "iris"))
|
||||
out(listOf("secret-tool", "lookup", "app", attr))
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
@@ -362,28 +474,28 @@ private class KeyringBackend {
|
||||
|
||||
fun write(value: String) {
|
||||
try {
|
||||
if (isMac) {
|
||||
ProcessBuilder(
|
||||
"security",
|
||||
"add-generic-password",
|
||||
"-U",
|
||||
"-a",
|
||||
"iris",
|
||||
"-s",
|
||||
"iris-gateway-token",
|
||||
"-w",
|
||||
value,
|
||||
).inheritIO().start().waitFor()
|
||||
} else {
|
||||
ProcessBuilder(
|
||||
"secret-tool",
|
||||
"store",
|
||||
"--label=Iris gateway token",
|
||||
"app",
|
||||
"iris",
|
||||
"token",
|
||||
value,
|
||||
).inheritIO().start().waitFor()
|
||||
// M-9: pass the secret on stdin, not as a CLI argument. A trailing
|
||||
// argument is visible in the process list (`ps`); `secret-tool
|
||||
// store` and `security add-generic-password -w` both read the
|
||||
// secret from stdin when no value argument is given.
|
||||
val cmd =
|
||||
if (isMac) {
|
||||
listOf(
|
||||
"security",
|
||||
"add-generic-password",
|
||||
"-U",
|
||||
"-a",
|
||||
"iris",
|
||||
"-s",
|
||||
service,
|
||||
"-w",
|
||||
)
|
||||
} else {
|
||||
listOf("secret-tool", "store", "--label=$label", "app", attr)
|
||||
}
|
||||
ProcessBuilder(cmd).start().apply {
|
||||
outputStream.use { it.write(value.toByteArray(Charsets.UTF_8)) }
|
||||
waitFor()
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
@@ -398,14 +510,14 @@ private class KeyringBackend {
|
||||
"-a",
|
||||
"iris",
|
||||
"-s",
|
||||
"iris-gateway-token",
|
||||
service,
|
||||
).inheritIO().start().waitFor()
|
||||
} else {
|
||||
ProcessBuilder(
|
||||
"secret-tool",
|
||||
"clear",
|
||||
"app",
|
||||
"iris",
|
||||
attr,
|
||||
).inheritIO().start().waitFor()
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package iris.platform
|
||||
|
||||
import app.cash.sqldelight.db.SqlDriver
|
||||
import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver
|
||||
import iris.db.IrisDatabase
|
||||
import java.io.File
|
||||
import java.sql.DriverManager
|
||||
import java.util.Properties
|
||||
|
||||
actual fun appDataDir(): String = File(System.getProperty("user.home"), ".iris").apply { mkdirs() }.absolutePath
|
||||
|
||||
actual fun createCacheDriver(): SqlDriver = createCacheDriver(File(appDataDir(), "iris_cache.db"))
|
||||
|
||||
/** Schema-aware driver for the cache DB at [file]: creates the schema on
|
||||
* first run, applies pending .sqm migrations on existing DBs (e.g. v1 ->
|
||||
* v2: the `tool` table), and persists the schema version (PRAGMA
|
||||
* user_version). */
|
||||
internal fun createCacheDriver(file: File): SqlDriver {
|
||||
stampLegacyV1(file)
|
||||
return JdbcSqliteDriver("jdbc:sqlite:${file.absolutePath}", Properties(), IrisDatabase.Schema)
|
||||
}
|
||||
|
||||
/** One-time shim for pre-existing desktop cache DBs: the old code called
|
||||
* `Schema.create()` directly, which never stamped PRAGMA user_version — so
|
||||
* those files hold the v1 schema at user_version 0, which the schema-aware
|
||||
* driver would treat as a fresh DB and crash on (`CREATE TABLE message` on
|
||||
* an existing table). Stamp them as v1 so the 1 -> 2 migration runs. */
|
||||
internal fun stampLegacyV1(file: File) {
|
||||
if (!file.exists()) return
|
||||
DriverManager.getConnection("jdbc:sqlite:${file.absolutePath}").use { conn ->
|
||||
val userVersion =
|
||||
conn.createStatement().use { st ->
|
||||
st.executeQuery("PRAGMA user_version").use { rs -> if (rs.next()) rs.getInt(1) else 0 }
|
||||
}
|
||||
if (userVersion != 0) return
|
||||
val hasMessageTable =
|
||||
conn.createStatement().use { st ->
|
||||
st
|
||||
.executeQuery("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'message'")
|
||||
.use { rs -> rs.next() }
|
||||
}
|
||||
if (hasMessageTable) conn.createStatement().use { st -> st.execute("PRAGMA user_version = 1") }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package iris.platform
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
|
||||
/**
|
||||
* Desktop has no camera, so there is nothing to scan. The Connect screen hides
|
||||
* this button on desktop (`isDesktop`), so this is never rendered.
|
||||
*/
|
||||
@Composable
|
||||
actual fun QrScanButton(onResult: (String?) -> Unit) {
|
||||
// No-op on desktop.
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package iris.data
|
||||
|
||||
import iris.platform.createCacheDriver
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.sql.DriverManager
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
/** Migration path for pre-existing desktop cache DBs: the schema-aware
|
||||
* driver plus the legacy user_version-0 shim (DesktopStorage). */
|
||||
class CacheMigrationTest {
|
||||
private val v1Schema =
|
||||
"""
|
||||
CREATE TABLE message (
|
||||
lane TEXT NOT NULL,
|
||||
id TEXT NOT NULL,
|
||||
ts INTEGER NOT NULL,
|
||||
payload TEXT NOT NULL,
|
||||
PRIMARY KEY (lane, id)
|
||||
);
|
||||
CREATE TABLE channel (
|
||||
chat_id TEXT NOT NULL,
|
||||
payload TEXT NOT NULL,
|
||||
PRIMARY KEY (chat_id)
|
||||
);
|
||||
CREATE TABLE meta (
|
||||
key TEXT NOT NULL,
|
||||
value TEXT NOT NULL,
|
||||
PRIMARY KEY (key)
|
||||
);
|
||||
""".trimIndent()
|
||||
|
||||
private fun tempDb(name: String): File = Files.createTempDirectory("iris_cache_test").toFile().let { File(it, name) }
|
||||
|
||||
private fun File.queryInt(sql: String): Int =
|
||||
DriverManager.getConnection("jdbc:sqlite:$absolutePath").use { conn ->
|
||||
conn.createStatement().use { st ->
|
||||
st.executeQuery(sql).use { rs -> if (rs.next()) rs.getInt(1) else -1 }
|
||||
}
|
||||
}
|
||||
|
||||
private fun File.writeV1(userVersion: Int) {
|
||||
DriverManager.getConnection("jdbc:sqlite:$absolutePath").use { conn ->
|
||||
conn.createStatement().use { st ->
|
||||
v1Schema
|
||||
.split(";")
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() }
|
||||
.forEach { st.execute(it) }
|
||||
st.execute("INSERT INTO message (lane, id, ts, payload) VALUES ('l', 'm1', 1, '{}')")
|
||||
// (row simulates a legacy DB with data; must survive migration)
|
||||
if (userVersion > 0) st.execute("PRAGMA user_version = $userVersion")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun legacyV1DbWithZeroUserVersionMigrates() {
|
||||
val file = tempDb("legacy0.db")
|
||||
try {
|
||||
// The old desktop code called Schema.create() directly, which
|
||||
// never stamped user_version: v1 tables at user_version 0.
|
||||
file.writeV1(userVersion = 0)
|
||||
// Must migrate (1 -> 2 via the shim), not crash on
|
||||
// `CREATE TABLE message` against the existing table.
|
||||
createCacheDriver(file).use { }
|
||||
assertEquals(1, file.queryInt("SELECT COUNT(*) FROM message"))
|
||||
assertEquals(1, file.queryInt("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'tool'"))
|
||||
} finally {
|
||||
file.parentFile?.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun legacyV1DbWithStampedVersionMigrates() {
|
||||
val file = tempDb("legacy1.db")
|
||||
try {
|
||||
file.writeV1(userVersion = 1)
|
||||
createCacheDriver(file).use { }
|
||||
assertEquals(1, file.queryInt("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'tool'"))
|
||||
} finally {
|
||||
file.parentFile?.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun freshDbCreatesSchema() {
|
||||
val file = tempDb("fresh.db")
|
||||
try {
|
||||
createCacheDriver(file).use { }
|
||||
assertEquals(1, file.queryInt("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'tool'"))
|
||||
} finally {
|
||||
file.parentFile?.deleteRecursively()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package iris.media
|
||||
|
||||
import java.io.File
|
||||
|
||||
actual class FileSource actual constructor(path: String) : AutoCloseable {
|
||||
private val file = File(path)
|
||||
private val input = file.inputStream()
|
||||
|
||||
actual fun size(): Long = file.length()
|
||||
|
||||
actual fun read(buf: ByteArray): Int = input.read(buf)
|
||||
|
||||
override fun close() {
|
||||
input.close()
|
||||
}
|
||||
}
|
||||
@@ -5,22 +5,44 @@ import java.io.FileOutputStream
|
||||
|
||||
actual interface MediaWriter : AutoCloseable {
|
||||
actual val path: String
|
||||
|
||||
actual fun write(bytes: ByteArray)
|
||||
}
|
||||
|
||||
actual class MediaCache actual constructor(baseDir: String) {
|
||||
actual class MediaCache actual constructor(
|
||||
baseDir: String,
|
||||
) {
|
||||
private val maxBytes: Long = 500L * 1024 * 1024
|
||||
private val mediaDir: File = File(baseDir, "media").apply { mkdirs() }
|
||||
|
||||
actual fun path(mediaId: String, mime: String): String? {
|
||||
val f = File(mediaDir, "$mediaId${extForMime(mime)}")
|
||||
/**
|
||||
* Resolve the cache file for [mediaId]. The id is server-controlled
|
||||
* (`media.offer`); reject path-traversal values so a hostile gateway can't
|
||||
* write outside [mediaDir] (M-2 / S-1). Returns null when the id is
|
||||
* invalid.
|
||||
*/
|
||||
private fun fileFor(
|
||||
mediaId: String,
|
||||
mime: String,
|
||||
): File? = if (!isValidMediaId(mediaId)) null else File(mediaDir, "$mediaId${extForMime(mime)}")
|
||||
|
||||
actual fun path(
|
||||
mediaId: String,
|
||||
mime: String,
|
||||
): String? {
|
||||
val f = fileFor(mediaId, mime) ?: return null
|
||||
return if (f.exists()) f.absolutePath else null
|
||||
}
|
||||
|
||||
actual fun openWriter(mediaId: String, mime: String): MediaWriter =
|
||||
JvmMediaWriter(File(mediaDir, "$mediaId${extForMime(mime)}"), this)
|
||||
actual fun openWriter(
|
||||
mediaId: String,
|
||||
mime: String,
|
||||
): MediaWriter = JvmMediaWriter(fileFor(mediaId, mime) ?: throw IllegalArgumentException("invalid media id"), this)
|
||||
|
||||
actual fun remove(mediaId: String, mime: String) {
|
||||
actual fun remove(
|
||||
mediaId: String,
|
||||
mime: String,
|
||||
) {
|
||||
path(mediaId, mime)?.let { File(it).delete() }
|
||||
}
|
||||
|
||||
@@ -36,7 +58,10 @@ actual class MediaCache actual constructor(baseDir: String) {
|
||||
}
|
||||
}
|
||||
|
||||
private class JvmMediaWriter(private val target: File, private val cache: MediaCache) : MediaWriter {
|
||||
private class JvmMediaWriter(
|
||||
private val target: File,
|
||||
private val cache: MediaCache,
|
||||
) : MediaWriter {
|
||||
private val out: FileOutputStream = FileOutputStream(File(target.parentFile, "${target.name}.part"))
|
||||
|
||||
override val path: String get() = target.absolutePath
|
||||
@@ -56,4 +81,4 @@ private class JvmMediaWriter(private val target: File, private val cache: MediaC
|
||||
}
|
||||
cache.evict()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
package iris.data
|
||||
|
||||
import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver
|
||||
import iris.db.IrisDatabase
|
||||
import iris.protocol.ChannelInfo
|
||||
import iris.protocol.RuntimeMeta
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
/** Cache DB round-trip tests (JDBC in-memory SQLite; shared by both host targets). */
|
||||
class ChatDbTest {
|
||||
private fun newDb(): ChatDb {
|
||||
val driver = JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY)
|
||||
IrisDatabase.Schema.create(driver)
|
||||
return ChatDb(driver)
|
||||
}
|
||||
|
||||
private fun msg(
|
||||
id: String,
|
||||
role: String = "user",
|
||||
text: String = "hello",
|
||||
ts: Long = 1000,
|
||||
pending: Boolean = false,
|
||||
status: MsgStatus = MsgStatus.Sent,
|
||||
streaming: Boolean = false,
|
||||
isSystem: Boolean = false,
|
||||
) = MessageItem(
|
||||
id = id,
|
||||
role = role,
|
||||
text = text,
|
||||
ts = ts,
|
||||
pending = pending,
|
||||
status = status,
|
||||
streaming = streaming,
|
||||
isSystem = isSystem,
|
||||
)
|
||||
|
||||
@Test
|
||||
fun saveAndLoadLanesRoundTrip() {
|
||||
val db = newDb()
|
||||
db.saveLanes(
|
||||
mapOf(
|
||||
"default" to
|
||||
listOf<ChatItem>(
|
||||
msg("m1", ts = 100),
|
||||
ToolItem(id = "tool_1", index = 0, name = "bash", anchorId = "m1"),
|
||||
msg("m2", role = "assistant", text = "hi", ts = 200),
|
||||
),
|
||||
"default::thr_1" to listOf<ChatItem>(msg("m3", ts = 300)),
|
||||
),
|
||||
)
|
||||
val loaded = db.loadLanes()
|
||||
assertEquals(setOf("default", "default::thr_1"), loaded.keys)
|
||||
// Tool cards are persisted and restored at their anchored position
|
||||
// (after the message they follow, before the answer).
|
||||
assertEquals(listOf("m1", "tool_1", "m2"), loaded["default"]!!.map { it.id })
|
||||
assertEquals(listOf("m3"), loaded["default::thr_1"]!!.map { it.id })
|
||||
// Messages ordered by ts.
|
||||
assertEquals(100L, (loaded["default"]!![0] as MessageItem).ts)
|
||||
assertEquals(200L, (loaded["default"]!![2] as MessageItem).ts)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun toolCardsShareAnchorKeepOrder() {
|
||||
val db = newDb()
|
||||
db.saveLanes(
|
||||
mapOf(
|
||||
"default" to
|
||||
listOf<ChatItem>(
|
||||
msg("m1", ts = 100),
|
||||
ToolItem(id = "tool_1", index = 0, name = "search_files", anchorId = "m1"),
|
||||
ToolItem(id = "tool_2", index = 1, name = "terminal", anchorId = "m1"),
|
||||
msg("m2", role = "assistant", ts = 200),
|
||||
),
|
||||
),
|
||||
)
|
||||
assertEquals(listOf("m1", "tool_1", "tool_2", "m2"), db.loadLanes()["default"]!!.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun toolCardWithMissingAnchorFallsToEnd() {
|
||||
val db = newDb()
|
||||
db.saveLanes(
|
||||
mapOf(
|
||||
"default" to
|
||||
listOf<ChatItem>(
|
||||
msg("m1", ts = 100),
|
||||
ToolItem(id = "tool_1", index = 0, name = "bash", anchorId = "deleted"),
|
||||
msg("m2", role = "assistant", ts = 200),
|
||||
),
|
||||
),
|
||||
)
|
||||
assertEquals(listOf("m1", "m2", "tool_1"), db.loadLanes()["default"]!!.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun restoreClosesOpenToolCard() {
|
||||
val db = newDb()
|
||||
db.saveLanes(
|
||||
mapOf(
|
||||
"default" to
|
||||
listOf<ChatItem>(
|
||||
msg("m1", ts = 100),
|
||||
ToolItem(id = "tool_1", index = 0, name = "bash", done = false, anchorId = "m1"),
|
||||
ToolItem(id = "tool_2", index = 1, name = "ls", done = true, ok = true, anchorId = "m1"),
|
||||
),
|
||||
),
|
||||
)
|
||||
val lane = db.loadLanes()["default"]!!
|
||||
// The process died before tool.end — the open card is closed as
|
||||
// interrupted, not left spinning.
|
||||
val open = lane.first { it.id == "tool_1" } as ToolItem
|
||||
assertTrue(open.done)
|
||||
assertFalse(open.ok)
|
||||
// A completed card is untouched.
|
||||
val done = lane.first { it.id == "tool_2" } as ToolItem
|
||||
assertTrue(done.ok)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun saveLanesReplacesPreviousSnapshot() {
|
||||
val db = newDb()
|
||||
db.saveLanes(mapOf("default" to listOf(msg("m1"), msg("m2"))))
|
||||
db.saveLanes(mapOf("default" to listOf(msg("m2"))))
|
||||
assertEquals(listOf("m2"), db.loadLanes()["default"]!!.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun restoreSanitizesMidFlightState() {
|
||||
val db = newDb()
|
||||
db.saveLanes(
|
||||
mapOf(
|
||||
"default" to
|
||||
listOf(
|
||||
msg("p1", status = MsgStatus.Pending, pending = true, ts = 0),
|
||||
msg("s1", role = "assistant", streaming = true, ts = 500),
|
||||
msg("r1", status = MsgStatus.Read, ts = 600),
|
||||
),
|
||||
),
|
||||
)
|
||||
val lane = db.loadLanes()["default"]!!
|
||||
val msgItem = { id: String -> lane.first { it.id == id } as MessageItem }
|
||||
// A pending send becomes failed (tap to retry); the gateway never
|
||||
// acknowledged it before the process died.
|
||||
assertEquals(MsgStatus.Failed, msgItem("p1").status)
|
||||
assertEquals(false, msgItem("p1").pending)
|
||||
// A streaming bubble is restored as finalized.
|
||||
assertEquals(false, msgItem("s1").streaming)
|
||||
// Read status is preserved.
|
||||
assertEquals(MsgStatus.Read, msgItem("r1").status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun systemMessagesAreNotPersisted() {
|
||||
val db = newDb()
|
||||
db.saveLanes(mapOf("default" to listOf<ChatItem>(msg("sys_1", role = "system", isSystem = true))))
|
||||
assertTrue(db.loadLanes().isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mediaAndRuntimeSurviveRoundTrip() {
|
||||
val db = newDb()
|
||||
val item =
|
||||
MessageItem(
|
||||
id = "m1",
|
||||
role = "assistant",
|
||||
text = "look",
|
||||
ts = 100,
|
||||
runtime = RuntimeMeta(model = "gpt", latency = 1.5),
|
||||
media =
|
||||
listOf(
|
||||
MediaItem(
|
||||
mediaId = "med1",
|
||||
kind = "image",
|
||||
mime = "image/png",
|
||||
size = 42,
|
||||
filename = "a.png",
|
||||
localPath = "/tmp/a.png",
|
||||
),
|
||||
),
|
||||
)
|
||||
db.saveLanes(mapOf("default" to listOf<ChatItem>(item)))
|
||||
val loaded = db.loadLanes()["default"]!!.first() as MessageItem
|
||||
assertEquals("gpt", loaded.runtime?.model)
|
||||
assertEquals("/tmp/a.png", loaded.media.first().localPath)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun channelsRoundTrip() {
|
||||
val db = newDb()
|
||||
db.saveChannels(
|
||||
listOf(
|
||||
ChannelInfo(chatId = "default", name = "General", isDefault = true),
|
||||
ChannelInfo(chatId = "chan_1", name = "Work"),
|
||||
ChannelInfo(chatId = "thr_1", name = "Topic", kind = "thread", parentChatId = "chan_1"),
|
||||
),
|
||||
)
|
||||
val loaded = db.loadChannels()
|
||||
assertEquals(3, loaded.size)
|
||||
assertEquals("Work", loaded.first { it.chatId == "chan_1" }.name)
|
||||
assertEquals("thread", loaded.first { it.chatId == "thr_1" }.kind)
|
||||
assertEquals(true, loaded.first { it.chatId == "default" }.isDefault)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun metaRoundTripAndClearAll() {
|
||||
val db = newDb()
|
||||
assertNull(db.metaGet("last_lane"))
|
||||
db.metaPut("last_lane", "chan_1")
|
||||
assertEquals("chan_1", db.metaGet("last_lane"))
|
||||
db.saveLanes(mapOf("default" to listOf<ChatItem>(msg("m1"))))
|
||||
db.saveChannels(listOf(ChannelInfo(chatId = "default", name = "General")))
|
||||
db.clearAll()
|
||||
assertTrue(db.loadLanes().isEmpty())
|
||||
assertEquals(emptyList<ChannelInfo>(), db.loadChannels())
|
||||
assertNull(db.metaGet("last_lane"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package iris.util
|
||||
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
/**
|
||||
* Parser tests for `iris://pair` links (docs/20). The payload shape mirrors
|
||||
* `pairing.qr_payload` on the gateway side.
|
||||
*/
|
||||
class PairLinkTest {
|
||||
private val token = "ab".repeat(32) // 64 hex chars
|
||||
|
||||
@Test
|
||||
fun parsesValidLink() {
|
||||
val link = PairLink.parse("iris://pair?host=192.168.1.50&port=8791&secure=0&token=$token")
|
||||
assertEquals("http://192.168.1.50:8791", link?.url)
|
||||
assertEquals(token, link?.token)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun defaultsPortTo8791() {
|
||||
val link = PairLink.parse("iris://pair?host=10.0.0.5&token=$token")
|
||||
assertEquals("http://10.0.0.5:8791", link?.url)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun secureOneSelectsHttps() {
|
||||
val link = PairLink.parse("iris://pair?host=10.0.0.5&port=8443&secure=1&token=$token")
|
||||
assertEquals("https://10.0.0.5:8443", link?.url)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun schemeIsCaseInsensitive() {
|
||||
val link = PairLink.parse("IRIS://pair?host=10.0.0.5&token=$token")
|
||||
assertEquals("http://10.0.0.5:8791", link?.url)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun percentDecodesHost() {
|
||||
// A hostname with a space would be %20 on the wire.
|
||||
val link = PairLink.parse("iris://pair?host=my%20host&token=$token")
|
||||
assertEquals("http://my host:8791", link?.url)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsMissingToken() {
|
||||
assertNull(PairLink.parse("iris://pair?host=10.0.0.5&port=8791"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsEmptyToken() {
|
||||
assertNull(PairLink.parse("iris://pair?host=10.0.0.5&token="))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsMissingHost() {
|
||||
assertNull(PairLink.parse("iris://pair?port=8791&token=$token"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsBadPort() {
|
||||
assertNull(PairLink.parse("iris://pair?host=10.0.0.5&port=0&token=$token"))
|
||||
assertNull(PairLink.parse("iris://pair?host=10.0.0.5&port=70000&token=$token"))
|
||||
assertNull(PairLink.parse("iris://pair?host=10.0.0.5&port=abc&token=$token"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsWrongScheme() {
|
||||
assertNull(PairLink.parse("foo://pair?host=10.0.0.5&token=$token"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsWrongHost() {
|
||||
assertNull(PairLink.parse("iris://chat?host=10.0.0.5&token=$token"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsNoAuthority() {
|
||||
assertNull(PairLink.parse("pair?host=10.0.0.5&token=$token"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun acceptsBoundaryPorts() {
|
||||
assertTrue(PairLink.parse("iris://pair?host=h&port=1&token=$token") != null)
|
||||
assertTrue(PairLink.parse("iris://pair?host=h&port=65535&token=$token") != null)
|
||||
}
|
||||
}
|
||||
+10
-10
@@ -11,8 +11,8 @@ create.
|
||||
|
||||
## Goals
|
||||
|
||||
- **Native feel.** Real Android app (Kotlin/Compose), not a WebView. Desktop
|
||||
app that is the same app, resized for a big screen.
|
||||
- **Native feel.** Real native app (Iris on Android, Kotlin/Compose), not a
|
||||
WebView. Desktop app that is the same app, resized for a big screen.
|
||||
- **First-class gateway citizen.** The app is a hermes *messaging platform*, so
|
||||
everything the gateway already does "just works": slash commands, cron
|
||||
delivery, `send_message` routing, coexistence with Telegram/Discord/etc.
|
||||
@@ -40,13 +40,13 @@ Everything in the feature checklist below.
|
||||
## Feature checklist → where it's handled
|
||||
|
||||
| Requirement | Gateway plugin | App |
|
||||
|---|---|---|
|
||||
| --- | --- | --- |
|
||||
| Input box, auto-grow (max height) | — | Compose `TextField` + bounded `heightIn` |
|
||||
| Menu button → all slash commands | Dispatches `/…`; serves command catalog | Bottom-sheet menu + `/` autocomplete |
|
||||
| Tool output (app decides how much) | Emits **structured** tool events | App setting: everything / truncated / nothing |
|
||||
| Reasoning shown before message | Captures + splits reasoning | Collapsible "Reasoning" block above message |
|
||||
| Intermediate messages | Forwards `Commentary` events | Distinct dimmed bubble |
|
||||
| Threading + channels; default chat; user channels for cron | `chat_id`/`thread_id` model; cron `deliver=android:<chat>[:<thread>]` | Channel list, thread toggle, "new channel" |
|
||||
| Threading + channels; default chat; user channels for cron | `chat_id`/`thread_id` model; cron `deliver=iris:<chat>[:<thread>]` | Channel list, thread toggle, "new channel" |
|
||||
| Search ("everywhere" / "this chat/channel") | FTS5 session search bridge | Search UI + scope toggle |
|
||||
| Attach media (music/video/images/docs) | Inbound cache; outbound `send_*` | Pickers + chunked upload + preview |
|
||||
| Push notifications | FCM (primary) / ntfy (fallback) | FCM token / ntfy topic + notification service |
|
||||
@@ -55,9 +55,9 @@ Everything in the feature checklist below.
|
||||
## Locked decisions (from planning)
|
||||
|
||||
| Decision | Choice |
|
||||
|---|---|
|
||||
| --- | --- |
|
||||
| Desktop app tech | **Compose Multiplatform** (shares Android code; "tweaked" for big screen) |
|
||||
| Push backend | **Both** — FCM primary, ntfy fallback (`ANDROID_PUSH_BACKEND`) |
|
||||
| Push backend | **Both** — ntfy default, FCM optional (`IRIS_PUSH_BACKEND`) |
|
||||
| Media transport | **Over the WebSocket** (chunked binary frames; no extra Python deps) |
|
||||
| Phone default layout | **User-toggleable, single-pane default** (auto two-pane on large screens) |
|
||||
|
||||
@@ -66,7 +66,7 @@ Everything in the feature checklist below.
|
||||
1. **`hermes-agent/` is a read-only research reference.** It lives next to this
|
||||
folder for study only. It is **git-ignored** and must **never** be committed,
|
||||
pushed, or included in any artifact. Our plugin is *installed* into a live
|
||||
hermes home (`~/.hermes/plugins/android`); we never edit hermes core files.
|
||||
hermes home (`~/.hermes/plugins/iris`); we never edit hermes core files.
|
||||
2. **ADB is available and a device is connected** (`a5ca2a4b`, Xiaomi MIX 2S,
|
||||
Android 10 / API 29). Use `adb install` / `adb logcat` / `adb shell am start`
|
||||
to install, launch, and debug the app on-device throughout the build.
|
||||
@@ -74,7 +74,7 @@ Everything in the feature checklist below.
|
||||
## Verified environment state (2026-08-19)
|
||||
|
||||
| Item | State |
|
||||
|---|---|
|
||||
| --- | --- |
|
||||
| OS | CachyOS (Arch-based), `pacman` present |
|
||||
| JDK | **Not installed** → Milestone M0 (`pacman -S jdk17-openjdk`) |
|
||||
| Android SDK | **Not installed** → M0 (cmdline-tools + sdkmanager) |
|
||||
@@ -88,6 +88,6 @@ Everything in the feature checklist below.
|
||||
## Naming
|
||||
|
||||
- Product/effort name: **Iris × Hermes** (folder `iris_x_hermes`).
|
||||
- hermes platform name: **`android`** (the plugin registers `Platform("android")`).
|
||||
- hermes platform name: **`iris`** (the plugin registers `Platform("iris")`).
|
||||
- WS default port: **8790** (configurable).
|
||||
- Default chat id: **`android:default`** (the home channel).
|
||||
- Default chat id: **`default`** (the home channel).
|
||||
+10
-10
@@ -11,8 +11,8 @@
|
||||
│ │ │ │ │
|
||||
│ │ ▼ legacy stream callbacks (delta / tool-progress / commentary) │ │
|
||||
│ │ ┌──────────────────────────────┐ ┌────────────────────────────────┐ │ │
|
||||
│ │ │ android PLATFORM PLUGIN │◄───────►│ WebSocket SERVER (websockets) │ │ │
|
||||
│ │ │ AndroidAdapter │ JSON │ ws://host:8790/ws │ │ │
|
||||
│ │ │ IRIS PLATFORM PLUGIN │◄───────►│ WebSocket SERVER (websockets) │ │ │
|
||||
│ │ │ IrisAdapter │ JSON │ ws://host:8790/ws │ │ │
|
||||
│ │ │ (BasePlatformAdapter) │ frames │ + media + FCM-token + pairing │ │ │
|
||||
│ │ │ • send / edit / stream │ └───────────────┬────────────────┘ │ │
|
||||
│ │ │ • media cache │ │ WSS │ │
|
||||
@@ -26,7 +26,7 @@
|
||||
│ │ Google FCM cloud │
|
||||
▼ │ │ │
|
||||
┌────────────────────────┐ │ ▼ │
|
||||
│ ANDROID APP │◄──┴── (wake) ┌──────────┐
|
||||
│ IRIS APP (ANDROID) │◄──┴── (wake) ┌──────────┐
|
||||
│ (Kotlin / Compose) │ WSS │ PHONE │
|
||||
│ • WS client (OkHttp) │◄───────────►│ MIX 2S │
|
||||
│ • ExoPlayer │ │ (API 29) │
|
||||
@@ -40,8 +40,8 @@
|
||||
## Process model
|
||||
|
||||
- **One `hermes gateway` process** hosts the agent core, the session store, the
|
||||
cron scheduler, *and* our `android` platform plugin. The plugin's WebSocket
|
||||
server runs on the gateway's asyncio loop (started in `AndroidAdapter.connect()`).
|
||||
cron scheduler, *and* our `iris` platform plugin. The plugin's WebSocket
|
||||
server runs on the gateway's asyncio loop (started in `IrisAdapter.connect()`).
|
||||
- **The app is a client.** It *initiates* the WS connection to the gateway
|
||||
(outbound), so no inbound port is needed on the phone. For LAN/remote access
|
||||
the user points the app at the gateway's LAN IP / Tailscale name / a WSS
|
||||
@@ -56,7 +56,7 @@ serves Telegram/Discord/… and cron) and the **`tui_gateway`** JSON-RPC backend
|
||||
(used by the TUI and the existing Electron desktop app). We deliberately use the
|
||||
**messaging gateway** because:
|
||||
|
||||
1. **Cron delivery is native.** Cron jobs resolve `deliver=android:<chat>[:<thread>]`
|
||||
1. **Cron delivery is native.** Cron jobs resolve `deliver=iris:<chat>[:<thread>]`
|
||||
through the platform registry and call our adapter's `send()`. No bridging.
|
||||
2. **`send_message` tool routing** works out of the box (plugin
|
||||
`parse_target_ref_fn`).
|
||||
@@ -72,7 +72,7 @@ protocol (`04-wire-protocol.md`) that borrows familiar names (`message.*`,
|
||||
## Key architectural decisions + rationale
|
||||
|
||||
| Decision | Rationale |
|
||||
|---|---|
|
||||
| --- | --- |
|
||||
| **Community-style platform plugin** (`register(ctx)` → `ctx.register_platform`) | Zero hermes-core changes; survives hermes updates; follows `ADDING_A_PLATFORM.md` "Plugin Path". |
|
||||
| **Single WS transport** for chat, streaming, tools, media, pairing, FCM-token | One connection, one auth, one dependency (`websockets`, already core). Media as chunked binary frames avoids adding an HTTP server. |
|
||||
| **`websockets` + `httpx` only** | Both are hermes *core* deps → the plugin adds **zero** new Python dependencies (respects hermes supply-chain pinning policy). |
|
||||
@@ -80,13 +80,13 @@ protocol (`04-wire-protocol.md`) that borrows familiar names (`message.*`,
|
||||
| **Reasoning split in the adapter** | The gateway prepends reasoning to the final text when `show_reasoning` is on; the adapter splits the stable prefix into a `reasoning` field so the app renders a clean collapsible block. |
|
||||
| **Channels/threads = `chat_id`/`thread_id`** | The gateway's `SessionSource` already models this; cron delivery already targets `platform:chat_id:thread_id`. We map app concepts onto existing primitives. |
|
||||
| **SQLite outbox + sync cursor** | Offline delivery + reconnect catch-up without re-reading full history. |
|
||||
| **Compose Multiplatform** | Desktop is "the Android app, tweaked" → share protocol/state/UI; only platform services + layout differ. |
|
||||
| **Compose Multiplatform** | Desktop is "the Iris app, tweaked" → share protocol/state/UI; only platform services + layout differ. |
|
||||
|
||||
## Data flow (one turn)
|
||||
|
||||
1. App sends `message.send {text}` (or `/cmd`).
|
||||
2. Plugin builds a `MessageEvent` (+ `media_urls` if attachments) →
|
||||
`AndroidAdapter.handle_message(event)`.
|
||||
`IrisAdapter.handle_message(event)`.
|
||||
3. Gateway resolves the session (`chat_id`/`thread_id`), runs the agent.
|
||||
4. Agent streams: `stream_delta_callback` → `GatewayStreamConsumer` →
|
||||
`adapter.send()` (first) / `adapter.edit_message()` (updates) →
|
||||
@@ -103,4 +103,4 @@ protocol (`04-wire-protocol.md`) that borrows familiar names (`message.*`,
|
||||
> (not the ACP-only event-native `render_message_event` path). We therefore map
|
||||
> the legacy `send`/`edit_message`/progress calls to our frames. The exact
|
||||
> tool-progress vs commentary classification is verified empirically in M2 by
|
||||
> running the real gateway with a test WS client (see `13-testing.md`).
|
||||
> running the real gateway with a test WS client (see `13-testing.md`).
|
||||
+12
-9
@@ -13,10 +13,10 @@ iris_x_hermes/
|
||||
│
|
||||
├── hermes-agent/ # ⚠️ READ-ONLY REFERENCE — NEVER PUSHED (git-ignored)
|
||||
│
|
||||
├── gateway-plugin/ # ① Python plugin → installed to ~/.hermes/plugins/android
|
||||
├── gateway-plugin/ # ① Python plugin → installed to ~/.hermes/plugins/iris
|
||||
│ ├── plugin.yaml # manifest (kind: platform, env vars, home channel)
|
||||
│ ├── __init__.py
|
||||
│ ├── adapter.py # AndroidAdapter(BasePlatformAdapter) + register(ctx)
|
||||
│ ├── adapter.py # IrisAdapter(BasePlatformAdapter) + register(ctx)
|
||||
│ ├── ws_server.py # websockets server, connection registry, framing
|
||||
│ ├── protocol.py # frame schemas (source of truth, mirrored in Kotlin)
|
||||
│ ├── media.py # inbound cache + outbound chunked streaming
|
||||
@@ -50,9 +50,10 @@ iris_x_hermes/
|
||||
## Module responsibilities
|
||||
|
||||
### `gateway-plugin/` (Python)
|
||||
- **`plugin.yaml`** — manifest: `name: android-platform`, `kind: platform`,
|
||||
|
||||
- **`plugin.yaml`** — manifest: `name: iris-platform`, `kind: platform`,
|
||||
`requires_env` / `optional_env` (surfaced in `hermes config`/setup).
|
||||
- **`adapter.py`** — `AndroidAdapter(BasePlatformAdapter)` + `register(ctx)`.
|
||||
- **`adapter.py`** — `IrisAdapter(BasePlatformAdapter)` + `register(ctx)`.
|
||||
The heart of the plugin. See `03-gateway-plugin.md`.
|
||||
- **`ws_server.py`** — `websockets` server, per-device connection registry,
|
||||
frame encode/decode, heartbeat, broadcast routing to all connected devices.
|
||||
@@ -61,13 +62,14 @@ iris_x_hermes/
|
||||
- **`media.py`** — inbound chunked upload → `cache_*_from_bytes`; outbound
|
||||
`media.offer`/`media.pull` chunked streaming.
|
||||
- **`outbox.py`** — SQLite outbox per `chat_id` + monotonic sync cursor.
|
||||
- **`push.py`** — `PushBackend` interface; `FcmBackend` (httpx, FCM HTTP v1) and
|
||||
`NtfyBackend` (reuses hermes ntfy publish). Selected by `ANDROID_PUSH_BACKEND`.
|
||||
- **`push.py`** — `PushBackend` interface; `NtfyBackend` (default) and
|
||||
`FcmBackend` (httpx, FCM HTTP v1). Selected by `IRIS_PUSH_BACKEND`.
|
||||
- **`pairing.py`** — token generation/verification (constant-time), device
|
||||
registry (SQLite), QR payload.
|
||||
- **`search.py`** — FTS5 query bridge over the hermes session store.
|
||||
|
||||
### `app/shared` (Kotlin KMP)
|
||||
|
||||
- **`commonMain`** — protocol models (kotlinx-serialization), `GatewayClient`
|
||||
(OkHttp WS), repositories (Room), ViewModels (StateFlow), and the Compose UI
|
||||
(design system, screens). ~80% of app code.
|
||||
@@ -77,13 +79,14 @@ iris_x_hermes/
|
||||
window management, `MediaPlayer` actual.
|
||||
|
||||
### `app/androidApp` / `app/desktopApp`
|
||||
|
||||
Thin shells: `Application`/`MainActivity` (Android) and `main()`/window
|
||||
(Desktop). They compose the `shared` UI and inject platform services.
|
||||
|
||||
## Build systems
|
||||
|
||||
- **Python plugin:** no build step (pure Python, stdlib + hermes core deps).
|
||||
Installed by copying/symlinking into `~/.hermes/plugins/android`. Tested with
|
||||
Installed by copying/symlinking into `~/.hermes/plugins/iris`. Tested with
|
||||
hermes's `scripts/run_tests.sh`.
|
||||
- **Kotlin/CMP:** Gradle (Kotlin DSL) with the Compose Multiplatform plugin.
|
||||
`./gradlew :androidApp:installDebug`, `./gradlew :desktopApp:run`,
|
||||
@@ -124,7 +127,7 @@ keystore.jks
|
||||
|
||||
## Install layout (runtime)
|
||||
|
||||
- **Plugin:** `~/.hermes/plugins/android/` ← copy of `gateway-plugin/`
|
||||
- **Plugin:** `~/.hermes/plugins/iris/` ← copy of `gateway-plugin/`
|
||||
(or a symlink for dev). Discovered by hermes's `PluginManager`.
|
||||
- **App (dev):** installed on-device via `./gradlew :androidApp:installDebug`.
|
||||
- **App (desktop, dev):** `./gradlew :desktopApp:run`.
|
||||
- **App (desktop, dev):** `./gradlew :desktopApp:run`.
|
||||
+78
-71
@@ -1,6 +1,6 @@
|
||||
# 03 — Gateway Plugin (Python)
|
||||
|
||||
The plugin is a **community-style hermes platform plugin** named `android`.
|
||||
The plugin is a **community-style hermes platform plugin** named `iris`.
|
||||
It follows the "Plugin Path" in `hermes-agent/gateway/platforms/ADDING_A_PLATFORM.md`
|
||||
and the canonical example `hermes-agent/plugins/platforms/irc/adapter.py`.
|
||||
**Zero hermes-core changes. Zero new Python dependencies** (`websockets` and
|
||||
@@ -11,8 +11,8 @@ and the canonical example `hermes-agent/plugins/platforms/irc/adapter.py`.
|
||||
## 3.1 `plugin.yaml` (manifest)
|
||||
|
||||
```yaml
|
||||
name: android-platform
|
||||
label: Android
|
||||
name: iris-platform
|
||||
label: Iris
|
||||
kind: platform
|
||||
version: 0.1.0
|
||||
description: >
|
||||
@@ -22,63 +22,63 @@ description: >
|
||||
channels/threads, media, FTS5 search, and FCM/ntfy push.
|
||||
author: <you>
|
||||
requires_env:
|
||||
- name: ANDROID_TOKEN
|
||||
- name: IRIS_TOKEN
|
||||
description: "Shared pairing token the app presents on connect"
|
||||
prompt: "Android pairing token"
|
||||
prompt: "Iris pairing token"
|
||||
password: true
|
||||
optional_env:
|
||||
- name: ANDROID_WS_HOST
|
||||
description: "WS bind host (default 127.0.0.1; use 0.0.0.0 for LAN)"
|
||||
prompt: "WS host"
|
||||
- name: IRIS_HTTP_HOST
|
||||
description: "HTTP bind host (default 127.0.0.1; use 0.0.0.0 for LAN)"
|
||||
prompt: "HTTP host"
|
||||
password: false
|
||||
- name: ANDROID_WS_PORT
|
||||
description: "WS port (default 8790)"
|
||||
prompt: "WS port"
|
||||
- name: IRIS_HTTP_PORT
|
||||
description: "HTTP port (default 8791)"
|
||||
prompt: "HTTP port"
|
||||
password: false
|
||||
- name: ANDROID_HOME_CHANNEL
|
||||
description: "Default chat id for cron/notification delivery (default android:default)"
|
||||
- name: IRIS_HOME_CHANNEL
|
||||
description: "Default chat id for cron/notification delivery (default default)"
|
||||
prompt: "Home channel"
|
||||
password: false
|
||||
- name: ANDROID_ALLOWED_USERS
|
||||
- name: IRIS_ALLOWED_USERS
|
||||
description: "Comma-separated allowed device_ids (empty = token-only auth)"
|
||||
prompt: "Allowed device ids"
|
||||
password: false
|
||||
- name: ANDROID_ALLOW_ALL_USERS
|
||||
- name: IRIS_ALLOW_ALL_USERS
|
||||
description: "Allow any paired device (dev only)"
|
||||
prompt: "Allow all devices? (true/false)"
|
||||
password: false
|
||||
- name: ANDROID_PUSH_BACKEND
|
||||
description: "Push backend: fcm (default) or ntfy"
|
||||
- name: IRIS_PUSH_BACKEND
|
||||
description: "Push backend: ntfy (default, keeps metadata off Google) or fcm"
|
||||
prompt: "Push backend"
|
||||
password: false
|
||||
- name: ANDROID_FCM_SERVICE_ACCOUNT
|
||||
- name: IRIS_FCM_SERVICE_ACCOUNT
|
||||
description: "Path to Firebase service-account JSON (FCM HTTP v1)"
|
||||
prompt: "FCM service account path"
|
||||
password: true
|
||||
- name: ANDROID_FCM_SERVER_KEY
|
||||
- name: IRIS_FCM_SERVER_KEY
|
||||
description: "Legacy FCM server key (fallback if no service account)"
|
||||
prompt: "FCM server key"
|
||||
password: true
|
||||
- name: NTFY_TOPIC
|
||||
description: "ntfy topic for push (when ANDROID_PUSH_BACKEND=ntfy)"
|
||||
description: "ntfy topic for push (when IRIS_PUSH_BACKEND=ntfy)"
|
||||
prompt: "ntfy topic"
|
||||
password: false
|
||||
- name: NTFY_SERVER_URL
|
||||
description: "ntfy server URL (default https://ntfy.sh)"
|
||||
prompt: "ntfy server URL"
|
||||
password: false
|
||||
- name: ANDROID_WS_CERT
|
||||
description: "TLS cert path for WSS (optional)"
|
||||
prompt: "WSS cert"
|
||||
- name: IRIS_HTTP_CERT
|
||||
description: "TLS cert path for HTTPS (optional)"
|
||||
prompt: "HTTPS cert"
|
||||
password: false
|
||||
- name: ANDROID_WS_KEY
|
||||
description: "TLS key path for WSS (optional)"
|
||||
prompt: "WSS key"
|
||||
- name: IRIS_HTTP_KEY
|
||||
description: "TLS key path for HTTPS (optional)"
|
||||
prompt: "HTTPS key"
|
||||
password: false
|
||||
```
|
||||
|
||||
Behavioral (non-secret) settings live in `config.yaml` under
|
||||
`gateway.platforms.android.extra` (host, port, home_channel, outbox retention,
|
||||
`gateway.platforms.iris.extra` (host, port, home_channel, outbox retention,
|
||||
max upload bytes, tls). Secrets live in `.env`. (hermes policy: `.env` = secrets
|
||||
only.)
|
||||
|
||||
@@ -87,21 +87,21 @@ only.)
|
||||
```python
|
||||
def register(ctx):
|
||||
ctx.register_platform(
|
||||
name="android",
|
||||
label="Android",
|
||||
adapter_factory=lambda cfg: AndroidAdapter(cfg),
|
||||
name="iris",
|
||||
label="Iris",
|
||||
adapter_factory=lambda cfg: IrisAdapter(cfg),
|
||||
check_fn=check_requirements, # passive: websockets importable + token set
|
||||
validate_config=validate_config, # host/port/token present
|
||||
is_connected=is_connected,
|
||||
required_env=["ANDROID_TOKEN"],
|
||||
required_env=["IRIS_TOKEN"],
|
||||
install_hint="No extra packages needed (websockets + httpx are core deps)",
|
||||
setup_fn=interactive_setup, # hermes gateway setup flow
|
||||
env_enablement_fn=_env_enablement, # seed extra + home_channel from env
|
||||
cron_deliver_env_var="ANDROID_HOME_CHANNEL",
|
||||
cron_deliver_env_var="IRIS_HOME_CHANNEL",
|
||||
standalone_sender_fn=_standalone_send, # best-effort out-of-proc cron (stretch)
|
||||
parse_target_ref_fn=_parse_target_ref, # "android:<chat>[:<thread>]"
|
||||
allowed_users_env="ANDROID_ALLOWED_USERS",
|
||||
allow_all_env="ANDROID_ALLOW_ALL_USERS",
|
||||
parse_target_ref_fn=_parse_target_ref, # "iris:<chat>[:<thread>]"
|
||||
allowed_users_env="IRIS_ALLOWED_USERS",
|
||||
allow_all_env="IRIS_ALLOW_ALL_USERS",
|
||||
max_message_length=0, # 0 = no limit (WS has none)
|
||||
emoji="📱",
|
||||
pii_safe=False,
|
||||
@@ -123,26 +123,29 @@ Field reference (all from `PlatformEntry`, `gateway/platform_registry.py:63`):
|
||||
`ensure_deps_fn`.
|
||||
|
||||
- **`check_requirements()`** — passive probe: `import websockets` succeeds and
|
||||
`ANDROID_TOKEN` is set. Never installs.
|
||||
`IRIS_TOKEN` is set. Never installs.
|
||||
- **`_env_enablement()`** — returns a dict seeding `PlatformConfig.extra`
|
||||
(host/port/home_channel/push_backend) + a `home_channel` key
|
||||
`{"chat_id": "android:default", "name": "Default"}` so `hermes gateway status`
|
||||
`{"chat_id": "default", "name": "Default"}` so `hermes gateway status`
|
||||
and cron home-channel resolution work without instantiating the adapter.
|
||||
- **`_parse_target_ref(ref)`** — if `ref` starts with `android:`, return
|
||||
`(chat_id, thread_id)` parsed from `android:<chat>[:<thread>]`; else `None`.
|
||||
- **`_parse_target_ref(ref)`** — the core strips the platform prefix first, so
|
||||
`ref` is the direct chat id (e.g. `chan_7`, `default`) with an optional
|
||||
`:t_<n>` thread suffix; friendly names resolve via the channel directory.
|
||||
Returns `(chat_id, thread_id)` or `None`.
|
||||
- **`interactive_setup()`** — prompts for token (or generates one), host/port,
|
||||
push backend + credentials, prints a QR code (pairing) and the app URL.
|
||||
|
||||
## 3.3 `AndroidAdapter(BasePlatformAdapter)`
|
||||
## 3.3 `IrisAdapter(BasePlatformAdapter)`
|
||||
|
||||
Constructor: `super().__init__(config=config, platform=Platform("android"))`.
|
||||
Constructor: `super().__init__(config=config, platform=Platform("iris"))`.
|
||||
Reads `config.extra` (env overrides win). Initializes: WS server (not started
|
||||
until `connect()`), connection registry, outbox (SQLite under
|
||||
`get_hermes_home()/"android"`), push backend, pairing store, channel directory.
|
||||
`get_hermes_home()/"iris"`), push backend, pairing store, channel directory.
|
||||
|
||||
### Lifecycle
|
||||
|
||||
- **`connect(*, is_reconnect=False) -> bool`**
|
||||
- Acquire scoped lock (`gateway.status.acquire_scoped_lock("android", key)`)
|
||||
- Acquire scoped lock (`gateway.status.acquire_scoped_lock("iris", key)`)
|
||||
so two profiles can't bind the same port/identity.
|
||||
- Start the `websockets` server on `host:port` (TLS if cert/key set).
|
||||
- `_mark_connected()`; return True.
|
||||
@@ -150,6 +153,7 @@ until `connect()`), connection registry, outbox (SQLite under
|
||||
- Stop server, close all device sockets, release lock, `_mark_disconnected()`.
|
||||
|
||||
### Inbound (app → agent)
|
||||
|
||||
- WS `message.send {text, reply_to?, media_refs?}` → build `SessionSource` via
|
||||
`self.build_source(chat_id, chat_name, chat_type, user_id, user_name,
|
||||
thread_id)` → build `MessageEvent(text=…, message_type=TEXT, source=…,
|
||||
@@ -171,6 +175,7 @@ until `connect()`), connection registry, outbox (SQLite under
|
||||
- `sync {cursor}` → `outbox.py` → replay frames since cursor.
|
||||
|
||||
### Outbound (agent → app)
|
||||
|
||||
- **`send(chat_id, content, reply_to=None, metadata=None) -> SendResult`**
|
||||
- Split reasoning prefix (see `05-streaming.md`) → `reasoning` field.
|
||||
- If **any** device is connected: broadcast `message` frame to all.
|
||||
@@ -195,7 +200,9 @@ until `connect()`), connection registry, outbox (SQLite under
|
||||
channel directory, return it (used by cron "continuable" threads).
|
||||
|
||||
### Streaming hooks
|
||||
|
||||
The main gateway drives delivery through the **legacy callback path**:
|
||||
|
||||
- `stream_delta_callback` → `GatewayStreamConsumer` → `send()` (first) +
|
||||
`edit_message()` (updates) → `message.start` / `message.update`.
|
||||
- `tool_progress_callback` → progress queue → `send_progress_messages` →
|
||||
@@ -208,29 +215,28 @@ The adapter tracks per-chat **turn state** (in-turn, current streaming
|
||||
`message` vs `tool.*` vs `commentary`. The exact classification markers are
|
||||
verified empirically in M2 (see `13-testing.md`).
|
||||
|
||||
## 3.4 WebSocket server (`ws_server.py`)
|
||||
## 3.4 HTTP server (`http_server.py`)
|
||||
|
||||
- Library: **`websockets`** (core dep, v15). `websockets.serve(handler, host,
|
||||
port, ssl=ctx)`.
|
||||
- **Handler** per connection:
|
||||
1. Await first frame; must be `hello {token, device_id, device_name, caps,
|
||||
fcm_token?}`. Verify token (constant-time) + allowlist. On failure: send
|
||||
`error {code:"auth"}` and close.
|
||||
2. On success: register in connection registry
|
||||
(`device_id → {ws, caps, fcm_token}`), send
|
||||
`hello.ack {server_caps, sync_cursor, channels[]}`.
|
||||
3. Loop: decode frames, dispatch to adapter inbound handlers.
|
||||
4. On close: deregister; if no devices remain, ensure pending outbox
|
||||
frames have push fired.
|
||||
- Library: **stdlib `http.server`** (`ThreadingHTTPServer` +
|
||||
`BaseHTTPRequestHandler`) in a daemon thread; bridges into the gateway's
|
||||
asyncio loop via `asyncio.run_coroutine_threadsafe`. Optional TLS via
|
||||
`ssl.SSLContext` (`IRIS_HTTP_CERT`/`IRIS_HTTP_KEY`). Full design:
|
||||
`19-http-fallback-transport.md`.
|
||||
- **Auth:** `Authorization: Bearer <token>` (constant-time `verify_token`)
|
||||
- device allowlist via `X-Iris-Device`; `401` on failure.
|
||||
- **Endpoints:** `GET /v1/health` (unauthenticated liveness),
|
||||
`POST /v1/frame` (any JSON frame the protocol accepts),
|
||||
`GET /v1/events?cursor=N` (SSE: outbox catch-up + live frames),
|
||||
`GET /v1/poll?cursor=N` (long-poll fallback), `POST /v1/media` +
|
||||
`GET /v1/media/{id}` (media upload/pull).
|
||||
- **Routing:** `emit(chat_id, frame)` → broadcast to **all** connected
|
||||
devices (no per-chat subscribe; single-user model). Global frames
|
||||
(`channel.*`, `status`) also broadcast to all.
|
||||
- **Heartbeat:** WS ping/pong + app-level `ping`/`pong`; dead peers reaped.
|
||||
- **Backpressure:** per-connection send queue with a bounded buffer; drop
|
||||
`message.update` (coalesce to latest) under pressure, never drop
|
||||
`message`/`tool.end`/`notification`.
|
||||
- **Limits:** 64 KiB request body cap, per-device token-bucket rate limit
|
||||
(20/s, burst 40) → `429`; media uploads bounded by the per-upload total
|
||||
cap. No CORS (app clients only).
|
||||
|
||||
## 3.5 State & storage (all under `get_hermes_home()/"android"`)
|
||||
## 3.5 State & storage (all under `get_hermes_home()/"iris"`)
|
||||
|
||||
> Use `get_hermes_home()` from `hermes_constants` for **all** paths (profile-safe).
|
||||
> Never hardcode `~/.hermes`.
|
||||
@@ -245,19 +251,20 @@ verified empirically in M2 (see `13-testing.md`).
|
||||
|
||||
## 3.6 Config resolution
|
||||
|
||||
- **Secrets (`.env`):** `ANDROID_TOKEN`, `ANDROID_FCM_SERVICE_ACCOUNT`,
|
||||
`ANDROID_FCM_SERVER_KEY`, `ANDROID_WS_CERT/KEY`, `NTFY_TOPIC` (if secret).
|
||||
- **Behavioral (`config.yaml` → `gateway.platforms.android.extra`):** `host`,
|
||||
`port`, `home_channel`, `allowed_users`, `push_backend`, `outbox_retention_hours`,
|
||||
`max_upload_bytes`, `tls`.
|
||||
- **Secrets (`.env`):** `IRIS_TOKEN`, `IRIS_FCM_SERVICE_ACCOUNT`,
|
||||
`IRIS_FCM_SERVER_KEY`, `IRIS_HTTP_CERT/KEY`, `NTFY_TOPIC` (if secret).
|
||||
- **Behavioral (`config.yaml` → `gateway.platforms.iris.extra`):** `host`,
|
||||
`http_port`, `home_channel`, `allowed_users`, `push_backend`, `outbox_retention_hours`,
|
||||
`max_upload_bytes`, `http_cert`/`http_key`.
|
||||
- Env vars override `config.yaml` (hermes convention). Read secrets with the
|
||||
scope-aware `_get_scoped_secret` pattern (see `plugins/platforms/irc/adapter.py:42`)
|
||||
so multiplexed profiles don't leak each other's tokens.
|
||||
|
||||
## 3.7 Failure & lifecycle safety
|
||||
|
||||
- WS server bind failure → `_set_fatal_error("bind_failed", …, retryable=True)`.
|
||||
- All outbound sends are best-effort; a dead socket latches and the frame falls
|
||||
to the outbox.
|
||||
- `disconnect()` cancels the server task and closes sockets cleanly.
|
||||
- Token/PII redaction in all logs (hermes PII policy).
|
||||
- HTTP server bind failure → non-fatal: log a warning, disable the HTTP leg,
|
||||
show it in the inspector (the plugin keeps working for other platforms).
|
||||
- All outbound sends are best-effort; a dead stream latches and the frame
|
||||
falls to the outbox.
|
||||
- `disconnect()` stops the HTTP server and closes streams cleanly.
|
||||
- Token/PII redaction in all logs (hermes PII policy).
|
||||
+198
-30
@@ -12,7 +12,7 @@ Every frame:
|
||||
"v": 1,
|
||||
"id": 42, // optional; present on requests + their responses
|
||||
"type": "message", // frame type (below)
|
||||
"chat_id": "android:default", // optional; scope for chat-scoped frames
|
||||
"chat_id": "default", // optional; scope for chat-scoped frames
|
||||
"thread_id": "t_123", // optional
|
||||
"payload": { } // type-specific object
|
||||
}
|
||||
@@ -34,25 +34,46 @@ JSON `media.upload.end` / final ack. See `07-media.md`.
|
||||
## Server → App (events / responses)
|
||||
|
||||
### `hello.ack`
|
||||
|
||||
Pairing succeeded.
|
||||
|
||||
```json
|
||||
{"type":"hello.ack","payload":{
|
||||
"server_caps":{"streaming":true,"reasoning":true,"tools":true,"media":true,
|
||||
"search":true,"push":"fcm","pickers":true},
|
||||
"search":true,"push":"fcm","pickers":true,
|
||||
"app_version":"0.1.2"},
|
||||
"sync_cursor":1042,
|
||||
"last_pushed_cursor":1040,
|
||||
"channels":[{"chat_id":"android:default","name":"Default","kind":"default","is_default":true}]
|
||||
"device_token":"9f2c…(64 hex)",
|
||||
"channels":[{"chat_id":"default","name":"Default","kind":"default","is_default":true}]
|
||||
}}
|
||||
```
|
||||
|
||||
`server_caps.app_version` is the gateway plugin's release version (the
|
||||
repo-root `VERSION` file, `gateway-plugin/version.py`). The app shows it in
|
||||
Settings → About (next to its own version) and hints when the app and
|
||||
gateway versions differ.
|
||||
The app reports its own version on the SSE open via the
|
||||
`X-Iris-App-Version` header (stored in the device registry's `caps` JSON,
|
||||
visible in `~/.hermes/.../devices.db`).
|
||||
|
||||
`last_pushed_cursor` is the highest outbox cursor already delivered to THIS
|
||||
device via the push backend (0 = never). The app skips system notifications
|
||||
for sync-replayed frames with `cursor <= last_pushed_cursor` — they already
|
||||
woke the device via push (dedupe, `08-push.md` §8.7).
|
||||
|
||||
`device_token` is the per-device token minted at pairing (docs/09 §9.3):
|
||||
the app stores it and presents it in the `Authorization` header INSTEAD of
|
||||
the shared `IRIS_TOKEN` from then on, so the gateway can revoke one device
|
||||
without affecting the others. Empty when the gateway didn't issue one
|
||||
(legacy).
|
||||
|
||||
### `message`
|
||||
|
||||
A final / standalone message.
|
||||
|
||||
```json
|
||||
{"type":"message","chat_id":"android:default","thread_id":null,
|
||||
{"type":"message","chat_id":"default","thread_id":null,
|
||||
"payload":{
|
||||
"message_id":"m_9001","role":"assistant",
|
||||
"text":"Here is the answer…",
|
||||
@@ -60,65 +81,137 @@ A final / standalone message.
|
||||
"media":[{"media_id":"md_5","kind":"video","mime":"video/mp4","size":123456,
|
||||
"filename":"clip.mp4"}], // optional
|
||||
"reply_to":"m_8999", // optional
|
||||
"model":"qwen3-27b","tokens":11,"ts":1724000000000
|
||||
"model":"qwen3-27b","tokens":11,"ts":1724000000000,
|
||||
"runtime":{"model":"qwen3-27b","context_pct":38,"cwd":"~",
|
||||
"latency":22.5,"cost":0.0012} // optional; see below
|
||||
}}
|
||||
```
|
||||
|
||||
`role` ∈ `user | assistant | system | cron`. `reasoning` present only when the
|
||||
agent produced reasoning and `show_reasoning` is on.
|
||||
|
||||
`runtime` (optional) is the **structured runtime-metadata footer** the app
|
||||
renders under final assistant messages (Telegram-style). The gateway ALWAYS
|
||||
sends it on final assistant messages; whether/what is shown is a **per-app
|
||||
setting** (Settings → Runtime footer), NOT a hermes config. Keys (all
|
||||
optional; absent when the data is unavailable, e.g. local models have no
|
||||
cost):
|
||||
|
||||
- `model` — bare model id, vendor prefix dropped (`gpt-5.4`)
|
||||
- `context_pct` — last-call context occupancy, 0-100 (int)
|
||||
- `cwd` — home-relative working dir (`~`)
|
||||
- `latency` — wall-clock turn duration, seconds (float)
|
||||
- `cost` — turn cost, USD (float)
|
||||
|
||||
### `message.start` / `message.update` / `message.stop`
|
||||
|
||||
Streaming a bubble. `update` carries the **full** current text (app replaces).
|
||||
|
||||
```json
|
||||
{"type":"message.start","chat_id":"…","payload":{"message_id":"m_9002","role":"assistant"}}
|
||||
{"type":"message.update","chat_id":"…","payload":{"message_id":"m_9002","text":"partial…"}}
|
||||
{"type":"message.stop","chat_id":"…","payload":{"message_id":"m_9002","final_text":"full…",
|
||||
"reasoning":"…","model":"…","tokens":11}}
|
||||
"reasoning":"…","model":"…","tokens":11,
|
||||
"runtime":{"model":"…","context_pct":38,"cwd":"~","latency":22.5}}}
|
||||
```
|
||||
|
||||
### `message.deleted`
|
||||
|
||||
The given message(s) were deleted from a chat/thread. Response to a
|
||||
`message.delete` request (`id` set) **and** broadcast to every device so all of
|
||||
them drop the message(s) from their cache. Also outboxed, so a device that was
|
||||
offline learns of the deletion on its next `sync`.
|
||||
|
||||
```json
|
||||
{"type":"message.deleted","id":30,"chat_id":"android:default","thread_id":null,
|
||||
{"type":"message.deleted","id":30,"chat_id":"default","thread_id":null,
|
||||
"payload":{"message_ids":["m_9001","m_9002"]}}
|
||||
```
|
||||
|
||||
### `commentary`
|
||||
|
||||
Intermediate assistant beat (between tool iterations).
|
||||
|
||||
```json
|
||||
{"type":"commentary","chat_id":"…","payload":{"message_id":"m_9003","text":"Let me inspect the repo first."}}
|
||||
```
|
||||
|
||||
### `tool.start` / `tool.progress` / `tool.end`
|
||||
|
||||
**Structured** tool events. The app decides how much to show (everything /
|
||||
truncated / nothing).
|
||||
|
||||
```json
|
||||
{"type":"tool.start","chat_id":"…","payload":{
|
||||
"index":3,"name":"terminal","preview":"pytest -q","args":{"command":"pytest -q"}}}
|
||||
"index":3,"name":"terminal","preview":"pytest -q","args":{"command":"pytest -q"},"emoji":"💻"}}
|
||||
{"type":"tool.progress","chat_id":"…","payload":{"index":3,"name":"terminal","note":"running…"}}
|
||||
{"type":"tool.end","chat_id":"…","payload":{"index":3,"name":"terminal","ok":true,"duration":12.4,
|
||||
"output_preview":"12 passed"}}
|
||||
```
|
||||
|
||||
`args` may be large; the app truncates per its setting. `output_preview` is a
|
||||
short tail (full output is not streamed — it lives in agent history).
|
||||
|
||||
`emoji` is a cosmetic per-tool glyph resolved server-side via hermes'
|
||||
`get_tool_emoji` (active-skin overrides, then the tool registry's per-tool
|
||||
`emoji` — e.g. `read_file` 📖, `write_file` ✍️, `terminal` 💻). Omitted when
|
||||
the tool is unknown, so the app falls back to its own default glyph.
|
||||
|
||||
### `todo.update`
|
||||
|
||||
The agent's **full current todo list** for a chat/thread lane (last-write-wins).
|
||||
Emitted whenever the `todo` tool completes — the tool *result* is the
|
||||
authoritative list, which also covers `merge` writes (whose args carry only
|
||||
the changed items) and read-only calls — and, as a **snapshot**, right after
|
||||
`hello` when a device opens its event stream.
|
||||
|
||||
```json
|
||||
{"type":"todo.update","chat_id":"default","thread_id":null,"payload":{
|
||||
"todos":[
|
||||
{"id":"1","content":"Scaffold the module","status":"completed"},
|
||||
{"id":"2","content":"Wire the store","status":"in_progress"},
|
||||
{"id":"3","content":"Add tests","status":"pending"}
|
||||
]}}
|
||||
```
|
||||
|
||||
`status` is one of `pending | in_progress | completed | cancelled`. The frame
|
||||
is **ephemeral**: it is never outboxed, so a reconnecting device learns the
|
||||
current list from the snapshot (not a replay), and a gateway restart drops it
|
||||
(the agent re-emits on the next `todo` call). The app renders it as a compact
|
||||
scrollable strip above the composer (max 3 lines; auto-scrolls to the item
|
||||
whose status just changed) and hides it once the list is empty or fully
|
||||
resolved.
|
||||
|
||||
### `typing` / `typing.stop`
|
||||
|
||||
```json
|
||||
{"type":"typing","chat_id":"…","payload":{"on":true}}
|
||||
```
|
||||
|
||||
### `notification`
|
||||
|
||||
In-app banner (foreground) and/or push mirror (background).
|
||||
|
||||
```json
|
||||
{"type":"notification","chat_id":"…","payload":{
|
||||
"kind":"channel_renamed","title":"ARIA","body":"Renamed topic to …","ts":1724000000000}}
|
||||
```
|
||||
|
||||
`kind` ∈ `channel_renamed | channel_created | cron | approval | clarify | generic`.
|
||||
|
||||
### `picker.model` / `picker.choice` / `picker.clarify` / `picker.approval` / `picker.confirm`
|
||||
|
||||
Interactive prompts. App renders a native picker; answers via `picker.select`.
|
||||
|
||||
`picker.choice` is implemented (the generic finite-choice menu used by
|
||||
`/reasoning`, `/fast`, and any future finite-choice slash command — hermes
|
||||
calls the adapter's `send_choice_picker` when the platform supports it).
|
||||
The server runs the command's selection callback on `picker.select` and
|
||||
delivers its reply as a normal `message` in the picker's chat. The frame is
|
||||
outboxed (a reconnecting device re-renders a still-pending picker); pending
|
||||
state is in-memory only, so a gateway restart expires it (a stale
|
||||
`picker.select` is a no-op). With no live device the adapter reports failure
|
||||
and hermes falls back to the text status card.
|
||||
|
||||
```json
|
||||
{"type":"picker.model","chat_id":"…","payload":{
|
||||
"picker_id":"pm_1","current_model":"qwen3-27b","current_provider":"local",
|
||||
@@ -129,21 +222,26 @@ Interactive prompts. App renders a native picker; answers via `picker.select`.
|
||||
```
|
||||
|
||||
### `channel.list` / `channel.created` / `channel.renamed` / `channel.deleted`
|
||||
|
||||
Channel directory updates. **Broadcast to all connected devices** (no explicit
|
||||
subscribe; the server pushes to every open WS).
|
||||
|
||||
```json
|
||||
{"type":"channel.created","payload":{"chat_id":"android:chan_7","name":"Cron Reports",
|
||||
{"type":"channel.created","payload":{"chat_id":"chan_7","name":"Cron Reports",
|
||||
"kind":"channel","parent_chat_id":null}}
|
||||
```
|
||||
|
||||
`channel.created` may carry `"auto":true` for a thread the gateway minted
|
||||
itself for an incoming message (auto-threading): the name is an instant
|
||||
derived title, and a follow-up `channel.renamed` upgrades it to the model's
|
||||
title.
|
||||
|
||||
### `history`
|
||||
|
||||
Response to a `history` request. Returns a page of messages for a chat/thread.
|
||||
|
||||
```json
|
||||
{"type":"history","id":20,"chat_id":"android:default","thread_id":null,
|
||||
{"type":"history","id":20,"chat_id":"default","thread_id":null,
|
||||
"payload":{
|
||||
"messages":[
|
||||
{"message_id":"m_8990","role":"user","text":"Hi","ts":1723990000000},
|
||||
@@ -154,17 +252,20 @@ Response to a `history` request. Returns a page of messages for a chat/thread.
|
||||
"oldest_message_id":"m_8990"
|
||||
}}
|
||||
```
|
||||
|
||||
`messages` are ordered oldest → newest. Paginate with `before_message_id` in the
|
||||
request. The app uses this to **populate the initial view** when a channel is
|
||||
opened (complements `sync`, which only replays undelivered outbox frames).
|
||||
|
||||
### `commands.catalog`
|
||||
|
||||
Request (app → server, empty payload) and response: the gateway's
|
||||
slash-command catalog for the app's `/` drawer. Derived from hermes' central
|
||||
`COMMAND_REGISTRY` (the same source the gateway help and the Telegram command
|
||||
menu use), restricted to commands available on gateway surfaces, plus
|
||||
plugin-registered commands. The app fuzzy-matches the typed prefix
|
||||
client-side (no `commands.complete` round-trip).
|
||||
|
||||
```json
|
||||
{"type":"commands.catalog","id":21,"payload":{
|
||||
"commands":[
|
||||
@@ -173,11 +274,14 @@ client-side (no `commands.complete` round-trip).
|
||||
{"name":"/status","description":"Show session status","args_hint":"","category":"Info","aliases":[]}
|
||||
]}}
|
||||
```
|
||||
|
||||
`name`/`aliases` carry the leading slash; `args_hint` is the registry's
|
||||
argument placeholder (empty when the command takes none).
|
||||
|
||||
### `commands.complete`
|
||||
|
||||
Response to a `commands.complete` request. Autocomplete matches for a typed prefix.
|
||||
|
||||
```json
|
||||
{"type":"commands.complete","id":22,"payload":{
|
||||
"prefix":"/mod",
|
||||
@@ -187,74 +291,100 @@ Response to a `commands.complete` request. Autocomplete matches for a typed pref
|
||||
```
|
||||
|
||||
### `agent.busy` / `agent.idle`
|
||||
|
||||
Agent lifecycle for a chat/thread. App shows a "thinking…" indicator on `busy`.
|
||||
|
||||
```json
|
||||
{"type":"agent.busy","chat_id":"android:default","thread_id":null,
|
||||
{"type":"agent.busy","chat_id":"default","thread_id":null,
|
||||
"payload":{"reason":"processing"}}
|
||||
{"type":"agent.idle","chat_id":"android:default","thread_id":null,"payload":{}}
|
||||
{"type":"agent.idle","chat_id":"default","thread_id":null,"payload":{}}
|
||||
```
|
||||
|
||||
`reason` ∈ `processing | tool | waiting_input | cron`.
|
||||
|
||||
### `search.results`
|
||||
|
||||
```json
|
||||
{"type":"search.results","id":7,"payload":{
|
||||
"query":"deploy","scope":"all","hits":[
|
||||
{"message_id":"m_123","chat_id":"android:chan_7","thread_id":null,
|
||||
{"message_id":"m_123","chat_id":"chan_7","thread_id":null,
|
||||
"role":"assistant","snippet":"…deploy the service…","ts":1723900000000}]}}
|
||||
```
|
||||
|
||||
### `media.offer`
|
||||
|
||||
Agent-sent media is available; app pulls bytes.
|
||||
|
||||
```json
|
||||
{"type":"media.offer","chat_id":"…","payload":{
|
||||
"media_id":"md_5","kind":"video","mime":"video/mp4","size":123456,"filename":"clip.mp4"}}
|
||||
```
|
||||
|
||||
### `read.receipt`
|
||||
|
||||
The gateway acknowledges that the agent has received and started processing
|
||||
the user's message. The app uses it to show ✓✓ on user bubbles.
|
||||
|
||||
```json
|
||||
{"type":"read.receipt","chat_id":"android:default","payload":{"message_id":"m_9001"}}
|
||||
{"type":"read.receipt","chat_id":"default","payload":{"message_id":"m_9001"}}
|
||||
```
|
||||
|
||||
Emitted to the originating connection when a `message.send` is accepted for
|
||||
processing (at the moment it is handed to the agent), for user-originated
|
||||
messages only.
|
||||
|
||||
### `status`
|
||||
|
||||
Gateway health state. Broadcast to all connected clients at startup
|
||||
(`state: "online"`); `restarting` / `degraded` are reserved for future use.
|
||||
(`state: "online"`) and to late joiners on `hello.ack`. The gateway also
|
||||
broadcasts `state: "restarting"` on its shutdown path (restart/stop), right
|
||||
before closing the sockets — the app posts the "Gateway restarting" chat
|
||||
notice immediately on that frame (the socket can take up to the ~20 s ping
|
||||
timeout to actually drop, so the notice must not wait for the disconnect);
|
||||
a plain network drop shows just the reconnect banner. `degraded` is reserved
|
||||
for future use.
|
||||
|
||||
```json
|
||||
{"type":"status","payload":{"state":"online"}}
|
||||
```
|
||||
|
||||
`state` ∈ `online | restarting | degraded`.
|
||||
|
||||
### `error`
|
||||
|
||||
```json
|
||||
{"type":"error","id":7,"payload":{"code":"not_found","message":"chat_id unknown"}}
|
||||
```
|
||||
|
||||
`code` ∈ `auth | not_found | rate_limited | media_too_large | unsupported | internal`.
|
||||
|
||||
### `pong`
|
||||
|
||||
Keepalive reply to `ping`.
|
||||
|
||||
## App → Server (requests / actions)
|
||||
|
||||
### `hello`
|
||||
|
||||
First frame; auth + caps.
|
||||
|
||||
```json
|
||||
{"type":"hello","payload":{
|
||||
"token":"<ANDROID_TOKEN>","device_id":"dev_a1b2","device_name":"MIX 2S",
|
||||
"token":"<IRIS_TOKEN>","device_id":"dev_a1b2","device_name":"MIX 2S",
|
||||
"caps":{"min_protocol":1,"media":true,"push":"fcm"},
|
||||
"fcm_token":"<FCM token>","ntfy_topic":"<topic, if ntfy>"}}
|
||||
```
|
||||
|
||||
### `message.send`
|
||||
|
||||
Send text (or a `/slash-command`).
|
||||
|
||||
```json
|
||||
{"type":"message.send","id":10,"chat_id":"android:default","thread_id":null,
|
||||
{"type":"message.send","id":10,"chat_id":"default","thread_id":null,
|
||||
"payload":{"text":"/model qwen3-27b","reply_to":"m_9001","media_refs":["mu_1"],
|
||||
"auto_thread":false}}
|
||||
```
|
||||
|
||||
`media_refs` reference completed `media.upload`s to attach.
|
||||
`auto_thread` (optional, default false) asks the gateway to mint a fresh
|
||||
thread for the message (auto-threading, `06-channels-cron-search.md` §6.3):
|
||||
@@ -264,7 +394,9 @@ that is not a slash command. The gateway then broadcasts
|
||||
`thread_id`.
|
||||
|
||||
### `media.upload.start` / (binary) / `media.upload.end`
|
||||
|
||||
See `07-media.md`.
|
||||
|
||||
```json
|
||||
{"type":"media.upload.start","id":11,"payload":{
|
||||
"media_ref":"mu_1","kind":"image","mime":"image/jpeg","size":204800,"filename":"a.jpg"}}
|
||||
@@ -273,106 +405,142 @@ See `07-media.md`.
|
||||
```
|
||||
|
||||
### `media.upload.ack`
|
||||
|
||||
Server → App response to `media.upload.end`: the ref is cached and may now be
|
||||
referenced in a `message.send` `media_refs`. Failures use `error` frames instead.
|
||||
|
||||
```json
|
||||
{"type":"media.upload.ack","id":11,"payload":{"ok":true,"media_ref":"mu_1"}}
|
||||
```
|
||||
|
||||
### `media.pull`
|
||||
|
||||
Request agent-sent media bytes.
|
||||
|
||||
```json
|
||||
{"type":"media.pull","id":12,"payload":{"media_id":"md_5"}}
|
||||
// server replies: binary frames, then {"type":"media.pull.end","id":12,"payload":{"ok":true}}
|
||||
```
|
||||
|
||||
### `picker.select`
|
||||
|
||||
Answer an interactive picker.
|
||||
|
||||
```json
|
||||
{"type":"picker.select","id":13,"payload":{"picker_id":"pm_1","value":"local/qwen3-27b"}}
|
||||
```
|
||||
|
||||
### `channel.create` / `channel.rename` / `channel.set_default` / `channel.delete`
|
||||
|
||||
```json
|
||||
{"type":"channel.create","id":14,"payload":{"name":"Cron Reports","kind":"channel"}}
|
||||
{"type":"channel.rename","id":15,"chat_id":"android:chan_7","payload":{"name":"Reports"}}
|
||||
{"type":"channel.set_default","id":16,"chat_id":"android:chan_7","payload":{}}
|
||||
{"type":"channel.rename","id":15,"chat_id":"chan_7","payload":{"name":"Reports"}}
|
||||
{"type":"channel.set_default","id":16,"chat_id":"chan_7","payload":{}}
|
||||
```
|
||||
|
||||
`channel.delete` is a **hard delete**: the channel/thread row is removed from
|
||||
the directory and the lane's history is wiped from the outbox and the hermes
|
||||
session store (no search trace, not recoverable). Deleting a channel also
|
||||
removes its threads. The default channel cannot be deleted.
|
||||
|
||||
### `search`
|
||||
|
||||
```json
|
||||
{"type":"search","id":17,"payload":{"query":"deploy","scope":"all"}}
|
||||
{"type":"search","id":18,"payload":{"query":"deploy","scope":"chat","chat_id":"android:chan_7","thread_id":null}}
|
||||
{"type":"search","id":18,"payload":{"query":"deploy","scope":"chat","chat_id":"chan_7","thread_id":null}}
|
||||
```
|
||||
|
||||
`scope` ∈ `all | chat`.
|
||||
|
||||
### `read.receipt`
|
||||
|
||||
App → server: "user has viewed this message." Server stores the read state and
|
||||
broadcasts to other devices (for multi-device ✓✓ sync). The app uses it to
|
||||
mark messages as read locally (✓✓ on user bubbles).
|
||||
|
||||
```json
|
||||
{"type":"read.receipt","payload":{"chat_id":"android:default","message_id":"m_9001"}}
|
||||
{"type":"read.receipt","payload":{"chat_id":"default","message_id":"m_9001"}}
|
||||
```
|
||||
|
||||
### `history`
|
||||
|
||||
Load a page of messages for a chat/thread (initial open, scroll-up pagination).
|
||||
|
||||
```json
|
||||
{"type":"history","id":20,"chat_id":"android:default","thread_id":null,
|
||||
{"type":"history","id":20,"chat_id":"default","thread_id":null,
|
||||
"payload":{"before_message_id":"m_8990","limit":50}}
|
||||
```
|
||||
|
||||
`before_message_id` — return messages older than this (omit for newest page).
|
||||
`limit` — max messages (default 50, max 200).
|
||||
|
||||
### `message.delete`
|
||||
Delete the given message(s) from a chat/thread. The server removes them from the
|
||||
outbox (so `history`/`sync` no longer return them) and broadcasts
|
||||
`message.deleted` to every device. Idempotent: a message already gone (pruned by
|
||||
retention) still yields a `message.deleted` broadcast so live caches drop it.
|
||||
|
||||
Completely delete the given message(s) from a chat/thread. The server removes
|
||||
them from the outbox (so `history`/`sync` no longer return them) **and** from
|
||||
the hermes session store (so no search trace survives and they are not
|
||||
recoverable), then broadcasts `message.deleted` to every device. Idempotent: a
|
||||
message already gone (pruned by retention) still yields a `message.deleted`
|
||||
broadcast so live caches drop it.
|
||||
|
||||
```json
|
||||
{"type":"message.delete","id":30,"chat_id":"android:default","thread_id":null,
|
||||
{"type":"message.delete","id":30,"chat_id":"default","thread_id":null,
|
||||
"payload":{"message_ids":["m_9001","m_9002"]}}
|
||||
```
|
||||
|
||||
### `commands.catalog`
|
||||
|
||||
Fetch the full slash-command catalog (for the `Menü` bottom sheet).
|
||||
|
||||
```json
|
||||
{"type":"commands.catalog","id":21,"payload":{}}
|
||||
```
|
||||
|
||||
### `commands.complete`
|
||||
|
||||
Autocomplete for a typed `/prefix`.
|
||||
|
||||
```json
|
||||
{"type":"commands.complete","id":22,"payload":{"prefix":"/mod"}}
|
||||
```
|
||||
|
||||
### `agent.stop`
|
||||
|
||||
Stop the current agent turn (abort generation / tool execution).
|
||||
|
||||
```json
|
||||
{"type":"agent.stop","id":23,"chat_id":"android:default","thread_id":null,"payload":{}}
|
||||
{"type":"agent.stop","id":23,"chat_id":"default","thread_id":null,"payload":{}}
|
||||
```
|
||||
|
||||
### `agent.steer`
|
||||
|
||||
Inject a steering message mid-turn (redirects the agent without a new turn).
|
||||
|
||||
```json
|
||||
{"type":"agent.steer","id":24,"chat_id":"android:default","thread_id":null,
|
||||
{"type":"agent.steer","id":24,"chat_id":"default","thread_id":null,
|
||||
"payload":{"text":"Actually, focus on the error case."}}
|
||||
```
|
||||
|
||||
### `sync`
|
||||
|
||||
Reconnect catch-up. Replays **undelivered outbox frames** (frames sent while
|
||||
this device was offline). Does NOT load full history — use `history` for that.
|
||||
|
||||
```json
|
||||
{"type":"sync","id":19,"payload":{"cursor":1042}}
|
||||
// server replays outbox frames with cursor > 1042, then {"type":"sync.done","id":19,"payload":{"cursor":1099}}
|
||||
```
|
||||
|
||||
### `fcm.register`
|
||||
|
||||
Update push token.
|
||||
|
||||
```json
|
||||
{"type":"fcm.register","payload":{"fcm_token":"<new>","ntfy_topic":"<topic>"}}
|
||||
```
|
||||
|
||||
### `ping`
|
||||
|
||||
Keepalive. `{"type":"ping","payload":{"ts":1724000000000}}` → `pong`.
|
||||
|
||||
## Ordering & reliability
|
||||
@@ -387,4 +555,4 @@ Keepalive. `{"type":"ping","payload":{"ts":1724000000000}}` → `pong`.
|
||||
- Anything not delivered live goes to the **outbox** and is replayed by `sync`.
|
||||
- **Broadcast:** channel directory events (`channel.*`) and read-receipts are
|
||||
pushed to **all** connected devices for that gateway (no subscribe step).
|
||||
- Requests get exactly one response or `error` (matched by `id`).
|
||||
- Requests get exactly one response or `error` (matched by `id`).
|
||||
+49
-4
@@ -12,11 +12,13 @@ produced by the gateway and rendered by the app.
|
||||
**Gateway side.** The agent's `stream_delta_callback` feeds a
|
||||
`GatewayStreamConsumer` (`gateway/stream_consumer.py:156`). The consumer
|
||||
accumulates text and, at intervals / thresholds, calls:
|
||||
|
||||
- `adapter.send(chat_id, text)` — first time a bubble is created.
|
||||
- `adapter.edit_message(chat_id, message_id, text)` — subsequent updates
|
||||
(each carries the **full** accumulated text).
|
||||
|
||||
**Adapter → frames.**
|
||||
|
||||
- First `send()` of a turn segment → `message.start {message_id, role}`.
|
||||
- Each `edit_message()` → `message.update {message_id, text}` (full text).
|
||||
- Segment/turn finalization → `message.stop {message_id, final_text, reasoning?,
|
||||
@@ -27,8 +29,45 @@ replace the bubble text (cheap: it's a full snapshot). On `message.stop`,
|
||||
finalize (attach reasoning/model/tokens footer, stop the cursor). Auto-scroll
|
||||
while the user is at the bottom.
|
||||
|
||||
**Smooth streaming (app-side rendering).** Re-parsing + re-laying-out the
|
||||
whole bubble on every update made streamed text unreadable (raw-markdown
|
||||
flashes, constant reflow). `MarkdownText` therefore renders streaming bubbles
|
||||
incrementally:
|
||||
|
||||
- **Reveal (typewriter):** the latest full snapshot is revealed at a steady
|
||||
rate instead of jumping per gateway update. The rate is user-adjustable:
|
||||
Settings → "Streaming speed" (`streamSmoothness`, 0.2–0.8 s between visible
|
||||
updates, lower = faster; `streamCharsPerSecond` maps it to chars/s:
|
||||
`60 / smoothness`, so 0.2 → 300 chars/s, 0.8 → 75 chars/s). Applied on the
|
||||
fly; a backlog exceeding ~2 s of reveal time is revealed at once (fast
|
||||
model / reconnect catch-up).
|
||||
- **Wait for the reveal:** the streaming renderer stays active until the
|
||||
reveal catches up, even after `message.stop` — a fast model that dumps the
|
||||
whole text in one or two frames still plays out the typewriter instead of
|
||||
jumping to the full message. Only then does the bubble switch to the static
|
||||
renderer (which also enables the HTML artifact card).
|
||||
- **Incremental parse:** the revealed prefix is fed as append chunks
|
||||
(`appendChunk`) into the library's `StreamingMarkdownState`
|
||||
(`rememberStreamingMarkdownState`, mikepenz 0.44.0) — an append-only parser
|
||||
that re-parses only the unstable tail. Settled blocks keep AST identity, so
|
||||
Compose never re-lays them out; only the tail re-renders per tick. A
|
||||
non-extension snapshot (rewrite) recreates the parser state and re-seeds it.
|
||||
- **Prefix-preserving transform:** `preserveNewlinesAsHardBreaksStreaming()`
|
||||
is like `preserveNewlinesAsHardBreaks()` but skips the still-incomplete last
|
||||
line, so the transform of a prefix is always a prefix of the transform of
|
||||
the whole (required for pure-append diffs). The static path keeps the
|
||||
original transform plus `retainState = true` (last formatted output stays
|
||||
visible during re-parses — no raw flash).
|
||||
- **Cursor:** the ▉ is appended to the last text leaf by the annotator (not to
|
||||
the parse input, which would break the append diff).
|
||||
|
||||
The gateway cadence (`edit_interval` / `buffer_threshold`, default 0.8 s /
|
||||
24 chars) is unchanged — smoothing happens entirely client-side, so it works
|
||||
with any gateway and per device.
|
||||
|
||||
**Streaming on/off.** Two levels:
|
||||
- **Gateway side:** hermes `display.platforms.android.streaming` (default
|
||||
|
||||
- **Gateway side:** hermes `display.platforms.iris.streaming` (default
|
||||
follows global). When off, the app just gets one final `message` frame.
|
||||
- **App side (per device):** Settings → "Streaming" toggle (default on). When
|
||||
off, the app ignores `message.start`/`message.update` frames and
|
||||
@@ -45,26 +84,30 @@ reference screenshot's "Reasoning:" panel with a copy button).
|
||||
**Gateway side.** hermes prepends reasoning to the final response when
|
||||
`show_reasoning` is enabled (`gateway/run.py:20089`). The format is stable and
|
||||
chosen by `reasoning_style` (`gateway/display_config.py:37`):
|
||||
|
||||
- `code` (default): `💭 **Reasoning:**\n```\n<reasoning>\n```\n\n<response>`
|
||||
- `blockquote`: `> 💭 **Reasoning:**\n> …\n\n<response>`
|
||||
- `subtext`: `-# 💭 Reasoning\n-# …\n\n<response>` (Discord-style)
|
||||
|
||||
**Plugin config.** Set for the `android` platform:
|
||||
**Plugin config.** Set for the `iris` platform:
|
||||
|
||||
```yaml
|
||||
display:
|
||||
platforms:
|
||||
android:
|
||||
iris:
|
||||
show_reasoning: true
|
||||
reasoning_style: code # we split on the code-fence form
|
||||
```
|
||||
|
||||
**Adapter split.** In `send()`, detect the `code`-style prefix and split:
|
||||
|
||||
```
|
||||
prefix = "💭 **Reasoning:**\n```\n"
|
||||
# find the closing "\n```\n\n" after the prefix
|
||||
reasoning = text[len(prefix):close_idx]
|
||||
body = text[close_idx + len("\n```\n\n"):]
|
||||
```
|
||||
|
||||
Emit `message {reasoning: <reasoning>, text: <body>, …}`. If no prefix is found
|
||||
(reasoning off / no reasoning), emit `message {text: …}` with no `reasoning`.
|
||||
|
||||
@@ -89,6 +132,7 @@ gateway progress queue → `send_progress_messages` (`gateway/run.py:4603`) →
|
||||
|
||||
**Adapter → frames.** The adapter classifies tool activity (via turn-state +
|
||||
line format) and emits **structured** frames — not pre-formatted strings:
|
||||
|
||||
- `tool.start {index, name, preview, args}` — a tool call began.
|
||||
- `tool.progress {index, name, note}` — in-progress update (optional).
|
||||
- `tool.end {index, name, ok, duration, output_preview}` — completed.
|
||||
@@ -99,6 +143,7 @@ short tail; full tool output is **not** streamed (it lives in agent history and
|
||||
is reachable via search).
|
||||
|
||||
**App side — the verbosity setting** (Settings → "Tool detail"):
|
||||
|
||||
- **Everything** — show tool name, full args (collapsible), and output preview.
|
||||
- **Truncated** (default) — show `emoji name: "short preview"` one-liner,
|
||||
collapsible to expand.
|
||||
@@ -147,4 +192,4 @@ srv → message.start {message_id:m3}
|
||||
srv → message.update {m3, "The repo has…"}
|
||||
srv → message.stop {m3, final_text:"…", reasoning:"…", model:"…", tokens:42}
|
||||
srv → typing {on:false}
|
||||
```
|
||||
```
|
||||
@@ -8,11 +8,11 @@ The hermes gateway already models conversations as `SessionSource` with
|
||||
gateway identity concepts**.
|
||||
|
||||
| App concept | hermes primitive | Example |
|
||||
|---|---|---|
|
||||
| Default chat | home channel `chat_id` | `android:default` |
|
||||
| A thread (inside default chat) | `thread_id` under the default `chat_id` | `chat_id=android:default, thread_id=t_12` |
|
||||
| A user-created channel | a new `chat_id` | `android:chan_7` |
|
||||
| A thread inside a channel | `thread_id` under that `chat_id` | `chat_id=android:chan_7, thread_id=t_31` |
|
||||
| --- | --- | --- |
|
||||
| Default chat | home channel `chat_id` | `default` |
|
||||
| A thread (inside default chat) | `thread_id` under the default `chat_id` | `chat_id=default, thread_id=t_12` |
|
||||
| A user-created channel | a new `chat_id` | `chan_7` |
|
||||
| A thread inside a channel | `thread_id` under that `chat_id` | `chat_id=chan_7, thread_id=t_31` |
|
||||
|
||||
- **`chat_id`** = the conversation lane (a channel or the default chat).
|
||||
- **`thread_id`** = an optional sub-lane within a `chat_id` (topic-like).
|
||||
@@ -23,10 +23,10 @@ gateway identity concepts**.
|
||||
## 6.2 Default chat
|
||||
|
||||
- On first connect, the plugin ensures a **default channel** exists:
|
||||
`chat_id = ANDROID_HOME_CHANNEL` (default `android:default`), `kind=default`,
|
||||
`chat_id = IRIS_HOME_CHANNEL` (default `default`), `kind=default`,
|
||||
`is_default=true`, name "Default".
|
||||
- It is also the **cron home channel** (`cron_deliver_env_var=
|
||||
ANDROID_HOME_CHANNEL`), so `deliver=android` (bare) routes here.
|
||||
IRIS_HOME_CHANNEL`), so `deliver=iris` (bare) routes here.
|
||||
- The app opens the default chat on launch.
|
||||
|
||||
## 6.3 Threads (toggle for overview)
|
||||
@@ -37,7 +37,7 @@ gateway identity concepts**.
|
||||
- **Threads OFF** — flat conversation; all messages use `thread_id=null`.
|
||||
- **Threads ON** — the app groups the conversation into topic-like lanes.
|
||||
Each new "topic" mints a `thread_id` (via `channel.create {kind:thread,
|
||||
parent_chat_id:android:default}` or an implicit thread). The UI shows a
|
||||
parent_chat_id:default}` or an implicit thread). The UI shows a
|
||||
topic switcher (like Telegram topics) above the message list.
|
||||
- Threads are **app-organized** but **gateway-real**: each `thread_id` is a
|
||||
distinct hermes session lane, so context is isolated per thread and cron can
|
||||
@@ -82,11 +82,13 @@ lane (nothing to title / session-scoped, not conversation starters).
|
||||
- **Requirement:** the user creates new channels so **cron job outputs can be
|
||||
delegated to them** instead of the default chat.
|
||||
- **`channel.create {name, kind:"channel"}`** → plugin mints
|
||||
`chat_id = android:chan_<n>`, stores in directory, broadcasts
|
||||
`chat_id = chan_<n>`, stores in directory, broadcasts
|
||||
`channel.created` to all devices. The new channel appears in the channel list.
|
||||
- **`channel.rename` / `channel.set_default` / `channel.delete`** manage the
|
||||
directory (rename broadcasts `channel.renamed`; delete is soft — marks
|
||||
archived, keeps history for search).
|
||||
directory (rename broadcasts `channel.renamed`; delete is a **hard delete**
|
||||
-- the channel/thread row is removed and the lane's history is wiped from
|
||||
the outbox and the hermes session store, so nothing is recoverable and no
|
||||
search trace survives).
|
||||
- **Automation channels:** a channel can be marked *automation*
|
||||
(`channel.set_automation {on}`, long-press / right-click menu; the default
|
||||
channel cannot be marked). Automation channels are **read-only for the
|
||||
@@ -102,9 +104,9 @@ lane (nothing to title / session-scoped, not conversation starters).
|
||||
- **Cron targeting** (the key payoff): because the plugin registers
|
||||
`parse_target_ref_fn` and `cron_deliver_env_var`, cron jobs and the
|
||||
`send_message` tool can target any channel/thread:
|
||||
- `deliver="android"` → home (default) channel.
|
||||
- `deliver="android:android:chan_7"` → that channel.
|
||||
- `deliver="android:android:chan_7:t_31"` → that channel's thread.
|
||||
- `deliver="iris"` → home (default) channel.
|
||||
- `deliver="iris:chan_7"` → that channel.
|
||||
- `deliver="iris:chan_7:t_31"` → that channel's thread.
|
||||
- In-chat: the agent's `cronjob` tool can be told "deliver to the *Cron
|
||||
Reports* channel"; the gateway resolves the name via the channel directory.
|
||||
- **In-app affordance:** each channel's menu has "Set as cron target" / shows a
|
||||
@@ -116,7 +118,7 @@ lane (nothing to title / session-scoped, not conversation starters).
|
||||
- Cron resolves delivery targets in `cron/scheduler.py:2148`
|
||||
(`_resolve_single_delivery_target`). For `platform:chat_id[:thread_id]` it
|
||||
calls `tools.send_message_tool.resolve_send_target`, which uses our
|
||||
`parse_target_ref_fn` to parse `android:<chat>[:<thread>]`.
|
||||
`parse_target_ref_fn` to parse `iris:<chat>[:<thread>]`.
|
||||
- Delivery then calls the **live adapter's `send(chat_id, text, …)`** (gateway
|
||||
running) → our WS `message` frame (or outbox+push if the app is offline).
|
||||
- Cron deliveries are framed with a `[Cron delivery: <name>]` header by hermes;
|
||||
@@ -148,4 +150,4 @@ lane (nothing to title / session-scoped, not conversation starters).
|
||||
|
||||
`hello.ack` and `channel.*` frames carry the directory. App keeps a local copy
|
||||
(Room) and reconciles on `channel.*` events (merge, don't clobber — see
|
||||
`10-android-app.md` state rules).
|
||||
`10-android-app.md` state rules).
|
||||
+80
-32
@@ -1,12 +1,15 @@
|
||||
# 07 — Media (upload, download, playback)
|
||||
|
||||
Media travels **over the WebSocket** as chunked binary frames (decision: no
|
||||
separate HTTP server; keeps the plugin to `websockets` only). Both directions
|
||||
use the same chunking.
|
||||
Media travels **over HTTP** (`POST /v1/media` for upload,
|
||||
`GET /v1/media/{id}` for pull; see `19-http-fallback-transport.md` §19.15).
|
||||
HTTP is the only transport — the WebSocket leg (chunked binary frames) was
|
||||
removed entirely. The contracts below (kinds, sha256, re-sniffing, delivery
|
||||
validation) apply to both directions.
|
||||
|
||||
## 7.1 Kinds & MIME
|
||||
|
||||
`kind` ∈ `image | audio | video | document | voice`.
|
||||
|
||||
- `image` — `image/*` (jpg/png/webp/gif/heic).
|
||||
- `audio` — `audio/*` (mp3/m4a/ogg/…) — music.
|
||||
- `video` — `video/*` (mp4/webm/mov).
|
||||
@@ -20,32 +23,38 @@ receipt (don't trust the client) using hermes helpers
|
||||
## 7.2 Inbound (app → agent) — `media.upload`
|
||||
|
||||
**Flow:**
|
||||
1. App picks a file (SAF) → reads size + MIME.
|
||||
2. App sends `media.upload.start {media_ref, kind, mime, size, filename}`.
|
||||
3. App streams the file as **binary WS frames** (e.g. 256 KiB chunks).
|
||||
4. App sends `media.upload.end {media_ref, sha256}`.
|
||||
5. Plugin verifies size ≤ `max_upload_bytes` and sha256, writes to the media
|
||||
|
||||
1. App picks a file (SAF) → reads size + MIME, computes sha256.
|
||||
2. App `POST /v1/media` with the raw file body; metadata in
|
||||
`X-Iris-Media-*` headers (`media_ref`, `kind`, `mime`, `filename`,
|
||||
`sha256`).
|
||||
3. Plugin verifies size ≤ `max_upload_bytes` and sha256, writes to the media
|
||||
cache via hermes `cache_*_from_bytes`:
|
||||
- image → `cache_image_from_bytes`
|
||||
- audio/voice → `cache_audio_from_bytes`
|
||||
- video → `cache_video_from_bytes`
|
||||
- document → `cache_document_from_bytes`
|
||||
→ returns a local path.
|
||||
5b. Plugin replies `media.upload.ack {ok, media_ref}` (failures use `error`).
|
||||
6. The path is attached to the next `message.send` via `media_refs`, becoming
|
||||
- document → `cache_document_from_bytes`
|
||||
→ returns a local path.
|
||||
4. Plugin replies `media.upload.ack {ok, media_ref}` (failures use `error`).
|
||||
5. The path is attached to the next `message.send` via `media_refs`, becoming
|
||||
`MessageEvent.media_urls` + `media_types`
|
||||
(`gateway/platforms/base.py:2337`). The agent's vision/audio tools can then
|
||||
read the file.
|
||||
|
||||
**Limits:** `get_inbound_media_max_bytes()` / `validate_inbound_media_size`
|
||||
(`base.py:758/779`) enforce the cap; over-limit → `error {code:"media_too_large"}`.
|
||||
**Limits:** two caps apply — the plugin's `max_upload_bytes` (default
|
||||
100 MiB) and hermes's `gateway.max_inbound_media_bytes` (default 128 MiB,
|
||||
enforced by `get_inbound_media_max_bytes()` / `validate_inbound_media_size`,
|
||||
`base.py:758/779`); over-limit → 413 + `error {code:"media_too_large"}`.
|
||||
Effective limit is the **min** of both; see §7.7. (The 1 MiB
|
||||
`MAX_BODY_BYTES` cap applies to JSON *frame* bodies only, not media uploads.)
|
||||
|
||||
**Backpressure:** large uploads use the WS flow control; the plugin reads
|
||||
binary frames into a temp file (not memory) to bound RAM.
|
||||
**Single-shot:** no chunking/resumability — HTTP carries the body; single-user
|
||||
scale makes a one-shot upload sufficient.
|
||||
|
||||
## 7.3 Outbound (agent → app) — `media.offer` / `media.pull`
|
||||
|
||||
**Flow:**
|
||||
|
||||
1. Agent produces/references media (e.g. generates an image, or replies with a
|
||||
`MEDIA:` tag / image URL). hermes base `extract_media` / `extract_images`
|
||||
(`base.py:4439/4884`) pull these out and call the adapter's
|
||||
@@ -54,14 +63,13 @@ binary frames into a temp file (not memory) to bound RAM.
|
||||
2. Adapter stages the file in the media cache, mints a `media_id`, and emits
|
||||
`media.offer {media_id, kind, mime, size, filename}` (inside/with the
|
||||
`message` frame's `media[]`).
|
||||
3. App sends `media.pull {media_id}`.
|
||||
4. Plugin streams the file as **binary WS frames**; ends with
|
||||
`media.pull.end {ok:true}`.
|
||||
5. App writes to its cache dir and hands the path to the player/viewer.
|
||||
3. App `GET /v1/media/{id}` — the full file body.
|
||||
4. App writes to its cache dir and hands the path to the player/viewer.
|
||||
|
||||
**Security:** `validate_media_delivery_path` (`base.py:1684`) + the media
|
||||
delivery root/recency/denied-path checks (`base.py:1312-1480`) ensure the plugin
|
||||
only serves files hermes is allowed to deliver (no arbitrary file read).
|
||||
only serves files hermes is allowed to deliver (no arbitrary file read). The
|
||||
delivery-path check is re-run **at pull time**, not just at offer time.
|
||||
|
||||
## 7.4 Live playback (AI-sent music/video)
|
||||
|
||||
@@ -79,19 +87,59 @@ only serves files hermes is allowed to deliver (no arbitrary file read).
|
||||
a desktop backend (see `11-desktop-app.md`): a `libmpv`/`mpv`-backed surface
|
||||
or a WebView fallback for video, and a desktop audio player for music.
|
||||
|
||||
## 7.5 Chunking parameters
|
||||
## 7.5 Integrity
|
||||
|
||||
- Chunk size: **256 KiB** (tunable).
|
||||
- Binary frames carry raw bytes only; framing/metadata is in the JSON header +
|
||||
end frames.
|
||||
- Reassembly is ordered (WS preserves order); a gap/corruption → abort +
|
||||
`error {code:"internal"}` + retry the whole transfer.
|
||||
- `sha256` in `media.upload.end` / a size check on pull verify integrity.
|
||||
- Upload: `sha256` (precomputed by the app, sent in `X-Iris-Media-Sha256`)
|
||||
is verified by the plugin; mismatch → `media.upload.ack {ok:false}`.
|
||||
- Pull: the app checks the received size against the offered `size`.
|
||||
- A failed transfer → retry the whole upload (single-shot, no resume).
|
||||
|
||||
## 7.6 App-side storage
|
||||
|
||||
- Cache dir: app-specific external cache (`getExternalCacheDir()/media`).
|
||||
- LRU eviction by size (configurable, default 500 MB) so old media doesn't fill
|
||||
the device.
|
||||
- Cache dir: app-specific external cache (`getExternalCacheDir()/media`,
|
||||
internal `cacheDir` fallback; desktop: `~/.iris/cache/media`).
|
||||
- LRU eviction by size (hardcoded 500 MB, `MediaCacheJvm.kt` `maxBytes`) so old
|
||||
media doesn't fill the device.
|
||||
- A `MediaRepository` tracks `{media_id, local_path, kind, size, ts}` in Room so
|
||||
bubbles can re-render players after process death.
|
||||
bubbles can re-render players after process death.
|
||||
|
||||
## 7.7 Size limits & where files live
|
||||
|
||||
**Inbound (app → agent) — two caps, effective limit is the min:**
|
||||
|
||||
| Cap | Default | Set via | Enforced by |
|
||||
| --- | --- | --- | --- |
|
||||
| Plugin `max_upload_bytes` | 100 MiB | `gateway.platforms.iris.extra.max_upload_bytes` (config.yaml) | `http_server.py` (Content-Length pre-check) + `media.py` `UploadSession.feed` (mid-stream) → `media_too_large` |
|
||||
| Hermes `gateway.max_inbound_media_bytes` | 128 MiB | `gateway.max_inbound_media_bytes` (config.yaml) | `validate_inbound_media_size` inside `cache_*_from_bytes` (`base.py:758/779`) → `media_too_large` |
|
||||
|
||||
Both are **pure config** — raising the limit needs no code change in the plugin
|
||||
or hermes-agent. The app itself has no upload cap.
|
||||
|
||||
**Why the caps exist:** the upload is streamed to a temp file (disk, bounded
|
||||
RAM in flight), but at completion the plugin reads the **entire blob into
|
||||
memory** (`UploadSession.read_bytes()` → `cache_*_from_bytes` →
|
||||
`write_bytes`), so peak RAM ≈ file size per upload. Hermes's cap exists to
|
||||
prevent OOM-killing the gateway (comment at `base.py:740-749`).
|
||||
|
||||
**Inbound storage (gateway host):**
|
||||
|
||||
- In flight: temp file `upl_*` under `~/.hermes/iris/media/tmp` (removed after
|
||||
completion or failure).
|
||||
- After caching: hermes media cache — `~/.hermes/cache/images/img_<uuid12><ext>`,
|
||||
`cache/audio/audio_<uuid12><ext>`, `cache/videos/video_<uuid12><ext>`,
|
||||
`cache/documents/doc_<uuid12>_<original filename>`. Video/image/audio lose
|
||||
their original filename; documents keep it.
|
||||
- Lifetime: hermes `cleanup_video_cache(max_age_hours=24)` deletes videos older
|
||||
than 24 h.
|
||||
|
||||
**Outbound (agent → app) — no size cap at the gateway.** `media.offer` carries
|
||||
metadata; `GET /v1/media/{id}` streams the full file in 256 KiB chunks
|
||||
regardless of size. The only constraints are the delivery-path re-validation at
|
||||
pull time and the 24 h offer TTL (`MediaStore.prune_outbound`).
|
||||
|
||||
**The effective outbound limit is set by the app:** the device media cache is
|
||||
LRU-capped at 500 MB (§7.6) and `evict()` runs right after each pull completes.
|
||||
A single file > 500 MB makes the eviction loop delete everything — *including
|
||||
the file it just downloaded*. So files > ~500 MB arrive but are immediately
|
||||
discarded. To retain large agent→app files, raise `maxBytes` in
|
||||
`MediaCacheJvm.kt` (or exempt files from eviction).
|
||||
+49
-10
@@ -1,17 +1,54 @@
|
||||
# 08 — Push Notifications, Outbox & Sync
|
||||
|
||||
The gateway can't reach a sleeping phone directly. Push goes through a cloud
|
||||
relay. **Decision: FCM primary, ntfy fallback** (`ANDROID_PUSH_BACKEND`).
|
||||
relay. **Decision: ntfy default, FCM optional** (`IRIS_PUSH_BACKEND`).
|
||||
Privacy: FCM push metadata (notification title, device token) is routed
|
||||
through Google's servers. ntfy is the private option — **but note the default
|
||||
`NTFY_SERVER_URL` is the public `https://ntfy.sh` cloud service**, so push
|
||||
metadata passes through ntfy.sh's servers unless you self-host ntfy (set
|
||||
`NTFY_SERVER_URL`); only a self-hosted ntfy keeps everything on your own
|
||||
infrastructure.
|
||||
|
||||
## 8.1 When push fires
|
||||
|
||||
- A frame targets a `chat_id` whose device is **disconnected** (WS closed) →
|
||||
drop to **outbox** + fire **push**.
|
||||
- A frame targets a `chat_id` whose device is **disconnected** (no live
|
||||
SSE/long-poll subscriber) → drop to **outbox** + fire **push** — with one
|
||||
refinement, *turn-aware push* (below).
|
||||
- Also fire push for high-priority foreground events the user should see even if
|
||||
the app is backgrounded (approvals, clarifies, cron completions) — the app
|
||||
decides whether to also show an in-app banner.
|
||||
- If the device is **connected**, no push (the live frame is enough).
|
||||
|
||||
### 8.1.1 Turn-aware push (one push per turn, final answer as body)
|
||||
|
||||
An agent turn can span minutes and emit several completed status messages
|
||||
("researching X…", "found Y…", "writing findings…", final answer). Pushing each
|
||||
parked message would spam an offline user with the steps in between. So while
|
||||
the agent's turn is **in flight** (hermes holds the typing indicator on from
|
||||
turn start until the handler's `finally` at turn end), normal-priority
|
||||
`message` / `message.stop` / `media.offer` frames that park with no live
|
||||
device are **held back** per chat instead of pushing; the latest one is pushed
|
||||
when the turn ends (`stop_typing`), so the offline user gets **one push with
|
||||
the final answer**. Details:
|
||||
|
||||
- Turn state is tracked per `chat_id` from the typing indicator
|
||||
(`send_typing` → in flight, `stop_typing` → ended; hermes fires
|
||||
`stop_typing` in the handler's `finally`, after the final send, so the
|
||||
flush always sees the final frame).
|
||||
- The held-back frame is still parked in the outbox — sync catch-up is
|
||||
unaffected; only the push is deferred.
|
||||
- **High-priority notifications** (approval/clarify/cron) push immediately,
|
||||
even mid-turn — they need user action.
|
||||
- If the device **reconnects mid-turn** (SSE/long-poll open), the held-back
|
||||
push is dropped: the app syncs the parked frames and must not get a
|
||||
duplicate push at turn end.
|
||||
- If the turn ends while the device is live, nothing is pushed (the frames
|
||||
were delivered live / synced).
|
||||
- Turns without a typing indicator (e.g. typing disabled in config) and
|
||||
non-turn deliveries (cron, standalone sends) push immediately as before.
|
||||
- Best-effort: a gateway crash mid-turn loses the held-back push (the frames
|
||||
remain in the outbox and sync on reconnect).
|
||||
|
||||
## 8.2 `PushBackend` interface (`push.py`)
|
||||
|
||||
```python
|
||||
@@ -23,13 +60,14 @@ class PushBackend(Protocol):
|
||||
def configured(self) -> bool: ...
|
||||
```
|
||||
|
||||
Selected at adapter init by `ANDROID_PUSH_BACKEND` (`fcm` default, `ntfy`).
|
||||
Selected at adapter init by `IRIS_PUSH_BACKEND` (`ntfy` default, `fcm`).
|
||||
|
||||
### 8.2.1 `FcmBackend` (optional; metadata via Google)
|
||||
|
||||
### 8.2.1 `FcmBackend` (primary)
|
||||
- **FCM HTTP v1 API** via `httpx` (core dep). Auth = Firebase **service
|
||||
account** (`ANDROID_FCM_SERVICE_ACCOUNT` JSON path) → mint a short-lived
|
||||
OAuth2 access token (cached, refreshed before expiry).
|
||||
- Fallback: legacy **server key** (`ANDROID_FCM_SERVER_KEY`) if no service
|
||||
account** (`IRIS_FCM_SERVICE_ACCOUNT` JSON path) → mint a short-lived
|
||||
OAuth2 access token (cached, refreshed before expiry).
|
||||
- Fallback: legacy **server key** (`IRIS_FCM_SERVER_KEY`) if no service
|
||||
account (simpler, but legacy).
|
||||
- Target = the device's **FCM token** (registered via `hello` /
|
||||
`fcm.register`, stored in `devices.db`).
|
||||
@@ -42,7 +80,8 @@ Selected at adapter init by `ANDROID_PUSH_BACKEND` (`fcm` default, `ntfy`).
|
||||
- Batch: FCM allows up to 500 tokens/message; we send per-device (1 user, few
|
||||
devices).
|
||||
|
||||
### 8.2.2 `NtfyBackend` (fallback, self-host friendly)
|
||||
### 8.2.2 `NtfyBackend` (default, self-host friendly)
|
||||
|
||||
- Reuses hermes's existing ntfy publish path (hermes ships an ntfy adapter).
|
||||
- Publish to `NTFY_TOPIC` on `NTFY_SERVER_URL` (default `https://ntfy.sh`) via
|
||||
`httpx` POST, with an `X-Title` / `X-Message` / `X-Tag` / `X-Priority` and a
|
||||
@@ -132,4 +171,4 @@ device push watermark:
|
||||
Residual edge: FCM is at-least-once, so a lost device ack can still produce a
|
||||
duplicate *system-displayed* notification (two `FCM-Notification:*` ids). The
|
||||
designed evolution is the data-only push option (§8.2.1), which moves display
|
||||
into the app and lets it use a stable per-message notification id.
|
||||
into the app and lets it use a stable per-message notification id.
|
||||
+89
-33
@@ -13,21 +13,24 @@
|
||||
## 9.2 Pairing flow
|
||||
|
||||
1. **Generate a token.** `hermes gateway setup` (our `interactive_setup`) either
|
||||
uses an existing `ANDROID_TOKEN` or generates a fresh high-entropy token
|
||||
uses an existing `IRIS_TOKEN` or generates a fresh high-entropy token
|
||||
(e.g. 32 bytes → 64 hex chars) and stores it in `.env`.
|
||||
2. **Present to the app.** Two options:
|
||||
- **QR code:** the setup prints a QR encoding
|
||||
`iris://pair?host=<lan-ip>&port=8790&token=<token>` (or a WSS URL). The
|
||||
phone scans it with the app's camera (or a system scanner) → pre-fills
|
||||
`iris://pair?host=<lan-ip>&port=8791&secure=0&token=<token>` (or a WSS
|
||||
URL when `secure=1`). The phone scans it with the app's **Scan QR**
|
||||
button (or a system scanner → `iris://pair` deep link) → pre-fills
|
||||
settings.
|
||||
- **Manual:** user types the server URL + token in the app's Connect screen.
|
||||
3. **App connects.** First WS frame is `hello {token, device_id, device_name,
|
||||
caps, fcm_token?}`.
|
||||
4. **Server verifies.** Constant-time compare of `token` vs `ANDROID_TOKEN`
|
||||
4. **Server verifies.** Constant-time compare of `token` vs `IRIS_TOKEN`
|
||||
(`hmac.compare_digest`). Optionally check `device_id` against
|
||||
`ANDROID_ALLOWED_USERS` (if set) or `ANDROID_ALLOW_ALL_USERS`.
|
||||
5. **On success:** register the device in `devices.db`, send `hello.ack`.
|
||||
**On failure:** send `error {code:"auth"}` and close.
|
||||
`IRIS_ALLOWED_USERS` (if set) or `IRIS_ALLOW_ALL_USERS`.
|
||||
5. **On success:** register the device in `devices.db`, **mint its
|
||||
per-device token** (if it has none yet) and return it in
|
||||
`hello.ack.device_token`. **On failure:** send `error {code:"auth"}`
|
||||
and close.
|
||||
|
||||
`device_id` is a stable, app-generated UUID (persisted in the app's
|
||||
secure storage). It identifies the device for routing + push, **not** as a
|
||||
@@ -35,37 +38,89 @@ security principal (the token is).
|
||||
|
||||
## 9.3 Auth model
|
||||
|
||||
- **Token = the security principal.** Any connection presenting the valid
|
||||
`ANDROID_TOKEN` is authorized (it's the user's own token).
|
||||
- **Allowlist (optional):** `ANDROID_ALLOWED_USERS` (comma-separated
|
||||
`device_id`s) restricts which *devices* may connect even with the token —
|
||||
useful if the token is shared. `ANDROID_ALLOW_ALL_USERS=true` disables the
|
||||
allowlist (dev only).
|
||||
- **Per-device tokens (stretch):** mint a unique token per device at pairing
|
||||
(revocable) instead of one shared token. v1 uses the shared token + optional
|
||||
device allowlist.
|
||||
- **Re-pairing:** rotating `ANDROID_TOKEN` invalidates all devices; they must
|
||||
re-pair. `hermes android pair` (stretch CLI) re-issues + prints a new QR.
|
||||
- **Two tokens, one principal per device.**
|
||||
- **Shared `IRIS_TOKEN` (bootstrap):** the setup token from
|
||||
`hermes gateway setup`. It authorizes *pairing* — a NEW device (no row
|
||||
in `devices.db` yet) presents it to connect, and the gateway mints a
|
||||
per-device token for it (returned in `hello.ack.device_token`). It
|
||||
keeps working for devices that never received a per-device token
|
||||
(legacy apps), so an upgrade never bricks a pairing.
|
||||
- **Per-device token (revocable):** minted once at pairing
|
||||
(`DeviceRegistry.issue_token`, 64 hex chars, stored in the `devices`
|
||||
table of `devices.db`). The app stores it in secure storage and
|
||||
presents it INSTEAD of the shared token from the next request on
|
||||
(`Authorization: Bearer <device-token>`). Both tokens are compared in
|
||||
constant time (`verify_token`); a revoked device is rejected before
|
||||
either comparison runs.
|
||||
- **Per-device revocation.** Two control surfaces (run on the gateway host):
|
||||
- **Setup flow** — `hermes gateway setup` → *Iris*: on an existing setup
|
||||
(devices already paired) it asks **"Remove a paired device?"** (default
|
||||
No). If yes: a numbered select menu (name, device id, last seen) whose
|
||||
LAST option is *Exit* (leaves the removal loop, continues the setup);
|
||||
picking a device asks for confirmation, then returns to the menu so
|
||||
several devices can be removed in a row.
|
||||
- **CLI** — `gateway-plugin/tools/iris_devices.py`:
|
||||
- `list` — paired devices (id, name, token minted?, last seen) + revoked ids.
|
||||
- `revoke <device_id>` — drops the device's row (token, push tokens,
|
||||
cursor) AND adds its id to the `revoked` denylist: the device can no
|
||||
longer connect with its device token **or** the shared token, while
|
||||
every other device is unaffected. This is the isolation primitive a
|
||||
shared token alone can't provide (a compromised device can't be cut
|
||||
off without rotating the token for everyone).
|
||||
- `unrevoke <device_id>` — removes it from the denylist so it can pair
|
||||
again (a fresh token is minted at the next pairing).
|
||||
- `reissue <device_id>` — rotates the device's token (the old one stops
|
||||
working; the app picks up the new one on its next (re)connect via
|
||||
`hello.ack`).
|
||||
Re-pairing a revoked device also works by giving the app a fresh
|
||||
`device_id` (e.g. `adb shell pm clear dev.iris.app`), which bootstraps
|
||||
with the shared token like any new device.
|
||||
- **Allowlist (optional):** `IRIS_ALLOWED_USERS` (comma-separated
|
||||
`device_id`s) restricts which *devices* may connect even with a valid
|
||||
token — useful if the shared token is exposed. `IRIS_ALLOW_ALL_USERS=true`
|
||||
disables the allowlist (dev only).
|
||||
- **Re-pairing / rotation.** Rotating `IRIS_TOKEN` no longer invalidates
|
||||
paired devices: they authenticate with their per-device tokens, which
|
||||
survive the rotation. Only bootstrap of NEW devices needs the new shared
|
||||
token. (Legacy devices without a per-device token still re-pair, as
|
||||
before.)
|
||||
|
||||
## 9.4 Transport security
|
||||
|
||||
- **Default (LAN/dev):** plain `ws://` on the trusted LAN. Fine for a home
|
||||
- **Default (LAN/dev):** plain `http://` on the trusted LAN. Fine for a home
|
||||
network.
|
||||
- **WSS (recommended for remote):** set `ANDROID_WS_CERT` / `ANDROID_WS_KEY`
|
||||
(self-signed or CA-signed). The app pins/accepts the cert (self-signed → user
|
||||
confirms fingerprint on first pair, like a SSH host key).
|
||||
- **HTTPS (recommended for remote):** set `IRIS_HTTP_CERT` / `IRIS_HTTP_KEY`
|
||||
(self-signed or CA-signed). CA-signed certs work out of the box.
|
||||
For a **self-signed** cert the app shows its SHA-256 fingerprint on first
|
||||
pair (like a SSH host key); once the user confirms it, the fingerprint is
|
||||
pinned in secure storage (`SecureStore.pinnedCertFingerprint`) and the
|
||||
app's `PinningTrustManager` accepts exactly that certificate from then on
|
||||
(hostname verification still applies). A *changed* certificate fails
|
||||
again with a fresh confirm request — the user must re-confirm, like a
|
||||
changed SSH host key. No system trust-store install needed. Note: the cert
|
||||
must carry a **SAN** for the URL host (OkHttp's hostname verifier rejects
|
||||
CN-only certs even when pinned) — e.g. `openssl req -x509 ... -addext
|
||||
"subjectAltName=DNS:myhost,IP:192.168.1.10"`.
|
||||
- **Remote reachability options** (documented, user's choice):
|
||||
- **Tailscale / WireGuard** (recommended): gateway gets a stable tailnet IP;
|
||||
app connects over the private mesh. No public exposure.
|
||||
- **Reverse proxy / tunnel** (Caddy, Cloudflare Tunnel, ngrok): terminate TLS
|
||||
at the edge, forward WS to `127.0.0.1:8790`.
|
||||
- **Public bind** (`0.0.0.0`) + WSS + strong token — last resort.
|
||||
at the edge, forward to `127.0.0.1:8791`.
|
||||
- **Public bind** (`0.0.0.0`) + HTTPS + strong token — last resort.
|
||||
- **HTTP transport (docs/19):** the gateway serves the same frames over plain
|
||||
HTTP (`IRIS_HTTP_PORT`, default 8791) — the only device-facing transport.
|
||||
It shares the same lock as everything else: the same Bearer token
|
||||
(constant-time `verify_token`) + the same device allowlist
|
||||
(`X-Iris-Device`), the same 64 KiB body cap and per-device rate limit.
|
||||
Optional TLS via `IRIS_HTTP_CERT` / `IRIS_HTTP_KEY`.
|
||||
`GET /v1/health` is unauthenticated by design (liveness only — it must
|
||||
not reflect tokens, device ids, or versions).
|
||||
- The app stores the server URL + (for self-signed) the pinned cert fingerprint
|
||||
in secure storage.
|
||||
|
||||
## 9.5 Secret & PII handling
|
||||
|
||||
- **Tokens/keys never logged.** Redact `ANDROID_TOKEN`, FCM tokens/keys, ntfy
|
||||
- **Tokens/keys never logged.** Redact `IRIS_TOKEN`, FCM tokens/keys, ntfy
|
||||
tokens in all log output (hermes PII policy; `agent/redact.py` patterns).
|
||||
- **`device_id`** is a random UUID (not PII). `device_name` is user-chosen.
|
||||
- **Media pull** is gated by hermes `validate_media_delivery_path` + delivery
|
||||
@@ -76,7 +131,7 @@ security principal (the token is).
|
||||
|
||||
## 9.6 Profile safety
|
||||
|
||||
- All plugin state lives under `get_hermes_home()/"android"` (profile-aware).
|
||||
- All plugin state lives under `get_hermes_home()/"iris"` (profile-aware).
|
||||
- Secrets are read with the scope-aware `_get_scoped_secret` pattern (see
|
||||
`plugins/platforms/irc/adapter.py:42`) so multiplexed profiles don't leak
|
||||
each other's tokens (fail-closed under `gateway.multiplex_profiles`).
|
||||
@@ -102,16 +157,17 @@ M7 research pass. "verified" = implemented and covered by
|
||||
"gap" = known limitation with the planned mitigation.
|
||||
|
||||
| # | Item | Status | Evidence / mitigation |
|
||||
|---|------|--------|-----------------------|
|
||||
| --- | ------ | -------- | ----------------------- |
|
||||
| 1 | Constant-time token compare | verified | `gateway-plugin/pairing.py:34` (`hmac.compare_digest`); `test_wrong_token_rejected` |
|
||||
| 2 | Bounded per-connection send buffer + rate limit on inbound frames | verified | Send: `SEND_TIMEOUT_S` bounds every outbound send (`ws_server.py:47`, `broadcast`/`send_to`). Inbound: per-connection token bucket on JSON frames (20/s, burst 40) → `error {code:"rate_limited"}` + close on exceed (`ws_server.py:55`, `_TokenBucket`, `_on_frame`); binary upload chunks exempt (see gap 1) |
|
||||
| 3 | Reject oversized frames / uploads (`max_upload_bytes`) | verified | `serve(max_size=adapter.max_upload_bytes)` (`ws_server.py:139`); per-upload total cap in `media.py` (`create_upload`/`feed`); `test_upload_declared_over_limit_rejected`, `test_upload_midstream_over_limit_rejected` |
|
||||
| 2 | Bounded per-connection send buffer + rate limit on inbound frames | verified | Send: `SEND_TIMEOUT_S` bounds every outbound send (`http_server.py`, `broadcast`/`send_to`). Inbound: per-device token bucket on JSON frames (20/s, burst 40) → `429` on exceed (`http_server.py`, `_rate_limited`); media uploads bounded by the per-request body cap + per-upload total cap (see gap 1) |
|
||||
| 3 | Reject oversized frames / uploads (`max_upload_bytes`) | verified | Per-request body cap in `http_server.py`; per-upload total cap in `media.py` (`create_upload`/`feed`); `test_upload_declared_over_limit_rejected`, `test_upload_midstream_over_limit_rejected` |
|
||||
| 4 | Verify media sha256 + re-sniff MIME (don't trust client) | verified | `media.py:317` (`complete_upload` digest check), `media.py:147` (`reclassify_kind`); `test_upload_sha256_mismatch_rejected`, `test_reclassify_kind_does_not_trust_client` |
|
||||
| 5 | Redact all secrets in logs | gap | No mechanical redaction; the token is printed to stdout by design during `hermes gateway setup` (`gateway-plugin/adapter.py:632,650`). Mitigation: stdout is operator-only, not a log file; a redaction pass over gateway logs is planned |
|
||||
| 6 | WSS + cert pinning for remote | gap (partial) | WSS supported server-side (`ANDROID_WS_CERT`/`ANDROID_WS_KEY`, `ws_server.py:122`); the app builds a default `OkHttpClient` with no `CertificatePinner` (`app/shared/src/commonMain/kotlin/iris/net/GatewayClient.kt:87`). Mitigation: remote access requires CA-signed WSS until pinning lands; LAN `ws://` stays the default |
|
||||
| 6 | HTTPS + cert pinning for remote | implemented | TLS supported server-side (`IRIS_HTTP_CERT`/`IRIS_HTTP_KEY`, `http_server.py`); the app pins self-signed certs via a fingerprint-confirm flow: `PinningTrustManager` wraps the platform default trust manager, a rejected cert is accepted only when its SHA-256 fingerprint matches the user-confirmed pin in `SecureStore.pinnedCertFingerprint`, anything else fails with `TlsFingerprintRequired` → confirm dialog on the Connect screen (`app/shared/src/commonMain/kotlin/iris/net/TlsPinning.kt`, `GatewayClient.State.TlsConfirmRequired`); hostname verification still applies (the cert needs a SAN for the URL host). CA-signed certs work out of the box; LAN `http://` stays the default. Tests: `TlsPinningTest`, `TlsPinningIntegrationTest` |
|
||||
| 7 | Outbox retention cap + prune | verified | `gateway-plugin/outbox.py:48` (`retention_hours` default 72h, `max_rows` cap, `take_overflow_pruned`); `test_outbox_row_cap_prunes_oldest` |
|
||||
| 8 | Fail-closed secret reads under multiplexing | verified | `_get_scoped_secret` (`gateway-plugin/adapter.py:74`) for `ANDROID_TOKEN`/`ANDROID_WS_CERT`/`ANDROID_WS_KEY`/FCM/ntfy secrets; scoped bind lock in `connect()` (`adapter.py:779`) |
|
||||
| 9 | Gap: inbound frame rate limiting | implemented | Closes item 2: token bucket in `ws_server.py` (JSON frames only). Binary upload chunks are exempt — a 100 MB upload is 400 × 256 KiB frames in a tight loop and would exhaust any sane bucket; uploads are already bounded by per-frame `max_size` + the per-upload total cap |
|
||||
| 8 | Fail-closed secret reads under multiplexing | verified | `_get_scoped_secret` (`gateway-plugin/adapter.py:74`) for `IRIS_TOKEN`/`IRIS_HTTP_CERT`/`IRIS_HTTP_KEY`/FCM/ntfy secrets; scoped bind lock in `connect()` (`adapter.py:779`) |
|
||||
| 9 | Gap: inbound frame rate limiting | implemented | Closes item 2: per-device token bucket in `http_server.py` (`_rate_limited`). Media uploads are bounded by the per-request body cap + the per-upload total cap |
|
||||
| 10 | Gap: Android token storage | implemented | `AndroidSecureStore` → `EncryptedSharedPreferences` (MasterKey AES256_GCM) with one-time migration of the plain `iris` prefs (read old key → write encrypted → delete old key); dep in `app/shared/build.gradle.kts` (`app/shared/src/androidMain/kotlin/iris/platform/AndroidSecureStore.kt`) |
|
||||
| 11 | Gap: guard not committed | implemented | `.pre-commit-config.yaml` (local hook → `scripts/guard_hermes_agent.sh --staged`); a fresh clone gets the guard after `pre-commit install` |
|
||||
| 12 | Gap: in-app QR scanner | gap | Pairing is manual URL+token only; the server prints a QR (`gateway-plugin/adapter.py:648-654`) that any system scanner can read. Plan: in-app camera scan later |
|
||||
| 12 | Gap: in-app QR scanner | implemented | `hermes gateway setup` renders a terminal QR (`gateway-plugin/qr.py`, pure-stdlib encoder) and the app's Connect screen has a **Scan QR** button (CameraX + ML Kit, `QrScanActivity`) plus an `iris://pair` deep link (`PairLink.parse`); `docs/20` |
|
||||
| 13 | Gap: per-device tokens (revocation) | implemented | `DeviceRegistry.issue_token` mints a 64-hex per-device token at pairing (stored in `devices.db`, returned in `hello.ack.device_token`); the app stores it in secure storage and presents it instead of the shared `IRIS_TOKEN` (bootstrap path unchanged). `tools/iris_devices.py revoke <device_id>` drops the device + denylists its id (rejected even with the shared token); `unrevoke`/`reissue` for re-pairing/rotation. `docs/09` §9.3 |
|
||||
+101
-20
@@ -1,4 +1,4 @@
|
||||
# 10 — Android App (Kotlin + Jetpack Compose)
|
||||
# 10 — Iris App (Android; Kotlin + Jetpack Compose)
|
||||
|
||||
Native client. Lives in the Compose Multiplatform project at `app/`; the bulk of
|
||||
the code is in `app/shared` (commonMain) so the Desktop app reuses it.
|
||||
@@ -6,13 +6,13 @@ the code is in `app/shared` (commonMain) so the Desktop app reuses it.
|
||||
## 10.1 Tech stack
|
||||
|
||||
| Concern | Choice |
|
||||
|---|---|
|
||||
| --- | --- |
|
||||
| Language | Kotlin |
|
||||
| UI | Jetpack Compose (Material 3), Compose Navigation |
|
||||
| Async | Kotlinx Coroutines + Flow |
|
||||
| WS client | OkHttp (`WebSocketListener`) |
|
||||
| JSON | kotlinx-serialization |
|
||||
| Local DB | **SQLDelight** (KMP; channels, messages cache, media index, sync cursor, settings) |
|
||||
| Local DB | **SQLDelight** (KMP; local cache: messages per lane, channel directory, meta — see 10.7/10.9. Sync cursor + settings live in `SecureStore`, media files in `MediaCache`) |
|
||||
| Media playback | Media3 **ExoPlayer** (audio + video) |
|
||||
| Push | Firebase Messaging (FCM) [primary] / ntfy listener [fallback] |
|
||||
| DI | Hilt |
|
||||
@@ -74,6 +74,7 @@ app/shared/src/
|
||||
## 10.5 Feature implementation (your checklist)
|
||||
|
||||
### Input box, auto-grow (max height)
|
||||
|
||||
- Compose `BasicTextField` inside a `Box` with
|
||||
`Modifier.heightIn(min = 1.line, max = 160.dp)`. Grows with lines, caps at
|
||||
160dp, then scrolls internally.
|
||||
@@ -82,6 +83,7 @@ app/shared/src/
|
||||
(configurable: Enter=send vs Enter=newline).
|
||||
|
||||
### Slash commands
|
||||
|
||||
- **`/` drawer (implemented):** typing `/` in the composer rolls a drawer up
|
||||
over the input listing the command catalog. The catalog is served by the
|
||||
gateway via `commands.catalog` request → response with
|
||||
@@ -102,6 +104,7 @@ app/shared/src/
|
||||
sheet with the options; answer via `picker.select`) — planned.
|
||||
|
||||
### Streaming (app-controlled)
|
||||
|
||||
- **Settings → "Streaming"** toggle (default on). When off, the app ignores
|
||||
`message.start`/`message.update` frames and shows each reply as a single
|
||||
final message on `message.stop` (the typing indicator covers the wait).
|
||||
@@ -109,9 +112,10 @@ app/shared/src/
|
||||
devices (see `05-streaming.md` §5.1).
|
||||
|
||||
### Tool output (app-controlled verbosity)
|
||||
|
||||
- `ToolCard` renders `tool.start/progress/end` frames.
|
||||
- The gateway always supplies the **full** tool data: it forces
|
||||
`display.platforms.android.tool_progress: verbose` (so the progress line
|
||||
`display.platforms.iris.tool_progress: verbose` (so the progress line
|
||||
carries the full args JSON → `tool.start.args`) and captures each completed
|
||||
call via the `post_tool_call` hook (→ `tool.end` `output_preview` /
|
||||
`duration` / `ok`). The app decides how much to show.
|
||||
@@ -123,6 +127,7 @@ app/shared/src/
|
||||
- Spinner while running; ✓/✗ + duration on `tool.end`.
|
||||
|
||||
### Reasoning before message
|
||||
|
||||
- `ReasoningBlock` (collapsible, "💭 Reasoning" header, monospace body, **copy**
|
||||
button) rendered **above** the message body from the `reasoning` field.
|
||||
Matches the reference screenshot.
|
||||
@@ -132,9 +137,11 @@ app/shared/src/
|
||||
tap-to-toggle always works.
|
||||
|
||||
### Intermediate messages
|
||||
|
||||
- `commentary` frames → dimmed/smaller bubble, distinct from final answers.
|
||||
|
||||
### Message selection + delete
|
||||
|
||||
- **Long-press** a message bubble (touch) or **right-click** it (desktop mouse)
|
||||
enters selection mode: the tapped message is selected (a circular check appears
|
||||
beside each bubble) and the composer is replaced by a selection toolbar
|
||||
@@ -143,12 +150,15 @@ app/shared/src/
|
||||
message) exits selection mode. Only finalized messages are selectable — a
|
||||
streaming bubble has no final id yet and a pending echo isn't on the server.
|
||||
- **Delete** → confirm dialog → `message.delete {message_ids:[…]}` for the
|
||||
current lane. The server removes the message(s) from the outbox (so
|
||||
`history`/`sync` no longer return them) and broadcasts `message.deleted` to
|
||||
every device; each device drops them from its cache (the requesting device
|
||||
also drops them locally for snappy UX). Deleting is idempotent.
|
||||
current lane. The server completely deletes the message(s): they are removed
|
||||
from the outbox (so `history`/`sync` no longer return them) **and** from the
|
||||
hermes session store (so no search trace survives and they are not
|
||||
recoverable), and `message.deleted` is broadcast to every device; each device
|
||||
drops them from its cache (the requesting device also drops them locally for
|
||||
snappy UX). Deleting is idempotent.
|
||||
|
||||
### Agent busy / stop / steer
|
||||
|
||||
- `agent.busy` → show "thinking…" indicator in chat header (animated dots).
|
||||
- `agent.idle` → clear indicator.
|
||||
- **Stop button** (appears in header while busy): sends `agent.stop`.
|
||||
@@ -156,8 +166,9 @@ app/shared/src/
|
||||
`agent.steer` (injects mid-turn) rather than queuing a new `message.send`.
|
||||
|
||||
### Threading + channels
|
||||
|
||||
- **Channel list** (drawer on single-pane; left rail on two-pane) = default chat
|
||||
+ user channels (avatar, name, last-message preview, unread badge, active
|
||||
- user channels (avatar, name, last-message preview, unread badge, active
|
||||
highlight bar) — matches the reference left sidebar.
|
||||
- **Thread toggle** in the default chat header: "Threads on/off". On → topic
|
||||
switcher above the message list (each topic = a `thread_id`).
|
||||
@@ -171,23 +182,27 @@ app/shared/src/
|
||||
menu offers "Set as cron target".
|
||||
- **Topic context menu** — long-press a topic chip (touch) or right-click it
|
||||
(desktop mouse) → "Rename" / "Delete". Rename → `channel.rename` (prefilled
|
||||
dialog); Delete → confirm → `channel.delete` (soft-delete; the thread leaves
|
||||
the switcher and, if it was the open lane, the app falls back to the channel's
|
||||
flat lane). The right-click handler is a skiko `expect`/`actual`
|
||||
dialog); Delete → confirm → `channel.delete` (hard delete; the thread leaves
|
||||
the switcher, its history is wiped from the outbox and session store, and if
|
||||
it was the open lane the app falls back to the channel's flat lane). The
|
||||
right-click handler is a skiko `expect`/`actual`
|
||||
(`iris/ui/ContextMenu.kt`); on touch it is a no-op (long-press covers it).
|
||||
|
||||
### Search
|
||||
|
||||
- Search bar (chat header or top) with a **scope toggle**: "Search everywhere" /
|
||||
"Search in this chat/channel". → `search` frame → results list → tap jumps to
|
||||
the message (navigate + highlight).
|
||||
|
||||
### Attach media
|
||||
|
||||
- Paperclip → system pickers (Photos / Files / Audio / Video / Docs) via SAF.
|
||||
- Selected files show as **preview chips** in the composer (thumbnail + name +
|
||||
remove). On send: `media.upload` (chunked) for each, then `message.send` with
|
||||
`media_refs`.
|
||||
|
||||
### Voice input (mic button)
|
||||
|
||||
- Mic button (right of composer, toggles to send when text is present).
|
||||
- Tap → request `RECORD_AUDIO` permission → start recording (MediaRecorder,
|
||||
OGG/Opus, 44.1 kHz mono).
|
||||
@@ -199,11 +214,13 @@ app/shared/src/
|
||||
transcribes it. No client-side STT.
|
||||
|
||||
### Push notifications
|
||||
|
||||
- FCM service (see `08-push.md`): foreground banner + background foreground
|
||||
service → `sync`. Notification channel per chat. Tap → deep-link to chat.
|
||||
- ntfy fallback: foreground service maintains the subscription.
|
||||
|
||||
### Live playback
|
||||
|
||||
- AI-sent audio/video → `media.pull` → cache file → **ExoPlayer** inline player
|
||||
(audio: mini-player; video: inline + fullscreen + PiP). Documents/images →
|
||||
viewer / open-with.
|
||||
@@ -211,12 +228,14 @@ app/shared/src/
|
||||
## 10.6 Layout (Telegram-style, per reference image)
|
||||
|
||||
**Two layout modes** (decision: user-toggleable, **single-pane default**):
|
||||
|
||||
- **Single-pane (default on phones):** chat full-screen; channel list in a
|
||||
swipeable drawer (hamburger / edge swipe).
|
||||
- **Two-pane (Telegram-style, like the reference):** persistent left channel
|
||||
rail + chat. Auto-enabled on tablets / large screens; toggleable in Settings.
|
||||
|
||||
**Chat screen anatomy (matches reference):**
|
||||
|
||||
- **Header:** back (single-pane), avatar, name + "Bot" subtitle, edit + overflow
|
||||
(⋮) menu (thread toggle, channel menu, set cron target, clear).
|
||||
- **Message list:** date separators ("7. August"); user bubbles **right**
|
||||
@@ -231,18 +250,80 @@ color. Accent = user's chosen brand color (default indigo, like the reference).
|
||||
|
||||
## 10.7 SQLDelight schema (cache)
|
||||
|
||||
- `channels(chat_id PK, name, kind, parent_chat_id, is_default, last_preview,
|
||||
last_ts, unread)`.
|
||||
- `messages(id PK, chat_id, thread_id, role, text, reasoning, model, tokens,
|
||||
ts, status[pending|sent|read], media_json)`.
|
||||
- `media(media_id PK, local_path, kind, mime, size, ts)`.
|
||||
- `meta(key PK, value)` — sync cursor, settings, device_id, server url, pinned
|
||||
cert fingerprint.
|
||||
Implemented in `app/shared/src/commonMain/sqldelight/iris/db/Cache.sq`
|
||||
(database `IrisDatabase`, package `iris.db`). Rows are stored as **JSON
|
||||
payloads** so the schema does not drift with the Kotlin model fields
|
||||
(`MessageItem` / `ChannelInfo` are `@Serializable`):
|
||||
|
||||
- `message(lane PK, id PK, ts, payload)` — one row per persisted
|
||||
`MessageItem`; `lane` is the lane key (`chatId` or `chatId::threadId`),
|
||||
`ts` for ordering. Local system notices are **not** persisted (ephemeral).
|
||||
- `tool(lane PK, id PK, seq, payload)` — one row per persisted `ToolItem`
|
||||
(tool-activity card). Tool cards are **not** part of the gateway's
|
||||
`history` (which carries final messages only), so the app persists them
|
||||
itself to restore them across a restart. The payload carries `anchor_id`
|
||||
(the id of the message the card follows — the last non-streaming message
|
||||
when the tool started); on load the card is inserted after its anchor, so
|
||||
the order user message → tool card → answer survives a restart. A card
|
||||
whose anchor is gone (deleted message) falls to the end of the lane; an
|
||||
open card (process died before `tool.end`) is restored closed as
|
||||
interrupted.
|
||||
- `channel(chat_id PK, payload)` — the whole channel directory (channels +
|
||||
threads), so the drawer works offline.
|
||||
- `meta(key PK, value)` — small UI state (currently: `last_lane`, the
|
||||
last-viewed lane, restored on startup).
|
||||
|
||||
Not in the DB (already persisted elsewhere): sync cursor + settings live in
|
||||
`SecureStore`; media files in the `MediaCache` (files, not DB rows).
|
||||
|
||||
## 10.9 Local cache (offline reading, instant start)
|
||||
|
||||
The server is authoritative; the SQLite cache (10.7) makes the app feel
|
||||
instant and readable offline (industry-standard chat-app behavior):
|
||||
|
||||
- **Startup:** `IrisController` restores `ChatStore` + `ChannelStore` from
|
||||
the cache *before* the gateway connection is up — the UI is populated
|
||||
immediately, no waiting for `history`/`sync`. Restored state is sanitized:
|
||||
a streaming bubble is finalized (the `sync` replay finalizes it for real)
|
||||
and a pending send becomes *failed* (tap to retry).
|
||||
- **Writes:** the controller snapshots the in-memory stores into the cache,
|
||||
debounced (750 ms) — one atomic full rewrite per change, so every mutation
|
||||
path (frames, media pulls, read receipts, deletes, retries) is covered
|
||||
without per-mutation hooks. A final synchronous flush runs on `dispose`.
|
||||
The outbox replay on reconnect is the safety net for anything lost in the
|
||||
debounce window (the cursor only advances on `sync.done`).
|
||||
- **Connect:** the last-viewed lane (from `meta`) is kept if it still exists
|
||||
on the server, otherwise the app falls back to the home channel. The full
|
||||
`history` of the active lane is reloaded either way (the cache may be
|
||||
stale; `sync` only covers the outbox delta since the saved cursor). This
|
||||
runs on a **fast path** (`GatewayClient.onHelloAck`, fired on the WS thread
|
||||
the moment `hello.ack` lands) rather than the state collector, which can be
|
||||
starved for seconds during startup on slow devices — getting the request
|
||||
out early so the response lands inside a flaky network's window. A lane is
|
||||
marked "history loaded" only when the response is actually processed, so a
|
||||
request/response lost in a WS drop is retried on the next (re)connect.
|
||||
- **Offline:** with no connection the cached lanes/channels are fully
|
||||
readable (the composer is disabled, a connection banner is shown). New
|
||||
frames reconcile the cache on reconnect via `sync` + `history`.
|
||||
- **Forget pairing:** `chatDb.clearAll()` wipes the cache (a different
|
||||
gateway means a different chat universe).
|
||||
|
||||
Storage: `AndroidSqliteDriver` (app database dir) on Android,
|
||||
`JdbcSqliteDriver` (`~/.iris/iris_cache.db`) on desktop — both via the
|
||||
`createCacheDriver()` platform actual (`iris/platform/PlatformStorage.kt`).
|
||||
|
||||
## 10.8 Onboarding / Connect screen
|
||||
|
||||
- First launch → **Connect**: server URL + token (or scan QR). "Test connection"
|
||||
does a real `hello` (not just a TCP probe — per hermes desktop guidance, the
|
||||
auth leg must be exercised). On success → save (secure storage) → main.
|
||||
- **Scan QR** (Android only, `docs/20`): a button below the token field opens
|
||||
`QrScanActivity` (CameraX + ML Kit, on-device, no Play services), requests the
|
||||
`CAMERA` permission, and pre-fills URL + token from the decoded
|
||||
`iris://pair…` payload via `PairLink.parse`. It never auto-connects — the
|
||||
user still taps "Test & Connect". A non-pairing QR sets an error and leaves
|
||||
the fields untouched. The same payload also arrives as an `iris://pair` deep
|
||||
link (system scanner / other phones) and pre-fills the screen the same way.
|
||||
Hidden on desktop (no camera).
|
||||
- States: connecting / connected / reconnecting / degraded / auth-failed — each
|
||||
with honest copy and a way out.
|
||||
with honest copy and a way out.
|
||||
@@ -1,13 +1,13 @@
|
||||
# 11 — Desktop App (Kotlin + Compose Multiplatform)
|
||||
|
||||
The desktop app is **the Android app, tweaked for a big screen**. It reuses the
|
||||
The desktop app is **the Iris app, tweaked for a big screen**. It reuses the
|
||||
entire `app/shared` module (protocol, network, repositories, state, most UI) and
|
||||
only adds desktop platform services + a wider default layout.
|
||||
|
||||
## 11.1 What's shared vs desktop-specific
|
||||
|
||||
| Layer | Shared (commonMain) | Desktop-specific (desktopMain) |
|
||||
|---|---|---|
|
||||
| --- | --- | --- |
|
||||
| Protocol / WS client | ✅ | — |
|
||||
| Repositories / state | ✅ | — |
|
||||
| Most Compose UI | ✅ | layout tweaks, keyboard shortcuts |
|
||||
@@ -62,9 +62,9 @@ only adds desktop platform services + a wider default layout.
|
||||
- The desktop app connects to the **same** gateway WS server as the phone (the
|
||||
user's home server / Tailscale). It does **not** spawn its own backend (unlike
|
||||
hermes's existing Electron desktop, which spawns `hermes serve`) — our
|
||||
desktop is a pure client of the messaging gateway, matching the Android app.
|
||||
desktop is a pure client of the messaging gateway, matching the Iris app.
|
||||
|
||||
## 11.5 Parity checklist (same functionality as Android)
|
||||
## 11.5 Parity checklist (same functionality as the Iris app)
|
||||
|
||||
- [ ] Streaming, reasoning block, tool cards (3-level verbosity), commentary.
|
||||
- [ ] Channels + threads + new channel + cron target.
|
||||
@@ -72,4 +72,4 @@ only adds desktop platform services + a wider default layout.
|
||||
- [ ] Media attach + live playback (via desktop player).
|
||||
- [ ] Slash command menu + autocomplete + interactive pickers.
|
||||
- [ ] Push (tray + OS notifications) + outbox/sync.
|
||||
- [ ] Pairing/Connect screen (URL + token, WSS cert pin).
|
||||
- [ ] Pairing/Connect screen (URL + token, WSS cert pin).
|
||||
+41
-29
@@ -9,6 +9,7 @@ First-time setup on a machine (verified baseline: CachyOS/Arch, `pacman`,
|
||||
pacman -S jdk17-openjdk
|
||||
java -version # expect 17.x
|
||||
```
|
||||
|
||||
(Compose Multiplatform + current AGP are happy on JDK 17. Use 17 to match the
|
||||
Android toolchain; 21 also works but 17 is the safe floor.)
|
||||
|
||||
@@ -28,10 +29,12 @@ export PATH=$PATH:$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-
|
||||
sdkmanager --licenses
|
||||
sdkmanager "platform-tools" "platforms;android-34" "build-tools;34.0.0"
|
||||
```
|
||||
|
||||
Persist `ANDROID_HOME`/`PATH` in `~/.bashrc`. ADB is already installed system-wide;
|
||||
`platform-tools` from the SDK is fine too (whichever is first on `PATH`).
|
||||
|
||||
Create `app/local.properties`:
|
||||
|
||||
```
|
||||
sdk.dir=/home/<you>/android-sdk
|
||||
```
|
||||
@@ -39,10 +42,12 @@ sdk.dir=/home/<you>/android-sdk
|
||||
## 12.3 Gradle
|
||||
|
||||
No system install — use the project wrapper:
|
||||
|
||||
```bash
|
||||
cd app
|
||||
./gradlew tasks # first run downloads the wrapper distribution
|
||||
```
|
||||
|
||||
(The wrapper version is pinned in `app/gradle/wrapper/gradle-wrapper.properties`.)
|
||||
|
||||
## 12.4 hermes environment (for the plugin + running the gateway)
|
||||
@@ -53,15 +58,19 @@ uv sync # creates .venv with all core deps (websockets, httpx,
|
||||
source .venv/bin/activate
|
||||
hermes --version # sanity
|
||||
```
|
||||
|
||||
- Run the gateway with the plugin:
|
||||
|
||||
```bash
|
||||
# install the plugin (dev: symlink)
|
||||
mkdir -p ~/.hermes/plugins
|
||||
ln -s "$PWD/../gateway-plugin" ~/.hermes/plugins/android
|
||||
hermes gateway status # should list "android"
|
||||
ln -s "$PWD/../gateway-plugin" ~/.hermes/plugins/iris
|
||||
hermes gateway status # should list "iris"
|
||||
hermes gateway # run
|
||||
```
|
||||
|
||||
- Tests use hermes's hermetic runner (never bare `pytest`):
|
||||
|
||||
```bash
|
||||
scripts/run_tests.sh tests/gateway/test_android.py
|
||||
```
|
||||
@@ -73,43 +82,46 @@ hermes --version # sanity
|
||||
`dev.iris.app`). Download `google-services.json` → `app/androidApp/`.
|
||||
3. Create a **service account** (Project settings → Service accounts → Generate
|
||||
new private key) → download the JSON. Store its path in
|
||||
`ANDROID_FCM_SERVICE_ACCOUNT` (in `~/.hermes/.env`).
|
||||
`IRIS_FCM_SERVICE_ACCOUNT` (in `~/.hermes/.env`).
|
||||
4. The app's `FirebaseMessagingService` obtains the FCM token at runtime and
|
||||
registers it via `hello` / `fcm.register`.
|
||||
|
||||
> Skip Firebase → set `ANDROID_PUSH_BACKEND=ntfy` and configure `NTFY_TOPIC` /
|
||||
> `NTFY_SERVER_URL` (self-host ntfy or use ntfy.sh). See `08-push.md`.
|
||||
> Skip Firebase → the default is already ntfy: leave `IRIS_PUSH_BACKEND` unset
|
||||
> (or set it to `ntfy`) and configure `NTFY_TOPIC` / `NTFY_SERVER_URL`
|
||||
> (self-host ntfy or use ntfy.sh). See `08-push.md`.
|
||||
|
||||
## 12.6 Environment variables (summary)
|
||||
|
||||
**Secrets (`~/.hermes/.env`):**
|
||||
|
||||
```
|
||||
ANDROID_TOKEN=<64-hex>
|
||||
ANDROID_PUSH_BACKEND=fcm # or ntfy
|
||||
ANDROID_FCM_SERVICE_ACCOUNT=/path/to/service-account.json
|
||||
# ANDROID_FCM_SERVER_KEY=<legacy key> # fallback if no service account
|
||||
IRIS_TOKEN=<64-hex>
|
||||
IRIS_PUSH_BACKEND=ntfy # default; fcm = opt-in (metadata via Google)
|
||||
IRIS_FCM_SERVICE_ACCOUNT=/path/to/service-account.json
|
||||
# IRIS_FCM_SERVER_KEY=<legacy key> # fallback if no service account
|
||||
# NTFY_TOPIC=iris-push # when ntfy
|
||||
# NTFY_SERVER_URL=https://ntfy.sh
|
||||
# ANDROID_WS_CERT=/path/cert.pem # WSS
|
||||
# ANDROID_WS_KEY=/path/key.pem
|
||||
# IRIS_HTTP_CERT=/path/cert.pem # HTTPS
|
||||
# IRIS_HTTP_KEY=/path/key.pem
|
||||
```
|
||||
|
||||
**Behavioral (`~/.hermes/config.yaml`):**
|
||||
|
||||
```yaml
|
||||
gateway:
|
||||
platforms:
|
||||
android:
|
||||
iris:
|
||||
enabled: true
|
||||
extra:
|
||||
host: 127.0.0.1 # 0.0.0.0 for LAN
|
||||
port: 8790
|
||||
home_channel: android:default
|
||||
http_port: 8791
|
||||
home_channel: default
|
||||
push_backend: fcm
|
||||
outbox_retention_hours: 72
|
||||
max_upload_bytes: 104857600 # 100 MB
|
||||
display:
|
||||
platforms:
|
||||
android:
|
||||
iris:
|
||||
show_reasoning: true
|
||||
reasoning_style: code
|
||||
streaming: true
|
||||
@@ -120,19 +132,19 @@ display:
|
||||
|
||||
```bash
|
||||
# 1. gateway up with plugin
|
||||
hermes gateway status | grep -i android
|
||||
hermes gateway status | grep -i iris
|
||||
|
||||
# 2. a raw WS client can pair + echo
|
||||
python - <<'PY'
|
||||
import asyncio, json, websockets
|
||||
async def main():
|
||||
async with websockets.connect("ws://127.0.0.1:8790/ws") as ws:
|
||||
await ws.send(json.dumps({"v":1,"type":"hello","payload":{
|
||||
"token":"<ANDROID_TOKEN>","device_id":"test","device_name":"probe",
|
||||
"caps":{"min_protocol":1}}}))
|
||||
print("recv:", await ws.recv())
|
||||
asyncio.run(main())
|
||||
PY
|
||||
# 2. the HTTP server answers (unauthenticated liveness)
|
||||
curl -s http://127.0.0.1:8791/v1/health
|
||||
# -> {"ok": true}
|
||||
|
||||
# 3. a frame round-trip with the pairing token
|
||||
curl -s -X POST http://127.0.0.1:8791/v1/frame \
|
||||
-H "Authorization: Bearer <IRIS_TOKEN>" -H "X-Iris-Device: probe" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"v":1,"type":"commands.catalog","id":1,"payload":{}}'
|
||||
```
|
||||
Expect a `hello.ack`. If you get `error {code:"auth"}`, the token/host/port is
|
||||
wrong.
|
||||
|
||||
Expect `{"ok": true}` from the health probe and a `commands.catalog` reply
|
||||
frame from the POST. If you get `401`, the token/host/port is
|
||||
wrong.
|
||||
+22
-9
@@ -6,20 +6,22 @@ without the app (critical for verifying frame shapes early).
|
||||
|
||||
## 13.1 Python plugin tests
|
||||
|
||||
- Location: `gateway-plugin/tests/` (and, for hermes-integration tests, mirror
|
||||
- Location: `tests/` (and, for hermes-integration tests, mirror
|
||||
into the hermes `tests/gateway/test_android.py` pattern when running under
|
||||
hermes's suite).
|
||||
- **Run with hermes's hermetic runner** (never bare `pytest`):
|
||||
|
||||
```bash
|
||||
cd hermes-agent
|
||||
scripts/run_tests.sh tests/gateway/test_android.py
|
||||
scripts/run_tests.sh # full suite (CI parity)
|
||||
```
|
||||
|
||||
- Coverage to write (behavioral, not change-detector — per hermes test policy):
|
||||
- `register(ctx)` produces a valid `PlatformEntry` (name, cron env var,
|
||||
parse_target_ref).
|
||||
- `check_requirements` / `validate_config` / `is_connected` truth table.
|
||||
- `_parse_target_ref`: `android:<chat>`, `android:<chat>:<thread>`, non-android
|
||||
- `_parse_target_ref`: `iris:<chat>`, `iris:<chat>:<thread>`, non-iris
|
||||
→ None.
|
||||
- **Reasoning split:** given a `show_reasoning`-style final text, `send()`
|
||||
emits `message {reasoning, text}` correctly; no-prefix → no reasoning field.
|
||||
@@ -46,19 +48,20 @@ without the app (critical for verifying frame shapes early).
|
||||
|
||||
## 13.2 WS test-client harness (do this FIRST, in M1/M2)
|
||||
|
||||
A small Python script (`gateway-plugin/tests/ws_probe.py`) that connects to the
|
||||
A small Python script (`tests/ws_probe.py`) that connects to the
|
||||
**real running gateway** and drives a turn, printing every frame. This is how we
|
||||
**empirically confirm** the exact frame shapes (especially tool-progress vs
|
||||
commentary classification and the reasoning prefix) before/while building the
|
||||
Kotlin client.
|
||||
|
||||
```bash
|
||||
hermes gateway & # with the android plugin
|
||||
python gateway-plugin/tests/ws_probe.py --token <ANDROID_TOKEN> \
|
||||
hermes gateway & # with the iris plugin
|
||||
python tests/ws_probe.py --token <IRIS_TOKEN> \
|
||||
--send "list the files and summarize"
|
||||
# prints: hello.ack, typing, message.start, message.update…, tool.start, tool.end,
|
||||
# commentary, message.stop {reasoning,…}, …
|
||||
```
|
||||
|
||||
Use it to lock `04-wire-protocol.md` against reality and to debug the adapter
|
||||
without waiting for the app.
|
||||
|
||||
@@ -102,6 +105,7 @@ adb logcat -d > /tmp/logcat.txt
|
||||
```
|
||||
|
||||
**E2E scenarios (script where possible):**
|
||||
|
||||
1. **Pair:** connect screen → enter URL+token → `hello.ack` → main. (Verify auth
|
||||
leg, not just TCP.)
|
||||
2. **Text round-trip:** send "hello" → streamed reply appears (message.start →
|
||||
@@ -112,7 +116,7 @@ adb logcat -d > /tmp/logcat.txt
|
||||
verbosity in Settings → rendering changes.
|
||||
5. **Intermediate:** a multi-step prompt → commentary bubble appears dimmed.
|
||||
6. **Channels:** create "Cron Reports" → appears in list; set as cron target.
|
||||
7. **Cron delivery:** create a cron job `deliver=android:android:chan_<n>` → it
|
||||
7. **Cron delivery:** create a cron job `deliver=iris:chan_<n>` → it
|
||||
fires → lands in that channel (not default).
|
||||
8. **Search:** "search everywhere" vs "this chat" → correct scoping; tap → jump.
|
||||
9. **Media (in):** attach a photo + a video → agent receives (vision) → reply.
|
||||
@@ -131,19 +135,28 @@ adb logcat -d > /tmp/logcat.txt
|
||||
entries drop out); tap a row → the command is sent and the drawer closes;
|
||||
type an unknown command → the drawer closes (the raw text can still be
|
||||
sent; hermes answers with its unknown-command reply).
|
||||
15. **HTTP fallback (docs/19):** with the WS port unreachable (e.g. the
|
||||
gateway bound WS to a dead port, or a firewall dropping 8790 but not
|
||||
8791), the app stays sendable: the status pill shows "connected · http"
|
||||
(green), a sent message echoes back within ~1 s and the agent reply
|
||||
streams in over SSE; the attach button is disabled (media needs the
|
||||
live WS). When the WS comes back the pill returns to "connected" and
|
||||
media works again. Automated: `e2e.py` scenario 13 (health +
|
||||
`POST /v1/frame` + SSE turn, user-echo < 1.5 s) and
|
||||
`ws_probe.py --http` (same assertion flags as the WS leg).
|
||||
|
||||
## 13.5 Debugging tips
|
||||
|
||||
- **Gateway side:** `~/.hermes/logs/gateway.log` (and `hermes logs --follow`).
|
||||
Our plugin logs under the `android` adapter name; secrets redacted.
|
||||
Our plugin logs under the `iris` adapter name; secrets redacted.
|
||||
- **WS framing bugs:** use the `ws_probe.py` harness — it isolates the protocol
|
||||
from the app.
|
||||
- **Streaming jitter:** the consumer edits at intervals; if updates look chunky,
|
||||
check `display.platforms.android.streaming` and the consumer's edit interval.
|
||||
check `display.platforms.iris.streaming` and the consumer's edit interval.
|
||||
- **Media pull stalls:** check chunk size + backpressure; confirm the file is
|
||||
within hermes delivery roots (`validate_media_delivery_path`).
|
||||
- **FCM not arriving:** confirm the token registered (`devices.db`), the service
|
||||
account can mint a token, and the app's `onNewToken` re-registered after
|
||||
`pm clear`.
|
||||
- **Profile leaks:** if tokens look wrong under multiple profiles, verify the
|
||||
scope-aware secret read (`_get_scoped_secret`) is used.
|
||||
scope-aware secret read (`_get_scoped_secret`) is used.
|
||||
+59
-12
@@ -1,4 +1,4 @@
|
||||
# 14 — Milestones (M0–M7)
|
||||
# 14 — Milestones (M0–M8)
|
||||
|
||||
Phased delivery. Each milestone ends with a **demo** (on-device where noted) and
|
||||
has explicit **acceptance criteria**. Work top-to-bottom; don't skip M0/M1.
|
||||
@@ -6,7 +6,9 @@ has explicit **acceptance criteria**. Work top-to-bottom; don't skip M0/M1.
|
||||
---
|
||||
|
||||
## M0 — Toolchain & scaffolding
|
||||
|
||||
**Goal:** everything builds; the plugin is discoverable; the repo is safe.
|
||||
|
||||
- [X] Install JDK 17, Android SDK, set `ANDROID_HOME` (`12-toolchain.md`).
|
||||
- [X] `cd hermes-agent && uv sync` (hermes venv works).
|
||||
- [X] Create monorepo scaffold (`02-monorepo.md`): `gateway-plugin/`, `app/`
|
||||
@@ -16,20 +18,22 @@ has explicit **acceptance criteria**. Work top-to-bottom; don't skip M0/M1.
|
||||
- [X] CMP project builds empty: `./gradlew :androidApp:assembleDebug`,
|
||||
`./gradlew :desktopApp:run` (blank window).
|
||||
- [X] Plugin skeleton: `plugin.yaml` + `adapter.py` with `register(ctx)` + a
|
||||
no-op `AndroidAdapter` → `hermes gateway status` lists **android**.
|
||||
- **Demo:** `hermes gateway status` shows `android`; `./gradlew
|
||||
no-op `IrisAdapter` → `hermes gateway status` lists **iris**.
|
||||
- **Demo:** `hermes gateway status` shows `iris`; `./gradlew
|
||||
:androidApp:installDebug` installs a blank app on the MIX 2S.
|
||||
- **Accept:** blank app installs + launches on-device; plugin visible in
|
||||
`hermes gateway status`; `hermes-agent/` is git-ignored (verify with
|
||||
`git status --ignored`).
|
||||
|
||||
## M1 — Gateway core loop (text round-trip)
|
||||
|
||||
**Goal:** pair + send a text message + get a (non-streaming) reply.
|
||||
|
||||
- [X] WS server (`ws_server.py`): bind, `hello` auth (constant-time),
|
||||
`hello.ack`, heartbeat, connection registry.
|
||||
- [X] `AndroidAdapter.send()` → `message` frame; inbound `message.send` →
|
||||
- [X] `IrisAdapter.send()` → `message` frame; inbound `message.send` →
|
||||
`MessageEvent` → `handle_message`.
|
||||
- [X] Pairing store + `ANDROID_TOKEN`; QR payload in `interactive_setup`.
|
||||
- [X] Pairing store + `IRIS_TOKEN`; QR payload in `interactive_setup`.
|
||||
- [X] App: Connect screen (URL+token, real `hello` test), `GatewayClient`
|
||||
(connect + reconnect), ChatScreen sends + renders `message`.
|
||||
- [X] `ws_probe.py` harness drives a real turn.
|
||||
@@ -38,9 +42,11 @@ has explicit **acceptance criteria**. Work top-to-bottom; don't skip M0/M1.
|
||||
reconnect after gateway restart re-pairs.
|
||||
|
||||
## M2 — Streaming + reasoning + tools + commentary
|
||||
|
||||
**Goal:** the "agent transparency" features.
|
||||
|
||||
- [X] Map consumer `send`/`edit_message` → `message.start/update/stop`.
|
||||
- [X] Reasoning: set `show_reasoning` for android; adapter splits prefix →
|
||||
- [X] Reasoning: set `show_reasoning` for iris; adapter splits prefix →
|
||||
`reasoning` field. **Verify format with `ws_probe.py`.** (The model
|
||||
returns a separate `reasoning_content` field. In the *streaming* case the
|
||||
gateway drops it — the stream consumer only forwards `content` and the
|
||||
@@ -64,12 +70,14 @@ has explicit **acceptance criteria**. Work top-to-bottom; don't skip M0/M1.
|
||||
rendering; reasoning copy button works; frame shapes match `04-wire-protocol`.
|
||||
|
||||
## M3 — Channels/threads + cron + search
|
||||
|
||||
**Goal:** organization + cron delegation + search.
|
||||
|
||||
- [X] Channel directory (SQLite): default channel ensured; `channel.create/
|
||||
rename/set_default/delete` + `channel.*` frames.
|
||||
- [X] Threads: toggle in default chat; `thread_id` lanes; `create_handoff_thread`.
|
||||
- [X] `parse_target_ref_fn` + `cron_deliver_env_var` → cron
|
||||
`deliver=android:<chat>[:<thread>]` works.
|
||||
`deliver=iris:<chat>[:<thread>]` works.
|
||||
- [X] `search.py` FTS5 bridge; `search` frame (all / this-chat) → results.
|
||||
- [X] App: channel list (drawer/rail), thread toggle + topic switcher, "new
|
||||
channel" + "set as cron target", SearchScreen with scope toggle + jump.
|
||||
@@ -79,7 +87,7 @@ has explicit **acceptance criteria**. Work top-to-bottom; don't skip M0/M1.
|
||||
isolate context; search scoping correct; channel list reconciles on events.
|
||||
- **Status (complete):** channel directory + threads + search + outbox sync
|
||||
verified end-to-end via `ws_probe.py` (create/rename/set_default/delete,
|
||||
thread lanes, FTS5 search, sync); cron `deliver=android:<chat>[:<thread>]`
|
||||
thread lanes, FTS5 search, sync); cron `deliver=iris:<chat>[:<thread>]`
|
||||
target resolution verified via `resolve_send_target`. App on-device: channel
|
||||
drawer, thread toggle + topic switcher, new channel, search overlay with
|
||||
jump. Minor UI gaps deferred to M7 polish: "set as cron target" is set via
|
||||
@@ -89,7 +97,9 @@ has explicit **acceptance criteria**. Work top-to-bottom; don't skip M0/M1.
|
||||
not e2e-tested (it shares the verified resolution path).
|
||||
|
||||
## M4 — Media
|
||||
|
||||
**Goal:** attach + receive + play media.
|
||||
|
||||
- [X] Inbound: `media.upload` chunked → `cache_*_from_bytes` → `media_urls`;
|
||||
size limit + sha256 + MIME re-sniff.
|
||||
- [X] Outbound: `send_*` → `media.offer`; `media.pull` chunked; delivery-path
|
||||
@@ -117,12 +127,14 @@ has explicit **acceptance criteria**. Work top-to-bottom; don't skip M0/M1.
|
||||
`04-wire-protocol.md` + `frames.schema.json`.
|
||||
|
||||
## M5 — Push + offline (FCM + ntfy)
|
||||
|
||||
**Goal:** reach the phone when backgrounded; catch up on reconnect.
|
||||
|
||||
- [x] Outbox (SQLite) + sync cursor; `sync`/`sync.done`; retention prune
|
||||
(row cap 5000 + prune banner, throttled 1/h).
|
||||
- [x] `push.py`: `FcmBackend` (HTTP v1 + service account, httpx; JWT via
|
||||
PyJWT+cryptography) + `NtfyBackend` (X-Data header); selected by
|
||||
`ANDROID_PUSH_BACKEND`. ntfy server exposed in `server_caps.push_ntfy_server`.
|
||||
`IRIS_PUSH_BACKEND`. ntfy server exposed in `server_caps.push_ntfy_server`.
|
||||
- [x] Fire push on no-live-subscriber; data payload for silent sync.
|
||||
High-priority kinds (approval/clarify/cron) push even when live.
|
||||
- [x] App: FCM service (`onNewToken` → `fcm.register`; inert without a
|
||||
@@ -143,15 +155,17 @@ has explicit **acceptance criteria**. Work top-to-bottom; don't skip M0/M1.
|
||||
loss/dup (verified); banners show for foreground events (implemented).
|
||||
|
||||
## M6 — Desktop app
|
||||
|
||||
**Goal:** the same app on a big screen.
|
||||
|
||||
- [x] `desktopMain`: tray + OS notifications; `MediaPlayer` actual (mpv/WebView);
|
||||
`MediaPicker` actual (file dialog); `SecureStore` actual; window mgmt.
|
||||
- [x] Two-pane default layout; keyboard shortcuts; optional inspector pane.
|
||||
- [ ] Parity pass vs Android feature checklist (`11-desktop-app.md`).
|
||||
- [ ] Parity pass vs Iris app feature checklist (`11-desktop-app.md`).
|
||||
- [x] jpackage builds (Linux first; macOS/Windows as available).
|
||||
- **Demo:** desktop app pairs to the same gateway; full feature parity; tray
|
||||
notifications; media plays.
|
||||
- **Accept:** all Android features work on desktop; tray + shortcuts work;
|
||||
- **Accept:** all Iris app features work on desktop; tray + shortcuts work;
|
||||
native binary launches.
|
||||
- **Status (complete, 2026-08-19):** All `desktopMain` actuals implemented and
|
||||
verified on Linux (X11). `DesktopSecureStore`: non-secrets in
|
||||
@@ -178,7 +192,9 @@ has explicit **acceptance criteria**. Work top-to-bottom; don't skip M0/M1.
|
||||
macOS/Windows packaging are deferred to M7.
|
||||
|
||||
## M7 — Polish + E2E + docs
|
||||
|
||||
**Goal:** ship-quality.
|
||||
|
||||
- [x] Telegram-style layout pass (per reference image): header, bubbles, date
|
||||
separators, ✓✓, model/token footer, banner, bottom bar.
|
||||
- [x] Theming (dark default, accent), onboarding/pairing UX, empty/loading/
|
||||
@@ -222,12 +238,43 @@ has explicit **acceptance criteria**. Work top-to-bottom; don't skip M0/M1.
|
||||
|
||||
---
|
||||
|
||||
## M8 — QR pairing
|
||||
|
||||
**Goal:** QR-based pairing — a scannable QR at `hermes gateway setup` plus an
|
||||
in-app scanner and `iris://pair` deep link (closes gap #12, `docs/20`).
|
||||
|
||||
- [x] Pure-stdlib QR encoder + terminal renderer (`gateway-plugin/qr.py`):
|
||||
byte mode, EC M with L fallback, versions 1–10, ISO penalty masking,
|
||||
**zero new Python deps**.
|
||||
- [x] `interactive_setup` renders the QR after the pairing URL (text lines
|
||||
stay as the primary path).
|
||||
- [x] `PairLink` parser (`iris/util/PairLink.kt`) + jvmTest (valid/missing
|
||||
token/bad port/wrong scheme/wrong host/percent-encoded/secure/default
|
||||
port).
|
||||
- [x] CameraX + ML Kit scanner (`QrScanActivity`, on-device, no Play
|
||||
services) + Connect-screen **Scan QR** button (Android only; hidden on
|
||||
desktop) + `CAMERA` permission.
|
||||
- [x] `iris://pair` deep link (system-scanner / other-phone fallback) reusing
|
||||
the same parser.
|
||||
- **Accept:** `docs/20` §20.6; gap #12 in `09-pairing-security.md` closed.
|
||||
- **Status (2026-08-22):** Encoder cross-checked byte-for-byte against an
|
||||
independent reference and decoded by an independent decoder (zbarimg); fixed
|
||||
v1-M and v7-M matrix vectors lock the algorithm. `hermes gateway setup`
|
||||
prints a scannable QR (v7-M, 45 modules) for the 64-hex-token payload. App:
|
||||
Connect screen shows **Scan QR** (Android), which opens `QrScanActivity`
|
||||
(CameraX camera2 + ML Kit barcode), requests `CAMERA`, and pre-fills URL +
|
||||
token via `PairLink.parse` without auto-connecting; `iris://pair` deep link
|
||||
pre-fills the same way. Docs updated per `docs/20` Part C.
|
||||
|
||||
---
|
||||
|
||||
## Sequencing notes
|
||||
|
||||
- **M1/M2 depend on the `ws_probe.py` harness** to lock frame shapes early —
|
||||
build it in M1.
|
||||
- **M3 (cron) and M5 (push) both touch the outbox** — build the outbox in M3,
|
||||
extend for push in M5.
|
||||
- **M6 (desktop) reuses M1–M5 shared code** — do it after the Android features
|
||||
- **M6 (desktop) reuses M1–M5 shared code** — do it after the Iris app features
|
||||
are stable so the shared module is settled.
|
||||
- Parallelizable: plugin (Python) and app (Kotlin) can be worked on
|
||||
concurrently once the protocol (`04-wire-protocol.md`) is agreed; the probe
|
||||
|
||||
@@ -5,7 +5,7 @@ integration point. Paths are relative to `hermes-agent/` (the read-only
|
||||
reference). This lets a coder jump straight to the right code instead of
|
||||
re-deriving the architecture.
|
||||
|
||||
> ⚠️ Read-only. We **install** our plugin into `~/.hermes/plugins/android`; we
|
||||
> ⚠️ Read-only. We **install** our plugin into `~/.hermes/plugins/iris`; we
|
||||
> never edit these files.
|
||||
|
||||
## Plugin / platform registration
|
||||
|
||||
+12
-10
@@ -3,24 +3,24 @@
|
||||
## Locked decisions (from planning, 2026-08-19)
|
||||
|
||||
| # | Decision | Choice | Rationale |
|
||||
|---|---|---|---|
|
||||
| 1 | Desktop app tech | **Compose Multiplatform** | Desktop = "the Android app, tweaked"; share protocol/state/UI. |
|
||||
| 2 | Push backend | **Both — FCM primary, ntfy fallback** | FCM is standard/reliable; ntfy for self-hosters with no Firebase. `ANDROID_PUSH_BACKEND`. |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | Desktop app tech | **Compose Multiplatform** | Desktop = "the Iris app, tweaked"; share protocol/state/UI. |
|
||||
| 2 | Push backend | **Both — ntfy default, FCM optional** (issue #10: FCM metadata — title, device token — is routed via Google's servers, contradicting the privacy claim; ntfy keeps it on your own infrastructure) | `IRIS_PUSH_BACKEND`. |
|
||||
| 3 | Media transport | **Over the WebSocket** | One transport, zero new Python deps; chunked binary frames. |
|
||||
| 4 | Phone default layout | **User-toggleable, single-pane default** | App-like on phones; auto two-pane on large screens; desktop defaults two-pane. |
|
||||
|
||||
## Additional decisions made during planning
|
||||
|
||||
| Decision | Choice | Note |
|
||||
|---|---|---|
|
||||
| Connection point | **Messaging gateway** (platform plugin `android`), not `tui_gateway` | Makes cron/`send_message`/slash/coexistence native. |
|
||||
| --- | --- | --- |
|
||||
| Connection point | **Messaging gateway** (platform plugin `iris`), not `tui_gateway` | Makes cron/`send_message`/slash/coexistence native. |
|
||||
| Plugin style | **Community plugin** (`register(ctx)`) | Zero hermes-core changes. |
|
||||
| Python deps | **None new** (`websockets` + `httpx` are core) | Respects hermes pinning policy. |
|
||||
| Tool events | **Structured frames; app controls verbosity** | Gateway sends full data; app = everything/truncated/nothing. |
|
||||
| Reasoning | **Adapter splits the `show_reasoning` prefix** | Clean `reasoning` field → collapsible block above message. |
|
||||
| Channels/threads | **Map onto `chat_id`/`thread_id`** | Existing gateway primitives; cron targets them. |
|
||||
| Offline | **SQLite outbox + sync cursor** | Catch-up on reconnect; push on disconnect. |
|
||||
| Default chat id | `android:default` | Home channel + cron default. |
|
||||
| Default chat id | `default` | Home channel + cron default. |
|
||||
| WS port | `8790` (default) | Configurable. |
|
||||
| minSdk | 26 (test device API 29) | Broad coverage. |
|
||||
| Frame routing | **Broadcast to all connected devices** (no per-chat subscribe) | Single-user model; simpler. |
|
||||
@@ -29,6 +29,8 @@
|
||||
| Agent lifecycle | **`agent.busy`/`agent.idle`** events + **`agent.stop`/`agent.steer`** requests | App shows thinking indicator; user can abort or steer mid-turn. |
|
||||
| Local DB (KMP) | **SQLDelight** (not Room) | Room is Android-only; SQLDelight works in commonMain for both platforms. |
|
||||
| Voice input | **Record → upload as audio media** (no client-side STT) | Agent's STT (if configured) handles transcription. |
|
||||
| QR encoder | **Pure-stdlib** (`gateway-plugin/qr.py`) | No `qrcode`/`segno`/Pillow; byte mode, EC M→L, v1–10, ISO penalty masking. Keeps the plugin's zero-new-dep rule. |
|
||||
| QR scanner | **ML Kit barcode** (not zxing-android-embedded) | On-device, no Google Play services; better accuracy/latency, Google-maintained. Android-only (desktop has no camera). |
|
||||
|
||||
## Open questions (resolve during implementation)
|
||||
|
||||
@@ -42,10 +44,10 @@ will proceed with unless you say otherwise.
|
||||
live gateway. If a clean metadata marker exists, prefer it.
|
||||
2. **Reasoning prefix format stability (M2).** We split on the `code`-style
|
||||
`💭 **Reasoning:**\n```\n…\n```\n\n` prefix. *Default:* set
|
||||
`reasoning_style: code` for android and split on that; fallback = no
|
||||
`reasoning_style: code` for iris and split on that; fallback = no
|
||||
reasoning field (full text) if the prefix isn't found. Verify in M2.
|
||||
3. **Per-device tokens vs shared token (M1/M5).** *Default (v1):* shared
|
||||
`ANDROID_TOKEN` + optional `ANDROID_ALLOWED_USERS` device allowlist.
|
||||
`IRIS_TOKEN` + optional `IRIS_ALLOWED_USERS` device allowlist.
|
||||
Per-device revocable tokens are a stretch.
|
||||
4. **Desktop video backend (M6).** *Default:* `libmpv`/`mpv`-backed Compose
|
||||
surface, WebView fallback. Confirm `mpv` availability on target OSes during
|
||||
@@ -54,7 +56,7 @@ will proceed with unless you say otherwise.
|
||||
recommended remote path; WSS + reverse proxy as alternatives. No public bind
|
||||
by default.
|
||||
6. **Streaming cadence (M2).** If live updates look chunky, tune
|
||||
`display.platforms.android.streaming` / consumer edit interval. *Default:*
|
||||
`display.platforms.iris.streaming` / consumer edit interval. *Default:*
|
||||
follow global streaming config.
|
||||
7. **App package name / branding.** *Default:* applicationId `dev.iris.app`,
|
||||
app name "Iris". Confirm final product name + package + icon.
|
||||
@@ -72,4 +74,4 @@ will proceed with unless you say otherwise.
|
||||
- End-to-end encryption (transport WSS only).
|
||||
- Standalone-cron delivery while the gateway process is fully down (best-effort
|
||||
push only).
|
||||
- iOS.
|
||||
- iOS.
|
||||
@@ -153,7 +153,7 @@ Config + setup per provider — `web_server.py` `/api/memory/providers/*`.
|
||||
`app/shared/.../protocol/Protocol.kt` → `docs/protocol/frames.schema.json`).
|
||||
2. **Security is the real gate.** The single-user model in
|
||||
`09-pairing-security.md` still holds, but control frames widen the blast
|
||||
radius of a leaked `ANDROID_TOKEN`. Sensitive operations (env/secrets,
|
||||
radius of a leaked `IRIS_TOKEN`. Sensitive operations (env/secrets,
|
||||
config writes, gateway restart, profile deletion) should get either an
|
||||
in-app confirmation step or a capability flag negotiated at pairing.
|
||||
3. **Read-heavy first.** Most of the value is in list/view frames (cheap,
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
# 18 — Code Review & Lint/LSP Cleanup (alpha → stable)
|
||||
|
||||
Comprehensive review of all three components — **gateway plugin**, **Iris app
|
||||
(Android)**, and **Desktop app** — performed to take the project from alpha to a
|
||||
clean, stable baseline. Each section records what was found, what was fixed,
|
||||
how it was verified, and what was deliberately left (with rationale).
|
||||
|
||||
> Companion file: [`DECISIONS.md`](../DECISIONS.md) at the repo root records the
|
||||
> judgment calls made during this pass (rule thresholds, suppressed findings,
|
||||
> config additions). This doc is the *findings*; that file is the *decisions*.
|
||||
|
||||
Verification tooling used throughout:
|
||||
|
||||
- **Ruff** (via the `hermes-agent/.venv` interpreter) — see
|
||||
[`gateway-plugin/ruff.toml`](../gateway-plugin/ruff.toml) for the rule set.
|
||||
- **pi-lens** (`lens_diagnostics mode=full`) — LSP + tree-sitter + ast-grep +
|
||||
opengrep + jscpd + gitleaks.
|
||||
- **Python test suite** — `hermes-agent/scripts/run_tests.sh
|
||||
tests/gateway/test_android.py` (64 tests).
|
||||
- **Kotlin** — `./gradlew :shared:testDebugUnitTest` / `:shared:desktopTest`
|
||||
and `./gradlew lint` (Android/Desktop).
|
||||
|
||||
---
|
||||
|
||||
## 18.1 Gateway plugin (`gateway-plugin/`)
|
||||
|
||||
### 18.1.1 Findings (before)
|
||||
|
||||
A fresh `lens_diagnostics mode=full` over `gateway-plugin/` reported **30
|
||||
blocking errors** and ~47 warnings. Ruff (broad rule set) reported **450**
|
||||
findings. Categories:
|
||||
|
||||
| Category | Count | Severity | Resolution |
|
||||
| --- | --- | --- | --- |
|
||||
| Empty `except: pass` blocks | 14 | blocking | Rewritten as `contextlib.suppress(...)` with a rationale comment (or a `logger.debug` where the swallow is worth tracing). |
|
||||
| Unreachable `except` clause | 2 | blocking | False positive from an over-broad tree-sitter rule, but the two-clause `try` was restructured into a single `except (A, B) as e:` + `isinstance` so the code is unambiguous *and* the rule no longer fires. |
|
||||
| SQL-injection sink (parameterized) | 4 | blocking | False positive — every value is bound via `?` placeholders. Suppressed inline (`pi-lens-ignore: python-sql-injection`) with a justification; the opengrep SQLAlchemy variant (misfiring on raw `sqlite3`) disabled project-wide. |
|
||||
| Hardcoded secret (`token_field`) | 3 | blocking | False positive — `token_field` is a DB *column name* string, not a credential. Suppressed inline. |
|
||||
| Path traversal (`open(path)`) | 1 | blocking | False positive — `path` is produced by hermes `cache_*_from_bytes` (hermes's own media dir), never raw user input. Suppressed inline. |
|
||||
| Unresolved hermes imports | many | blocking (LSP) | Not a code bug — the plugin imports hermes-runtime modules (`websockets`, `gateway.platforms.base`, `hermes_state_search`, …) that live in the read-only `hermes-agent/` tree + its venv. Fixed by adding [`pyrightconfig.json`](../pyrightconfig.json) pointing the Python LSP at that venv + source root. |
|
||||
| `int()`/`float()`/`open()` "unchecked" | 38+ | warning | Noisy heuristic on validated internal data. Disabled project-wide in [`.pi-lens.json`](../.pi-lens.json) (see DECISIONS). |
|
||||
| Logger "credential leak" | 3 | warning | False positive — the word *token* in a log message; the logged values (peer addr, device id, HTTP status) are not secrets. Disabled project-wide. |
|
||||
| Ruff: line length / type annotations / imports / magic values / complexity | 450 | lint | All fixed (see 18.1.3). |
|
||||
| gitleaks (git-ignored paths) | several | warning | Allowlisted in [`.gitleaks.toml`](../.gitleaks.toml) — the hits were the read-only `hermes-agent/` tree, `build/` artifacts, and the standard (git-ignored) `google-services.json`. |
|
||||
|
||||
### 18.1.2 Real bugs fixed
|
||||
|
||||
- **`adapter.py` `interactive_setup` broken imports** (regression, silently masked): the
|
||||
setup flow imported `print_info`/`print_success`/`print_warning`/`prompt` from
|
||||
`hermes_cli.config`, but those live in `hermes_cli.cli_output`; it also imported
|
||||
a `print_code` that does not exist in hermes at all. The whole import block
|
||||
raised `ImportError`, which the surrounding `try/except` swallowed, so
|
||||
`hermes gateway setup` for the iris platform **always bailed out early** with
|
||||
"setup helpers unavailable" and never generated a token or prompted for
|
||||
host/port. Fixed by importing the print helpers from `hermes_cli.cli_output`,
|
||||
the env helpers from `hermes_cli.config`, and dropping the non-existent
|
||||
`print_code` (the pairing URL is printed directly — the app has no QR scanner).
|
||||
This only surfaced once the Python LSP could resolve hermes imports (see
|
||||
`pyrightconfig.json`); before that the unresolved imports masked the bad
|
||||
symbols.
|
||||
- **`adapter.py` `release_scoped_lock` type error**: `self._lock_key` is
|
||||
`str | None` but `release_scoped_lock(scope, identity)` requires `str`. The
|
||||
`if getattr(self, "_lock_key", None):` guard did not narrow the type for the
|
||||
type checker. Fixed by binding to a local `lock_key` and guarding on that.
|
||||
- **`ws_server.py` hello-auth `try`**: the original
|
||||
`except asyncio.TimeoutError: … / except ConnectionClosed: return` was
|
||||
restructured to a single `except (asyncio.TimeoutError, ConnectionClosed) as
|
||||
e:` with an `isinstance` branch. Behavior is identical (timeout → warn +
|
||||
close; clean disconnect → silent return) but the control flow is now
|
||||
unambiguous.
|
||||
- **`ws_server.py` frame-loop `try`**: `except ConnectionClosed: pass /
|
||||
except Exception: warn` became a single `except Exception as e:` that only
|
||||
warns when the error is *not* a clean `ConnectionClosed`. A normal
|
||||
disconnect no longer risks being logged as an error.
|
||||
- **`media.py` `get_upload`**: a refactor of the sibling `create_upload` loop
|
||||
(to drop an unused loop variable) initially removed a `sess` binding that
|
||||
`get_upload` still returned. Caught by ruff (`F821` undefined name) and
|
||||
reverted for that loop only.
|
||||
|
||||
### 18.1.3 Ruff cleanup
|
||||
|
||||
Added [`gateway-plugin/ruff.toml`](../gateway-plugin/ruff.toml) with a broad
|
||||
rule set (`E W F I UP B SIM PL RET C4`) and `line-length = 100`. Changes:
|
||||
|
||||
- **Type annotations**: `typing.Dict/List/Tuple` → builtins; `Optional[X]` →
|
||||
`X | None` (pyupgrade `UP006`/`UP035`/`UP045`).
|
||||
- **Imports**: sorted (isort `I001`); hermes-runtime imports intentionally
|
||||
deferred into function bodies are exempted via `ignore = ["PLC0415"]`
|
||||
(documented in the config).
|
||||
- **Line length**: 115 lines wrapped to ≤ 100 chars (mostly `protocol.error(…)`
|
||||
call sites and log statements).
|
||||
- **Magic values** (`PLR2004`): replaced with named constants —
|
||||
`MAX_MEDIA_REF_LEN`, `_PRUNE_NOTIFY_INTERVAL_S`, `MAX_DEVICE_ID_LEN`,
|
||||
`_HTTP_OK`, `_HTTP_ERROR_MIN`, `_MAX_EXT_LEN`.
|
||||
- **Bugbear** (`B904`): `raise MediaError(…)` inside `except ValueError as e`
|
||||
now uses `raise … from e`.
|
||||
- **Simplify** (`SIM115`): file read in `ws_probe.py` now uses a context
|
||||
manager.
|
||||
- **Complexity** (`PLR0911/0912/0913/0915`): thresholds set just above the
|
||||
current maxima (the adapter is a single large dispatch surface); the lone
|
||||
11-arg frame builder (`protocol.message`) is `noqa`'d with a comment.
|
||||
|
||||
### 18.1.4 Verification
|
||||
|
||||
- `ruff check gateway-plugin` → **All checks passed**.
|
||||
- `pyright gateway-plugin` (with `pyrightconfig.json`) → **0 errors, 0 warnings**.
|
||||
- `scripts/run_tests.sh tests/gateway/test_android.py` → **64/64 passed**.
|
||||
- `python -m compileall gateway-plugin` → clean.
|
||||
- Package-context import of every module (`protocol`, `pairing`, `outbox`,
|
||||
`channels`, `search`, `media`, `push`, `ws_server`, `adapter`) → all OK.
|
||||
- `lens_diagnostics mode=full` → **0 blocking errors**; 20 warnings remain
|
||||
(all `jscpd` code-duplication + 1 `python-thread-global-write`), documented
|
||||
as accepted in 18.1.5.
|
||||
|
||||
### 18.1.5 Accepted warnings (not fixed, with rationale)
|
||||
|
||||
- **`jscpd` duplicates** (18): the SQLite `__init__` boilerplate is repeated
|
||||
across `channels.py`/`outbox.py`/`pairing.py`; the channel-frame handlers in
|
||||
`adapter.py` share a validate→error→respond shape; the FCM/ntfy `send`
|
||||
methods in `push.py` are structurally similar. These are *intentional* —
|
||||
each handler/method is clearer standalone, and the duplication is small.
|
||||
Extracting a base would add indirection for little gain at this scale.
|
||||
- **`python-thread-global-write`** (`adapter.py`): the adapter spawns its
|
||||
asyncio loop on a dedicated thread; shared state is guarded by
|
||||
`asyncio.Lock`/`threading.Lock` as appropriate. The heuristic cannot see the
|
||||
locking, so this is a false positive.
|
||||
|
||||
---
|
||||
|
||||
## 18.2 Iris app — Android (`app/androidApp` + `app/shared`)
|
||||
|
||||
The Iris Android and Desktop apps share the `:shared` KMP module (`commonMain` +
|
||||
`jvmMain`), so most Kotlin code is covered here and in 18.3.
|
||||
|
||||
### 18.2.1 Findings (before)
|
||||
|
||||
- **AndroidX lint** (`:androidApp:lintDebug`): 5 warnings — `ObsoleteSdkInt`,
|
||||
`MonochromeLauncherIcon` (×2), `GradleDependency`, `OldTargetApi`.
|
||||
- **pi-lens** (`lens_diagnostics mode=full`): 3 blocking + 66 warnings.
|
||||
- `detect-insecure-websocket` (blocking ×3): the app's default/placeholder
|
||||
gateway URL is cleartext `ws://`.
|
||||
- `gcm-detection` (×4): AES-GCM usage in `DesktopSecureStore`.
|
||||
- `exported_activity` (×1): the launcher `MainActivity`.
|
||||
- `jscpd` duplicates (many): platform impls, Compose boilerplate, icon XML.
|
||||
|
||||
### 18.2.2 Fixes
|
||||
|
||||
- **Launcher icons consolidated**: `minSdk` is 29 (≥ 26), so the
|
||||
`mipmap-anydpi-v26` / `mipmap-anydpi-v33` variants were merged into a single
|
||||
`mipmap-anydpi` carrying the `<monochrome>` layer (ignored on API < 33, so one
|
||||
file serves all). This cleared both `ObsoleteSdkInt` and `MonochromeLauncherIcon`.
|
||||
- **`core-splashscreen`** bumped 1.0.1 → 1.2.0 (cleared `GradleDependency`).
|
||||
- **`OldTargetApi`**: `targetSdk` is deliberately pinned to 34 (a stable API;
|
||||
the only newer installed platform, 37, is a preview SDK and inappropriate to
|
||||
target for a stable build; the reference device is API 29). Suppressed in the
|
||||
`lint { }` block with a comment.
|
||||
- **Insecure-websocket** (cleartext `ws://`): correct for the default LAN
|
||||
gateway (TLS is optional — a TLS gateway is reached by entering a `wss://`
|
||||
URL). Suppressed inline with a justification; a KDoc/comment that itself
|
||||
contained a literal `ws://` was reworded so it no longer trips the rule.
|
||||
- **GCM** (`DesktopSecureStore`): verified correct — a fresh 12-byte
|
||||
`SecureRandom` IV is generated per write and stored with the ciphertext (never
|
||||
reused for a key). Suppressed inline with a justification.
|
||||
- **Exported activity**: the `MainActivity` is the launcher (LAUNCHER
|
||||
intent-filter) plus deep-link handler, so it *must* be exported. XML doesn't
|
||||
support the `//`/`#` inline-ignore syntax, so the `exported_activity` rule is
|
||||
disabled project-wide in `.pi-lens.json` (the app has exactly one exported
|
||||
activity, the required launcher).
|
||||
|
||||
### 18.2.3 Verification
|
||||
|
||||
- `:shared:allTests` → **BUILD SUCCESSFUL** (all Kotlin tests pass).
|
||||
- `:androidApp:lintDebug` → **0 issues**.
|
||||
- `:androidApp:assembleDebug` → **BUILD SUCCESSFUL**.
|
||||
- Installed on device `a5ca2a4b` (`:androidApp:installDebug`), launched
|
||||
`dev.iris.app/.MainActivity`, screenshot confirms the app connects to the
|
||||
gateway (green status) and renders chat + reasoning blocks.
|
||||
- `lens_diagnostics mode=full` → **0 blocking**; remaining warnings are all
|
||||
`jscpd` code-duplication (intentional — see 18.2.4).
|
||||
|
||||
### 18.2.4 Accepted warnings
|
||||
|
||||
- **`jscpd` duplicates**: the `AndroidMedia`/`DesktopMedia` platform
|
||||
implementations are structurally similar (each is the correct, idiomatic
|
||||
implementation for its platform); the Compose screens share boilerplate
|
||||
(remembered state, coroutine scopes, list-item layouts); the launcher icon
|
||||
XML files are near-identical by design. Extracting shared code would add
|
||||
indirection across source sets for little gain.
|
||||
|
||||
## 18.3 Desktop app (`app/desktopApp`)
|
||||
|
||||
The desktop app is a thin JVM shell (`Main.kt`) over the shared `:shared`
|
||||
module's `desktopMain` source set. It is a **special case**: the user verifies
|
||||
it runs themselves. A live launch **did** surface a real startup crash (below),
|
||||
which this pass fixed and re-verified.
|
||||
|
||||
### 18.3.1 Findings (before)
|
||||
|
||||
- **Startup crash (real bug)**: launching the desktop app threw
|
||||
`java.lang.UnsupportedClassVersionError` — the Markdown rendering stack was
|
||||
compiled for **Java 21** (class file 65.0) but the app runs on **Java 17**
|
||||
(class file 61.0). Two artifacts were affected:
|
||||
- `com.mikepenz:multiplatform-markdown-renderer:0.44.0` (JVM bytecode = Java 21), and
|
||||
- its transitive `dev.snipme:highlights:1.1.0` (also Java 21).
|
||||
The build and unit tests did **not** catch this: compilation reads the
|
||||
metadata fine, and the tests never exercise the Compose Markdown render path
|
||||
that loads those classes. It only failed at runtime on first render.
|
||||
- **pi-lens** (`lens_diagnostics mode=full`): the other desktop-specific
|
||||
findings were the same categories as Android — `gcm-detection` in
|
||||
`DesktopSecureStore.kt` (×4, fixed in 18.2.2) and `jscpd` duplicates in
|
||||
`DesktopMedia.kt` / `Main.kt` (intentional, see 18.2.4).
|
||||
|
||||
### 18.3.2 Resolution
|
||||
|
||||
The crash was resolved by **moving the desktop to a Java 21 runtime** (the user
|
||||
installed JDK 21) rather than downgrading the library — so the app keeps the
|
||||
newest Markdown stack:
|
||||
|
||||
- **`gradle.properties`**: added `org.gradle.java.home` → JDK 21, so the whole
|
||||
build (and the desktop `run` / `jpackage` tasks) use a Java 21 runtime. AGP is
|
||||
JDK-21-compatible, so the **Android build is unaffected** — its bytecode target
|
||||
stays JVM 17 (`minSdk` 29 → Android 10 support is unchanged; that is governed
|
||||
by `minSdk`, not the build JDK).
|
||||
- **`shared/build.gradle.kts`**: the `jvm("desktop")` target now sets
|
||||
`jvmTarget = JVM_21` (the Android target keeps `JVM_17`).
|
||||
- **Markdown restored to `0.44.0`** (from the interim `0.38.1`): its Java-21
|
||||
bytecode (and its `highlights:1.1.0` dependency) now load on the Java 21
|
||||
desktop runtime. The app's Markdown API usage is unchanged.
|
||||
- The GCM ignores in `DesktopSecureStore.kt` (18.2.2) apply to the desktop
|
||||
target.
|
||||
|
||||
> **Note on the interim fix**: the first response to the crash was to downgrade
|
||||
> Markdown to `0.38.1` (the newest version whose bytecode *and* `highlights`
|
||||
> dep are Java 17). Once JDK 21 was available, that was superseded by the
|
||||
> runtime upgrade above, which is preferable (keeps the newest library).
|
||||
|
||||
### 18.3.3 Verification
|
||||
|
||||
- Build now runs on **JDK 21** (`org.gradle.java.home`).
|
||||
- `:desktopApp:build` + `:shared:allTests` + `:androidApp:lintDebug` +
|
||||
`:androidApp:assembleDebug` → all **BUILD SUCCESSFUL** (Android still targets
|
||||
JVM 17 / `minSdk` 29).
|
||||
- **Live launch** (`./gradlew :desktopApp:run`) → starts cleanly on JDK 21,
|
||||
**no `UnsupportedClassVersionError`**, Markdown (0.44.0) renders.
|
||||
- `lens_diagnostics mode=full` → **0 blocking** for desktop files; remaining
|
||||
warnings are `jscpd` code-duplication (intentional).
|
||||
- Packaging config (`jpackage` app-image / `.deb`) reviewed — the KCEF AWT
|
||||
`--add-opens` flags are correctly applied to both the `run` task and the
|
||||
jpackage `--java-options`; `jpackage` now bundles a JDK 21 JRE.
|
||||
|
||||
> **Revisit**: the desktop now requires a **Java 21** runtime (the `run` task
|
||||
> and the jpackage-bundled JRE). If you ever need the desktop to run on Java 17
|
||||
> again, revert `org.gradle.java.home` + the desktop `jvmTarget` to 17 and pin
|
||||
> Markdown to `0.38.1`. Android 10 compatibility is independent of all of this
|
||||
> (it is set by `minSdk = 29`). The known non-fatal `pure virtual method called`
|
||||
> jpackage message on Linux (JDK-8348560) is expected and does not affect the
|
||||
> app.
|
||||
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user