From 4f09bc41bbe3d7c7a153c352df1b3f5cfa6beb87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaroslav=20Bene=C5=A1?= Date: Wed, 21 Oct 2026 13:44:30 +0000 Subject: [PATCH] LLeMbas for Android 0.1.0 (alpha, unreleased): the first commit A native client for a LLeMbas instance on the server's /api/v2, and the phone's digital assistant. - Sign in by device code; the token sealed in the Android Keystore; several instances. - Chats and agent chats: the list, a chat with its reply streaming as JSON server-sent events (reconnecting, whole blocks), thinking, tool calls, steered messages, the plan, jobs, stop, edit, regenerate, continue, the model, effort and Plan mode, attachments and dictation. - Cards in a sheet, answered as the page's form says it; first answer wins. - Notifications through UnifiedPush, no Google services; an approval can be answered from its notification. - The digital assistant: a VoiceInteractionService with its session (a sheet over the current app, "Include screen" off by default), a recognition service through the instance's speech-to-text, the lock-screen path that asks to unlock before sending, a Quick Settings tile and an Ask shortcut. - Share to LLeMbas; Moria and Shire from the server's tokens; nine languages; a self-updater in the `full` flavour, none in `fdroid`. Generated and pinned from the server, each checked in CI: the theme (tokens.lock.json), the contract (contract/lock.json, server 2124ba9), the strings and the icons. Built and tested only on GitHub Actions. Co-Authored-By: Claude Opus 5.5 --- .editorconfig | 22 + .github/workflows/ci.yml | 63 +++ .github/workflows/release.yml | 76 +++ .gitignore | 16 + CHANGELOG.md | 33 ++ LICENSE | 21 + README.md | 55 ++ app/build.gradle.kts | 131 +++++ app/proguard-rules.pro | 19 + app/src/full/AndroidManifest.xml | 10 + app/src/main/AndroidManifest.xml | 127 +++++ .../main/java/eu/llembas/android/LembasApp.kt | 33 ++ .../java/eu/llembas/android/MainActivity.kt | 116 ++++ .../java/eu/llembas/android/api/ApiClient.kt | 270 +++++++++ .../java/eu/llembas/android/api/LiveReply.kt | 72 +++ .../java/eu/llembas/android/api/Models.kt | 348 ++++++++++++ .../eu/llembas/android/api/StreamClient.kt | 86 +++ .../llembas/android/assist/AskTileService.kt | 22 + .../llembas/android/assist/AssistActivity.kt | 105 ++++ .../android/assist/AssistController.kt | 155 ++++++ .../eu/llembas/android/assist/AssistPanel.kt | 120 ++++ .../llembas/android/assist/AssistService.kt | 151 +++++ .../assist/LembasRecognitionService.kt | 83 +++ .../java/eu/llembas/android/assist/Voice.kt | 136 +++++ .../java/eu/llembas/android/auth/Instances.kt | 129 +++++ .../main/java/eu/llembas/android/push/Push.kt | 173 ++++++ .../eu/llembas/android/share/ShareActivity.kt | 109 ++++ .../java/eu/llembas/android/ui/Markdown.kt | 79 +++ .../java/eu/llembas/android/ui/chat/Blocks.kt | 217 ++++++++ .../java/eu/llembas/android/ui/chat/Cards.kt | 223 ++++++++ .../eu/llembas/android/ui/chat/ChatScreen.kt | 388 +++++++++++++ .../llembas/android/ui/chat/ChatViewModel.kt | 246 +++++++++ .../llembas/android/ui/chats/ChatsScreen.kt | 214 +++++++ .../android/ui/settings/SettingsScreen.kt | 172 ++++++ .../llembas/android/ui/signin/SignInScreen.kt | 187 +++++++ .../java/eu/llembas/android/ui/theme/Theme.kt | 60 ++ .../eu/llembas/android/ui/theme/Tokens.kt | 91 +++ .../java/eu/llembas/android/update/Updater.kt | 136 +++++ .../res/drawable/ic_launcher_foreground.xml | 13 + .../res/drawable/ic_launcher_monochrome.xml | 9 + app/src/main/res/drawable/ic_notification.xml | 7 + .../res/mipmap-anydpi-v26/ic_launcher.xml | 6 + app/src/main/res/values-cs/strings.xml | 99 ++++ app/src/main/res/values-de/strings.xml | 99 ++++ app/src/main/res/values-es/strings.xml | 99 ++++ app/src/main/res/values-fr/strings.xml | 99 ++++ app/src/main/res/values-hu/strings.xml | 99 ++++ app/src/main/res/values-it/strings.xml | 99 ++++ app/src/main/res/values-pl/strings.xml | 99 ++++ app/src/main/res/values-sk/strings.xml | 99 ++++ app/src/main/res/values/colors.xml | 5 + app/src/main/res/values/strings.xml | 100 ++++ app/src/main/res/values/themes.xml | 15 + app/src/main/res/xml/assist_service.xml | 11 + .../main/res/xml/data_extraction_rules.xml | 17 + .../main/res/xml/network_security_config.xml | 13 + app/src/main/res/xml/recognition_service.xml | 3 + app/src/main/res/xml/shortcuts.xml | 13 + .../java/eu/llembas/android/ClientTest.kt | 64 +++ .../java/eu/llembas/android/ContractTest.kt | 100 ++++ .../java/eu/llembas/android/LiveReplyTest.kt | 48 ++ .../eu/llembas/android/SmallThingsTest.kt | 34 ++ build.gradle.kts | 6 + contract/chat.json | 18 + contract/chat_agent.json | 21 + contract/event_ask.json | 127 +++++ contract/event_ask_empty.json | 3 + contract/event_canvas.json | 9 + contract/event_close.json | 1 + contract/event_done.json | 94 ++++ contract/event_jobs.json | 21 + contract/event_metrics.json | 13 + contract/event_plan.json | 32 ++ contract/event_status.json | 3 + contract/event_steered.json | 5 + contract/event_steps.json | 61 ++ contract/event_tail.json | 5 + contract/lock.json | 5 + contract/message_assistant.json | 87 +++ contract/message_user.json | 14 + contract/version.json | 1 + gradle.properties | 5 + gradle/libs.versions.toml | 50 ++ gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 43764 bytes gradle/wrapper/gradle-wrapper.properties | 8 + gradlew | 251 +++++++++ gradlew.bat | 94 ++++ scripts/fetch-contract.py | 64 +++ scripts/fetch-tokens.py | 128 +++++ scripts/gen-icons.py | 81 +++ scripts/gen-strings.py | 91 +++ scripts/hygiene.sh | 29 + scripts/strings.py | 116 ++++ scripts/strings_own.json | 522 ++++++++++++++++++ settings.gradle.kts | 18 + tokens.lock.json | 5 + 96 files changed, 7932 insertions(+) create mode 100644 .editorconfig create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/release.yml create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 app/build.gradle.kts create mode 100644 app/proguard-rules.pro create mode 100644 app/src/full/AndroidManifest.xml create mode 100644 app/src/main/AndroidManifest.xml create mode 100644 app/src/main/java/eu/llembas/android/LembasApp.kt create mode 100644 app/src/main/java/eu/llembas/android/MainActivity.kt create mode 100644 app/src/main/java/eu/llembas/android/api/ApiClient.kt create mode 100644 app/src/main/java/eu/llembas/android/api/LiveReply.kt create mode 100644 app/src/main/java/eu/llembas/android/api/Models.kt create mode 100644 app/src/main/java/eu/llembas/android/api/StreamClient.kt create mode 100644 app/src/main/java/eu/llembas/android/assist/AskTileService.kt create mode 100644 app/src/main/java/eu/llembas/android/assist/AssistActivity.kt create mode 100644 app/src/main/java/eu/llembas/android/assist/AssistController.kt create mode 100644 app/src/main/java/eu/llembas/android/assist/AssistPanel.kt create mode 100644 app/src/main/java/eu/llembas/android/assist/AssistService.kt create mode 100644 app/src/main/java/eu/llembas/android/assist/LembasRecognitionService.kt create mode 100644 app/src/main/java/eu/llembas/android/assist/Voice.kt create mode 100644 app/src/main/java/eu/llembas/android/auth/Instances.kt create mode 100644 app/src/main/java/eu/llembas/android/push/Push.kt create mode 100644 app/src/main/java/eu/llembas/android/share/ShareActivity.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/Markdown.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/chat/Blocks.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/chat/Cards.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/chats/ChatsScreen.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/signin/SignInScreen.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/theme/Theme.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/theme/Tokens.kt create mode 100644 app/src/main/java/eu/llembas/android/update/Updater.kt create mode 100644 app/src/main/res/drawable/ic_launcher_foreground.xml create mode 100644 app/src/main/res/drawable/ic_launcher_monochrome.xml create mode 100644 app/src/main/res/drawable/ic_notification.xml create mode 100644 app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml create mode 100644 app/src/main/res/values-cs/strings.xml create mode 100644 app/src/main/res/values-de/strings.xml create mode 100644 app/src/main/res/values-es/strings.xml create mode 100644 app/src/main/res/values-fr/strings.xml create mode 100644 app/src/main/res/values-hu/strings.xml create mode 100644 app/src/main/res/values-it/strings.xml create mode 100644 app/src/main/res/values-pl/strings.xml create mode 100644 app/src/main/res/values-sk/strings.xml create mode 100644 app/src/main/res/values/colors.xml create mode 100644 app/src/main/res/values/strings.xml create mode 100644 app/src/main/res/values/themes.xml create mode 100644 app/src/main/res/xml/assist_service.xml create mode 100644 app/src/main/res/xml/data_extraction_rules.xml create mode 100644 app/src/main/res/xml/network_security_config.xml create mode 100644 app/src/main/res/xml/recognition_service.xml create mode 100644 app/src/main/res/xml/shortcuts.xml create mode 100644 app/src/test/java/eu/llembas/android/ClientTest.kt create mode 100644 app/src/test/java/eu/llembas/android/ContractTest.kt create mode 100644 app/src/test/java/eu/llembas/android/LiveReplyTest.kt create mode 100644 app/src/test/java/eu/llembas/android/SmallThingsTest.kt create mode 100644 build.gradle.kts create mode 100644 contract/chat.json create mode 100644 contract/chat_agent.json create mode 100644 contract/event_ask.json create mode 100644 contract/event_ask_empty.json create mode 100644 contract/event_canvas.json create mode 100644 contract/event_close.json create mode 100644 contract/event_done.json create mode 100644 contract/event_jobs.json create mode 100644 contract/event_metrics.json create mode 100644 contract/event_plan.json create mode 100644 contract/event_status.json create mode 100644 contract/event_steered.json create mode 100644 contract/event_steps.json create mode 100644 contract/event_tail.json create mode 100644 contract/lock.json create mode 100644 contract/message_assistant.json create mode 100644 contract/message_user.json create mode 100644 contract/version.json create mode 100644 gradle.properties create mode 100644 gradle/libs.versions.toml create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100755 gradlew create mode 100644 gradlew.bat create mode 100755 scripts/fetch-contract.py create mode 100755 scripts/fetch-tokens.py create mode 100755 scripts/gen-icons.py create mode 100755 scripts/gen-strings.py create mode 100755 scripts/hygiene.sh create mode 100755 scripts/strings.py create mode 100644 scripts/strings_own.json create mode 100644 settings.gradle.kts create mode 100644 tokens.lock.json diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..a9624e6 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,22 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 + +[*.{kt,kts}] +ktlint_code_style = intellij_idea +max_line_length = 160 +# Compose functions are named like types. +ktlint_function_naming_ignore_when_annotated_with = Composable +ktlint_standard_no-wildcard-imports = enabled +ktlint_standard_filename = disabled + +[*.{xml,json,yml,toml}] +indent_size = 2 + +[*.py] +max_line_length = 100 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..a20fd1c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,63 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + check: + runs-on: ubuntu-24.04 + timeout-minutes: 40 + steps: + - uses: actions/checkout@v4 + + - name: Nothing private in the repository + run: scripts/hygiene.sh + + - name: Generated files match their sources + run: | + python3 scripts/fetch-tokens.py # Tokens.kt matches tokens.lock.json + python3 scripts/fetch-contract.py # contract/ matches contract/lock.json + python3 scripts/gen-strings.py --check + + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 17 + + - name: ktlint (signature-checked) + run: | + curl -sSfL -o ktlint https://github.com/pinterest/ktlint/releases/download/1.8.0/ktlint + echo "a3fd620207d5c40da6ca789b95e7f823c54e854b7fade7f613e91096a3706d75 ktlint" | sha256sum -c + chmod +x ktlint + ./ktlint "app/src/**/*.kt" "*.kts" "app/*.kts" + + - uses: gradle/actions/wrapper-validation@v4 + + - uses: gradle/actions/setup-gradle@v4 + + - name: Unit tests and both builds + run: ./gradlew --no-daemon testFullDebugUnitTest assembleFullDebug assembleFdroidDebug + + - name: Android lint (report only, for now) + run: ./gradlew --no-daemon lintFullDebug + continue-on-error: true + + - uses: actions/upload-artifact@v4 + with: + name: llembas-android-debug + path: app/build/outputs/apk/*/debug/*.apk + if-no-files-found: error + + - uses: actions/upload-artifact@v4 + if: always() + with: + name: reports + path: | + app/build/reports/ + app/build/test-results/ + if-no-files-found: ignore diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..a63cc63 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,76 @@ +name: Release + +# A signed tag `vX.Y.Z` builds both flavours, signed with the release key from the secrets, +# and publishes them with SHA256SUMS as the GitHub Release. The release notes are the tag's +# message. The key never touches the repository: it is written to a temporary file here and +# deleted with the runner. +on: + push: + tags: ["v*"] + workflow_dispatch: + inputs: + tag: + description: Tag to build + required: true + +permissions: + contents: write + +jobs: + release: + runs-on: ubuntu-24.04 + timeout-minutes: 40 + env: + TAG: ${{ github.event.inputs.tag || github.ref_name }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ env.TAG }} + + - name: The tag object, for its message + run: git fetch --force origin "refs/tags/$TAG:refs/tags/$TAG" + + - name: The version is the tag + run: | + version="$(sed -n -E 's/^ *versionName = "([^"]+)".*/\1/p' app/build.gradle.kts)" + [ "v$version" = "$TAG" ] || { echo "versionName $version is not $TAG" >&2; exit 1; } + echo "VERSION=$version" >> "$GITHUB_ENV" + + - run: scripts/hygiene.sh + + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 17 + + - uses: gradle/actions/wrapper-validation@v4 + + - uses: gradle/actions/setup-gradle@v4 + + - name: Build, signed + env: + KEYSTORE_B64: ${{ secrets.LEMBAS_KEYSTORE_B64 }} + LEMBAS_KEYSTORE_PASSWORD: ${{ secrets.LEMBAS_KEYSTORE_PASSWORD }} + LEMBAS_KEY_ALIAS: ${{ secrets.LEMBAS_KEY_ALIAS }} + LEMBAS_KEY_PASSWORD: ${{ secrets.LEMBAS_KEY_PASSWORD }} + run: | + [ -n "$KEYSTORE_B64" ] || { echo "no release key in the secrets" >&2; exit 1; } + export LEMBAS_KEYSTORE="$RUNNER_TEMP/release.jks" + echo "$KEYSTORE_B64" | base64 -d > "$LEMBAS_KEYSTORE" + ./gradlew --no-daemon testFullReleaseUnitTest assembleFullRelease assembleFdroidRelease + rm -f "$LEMBAS_KEYSTORE" + + - name: Name the files and sum them + run: | + mkdir dist + cp app/build/outputs/apk/full/release/app-full-release.apk "dist/llembas-android-$VERSION.apk" + cp app/build/outputs/apk/fdroid/release/app-fdroid-release.apk "dist/llembas-android-$VERSION-fdroid.apk" + { echo "# llembas-android $VERSION"; (cd dist && sha256sum *.apk); } > SHA256SUMS + mv SHA256SUMS dist/ + + - name: Publish + env: + GH_TOKEN: ${{ github.token }} + run: | + git tag -l --format='%(contents)' "$TAG" | sed '/-----BEGIN SSH SIGNATURE-----/,$d' > notes.md + gh release create "$TAG" --verify-tag --title "LLeMbas for Android $VERSION" --notes-file notes.md dist/* diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e2437af --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +# Gradle and Android build output +.gradle/ +build/ +/app/build/ +local.properties +*.apk +*.aab +# A release key never goes in the repository (CI writes it from secrets) +*.jks +*.keystore +# IDEs +.idea/ +*.iml +.kotlin/ +# Python +__pycache__/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..c2572f2 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,33 @@ +# Changelog + +What changed in each release of LLeMbas for Android. Versions follow SemVer; until 1.0.0 the app +is in alpha and releases come off `main`. + +## [Unreleased] + +## [0.1.0] — unreleased + +The first version: a native client for a LLeMbas instance (server 1.7.0 or newer), and the +phone's digital assistant. + +### Added + +- **Sign in by device code**, as the LLeMbas CLI does: type the instance's address, approve the + code in the browser. The token is sealed with a key in the Android Keystore. Several instances, + one in use at a time. +- **Chats and agent chats**: the list (archive by swiping), a chat with its reply streaming in -- + thinking, tool calls with their output behind a tap, edits, steered messages -- the plan, the + background jobs, stop, edit, regenerate, continue, carrying out a plan, the model, effort and + Plan mode. Attachments from the phone, and dictation through the instance's speech-to-text. +- **Cards**: approvals (once, always, deny with a reason, a corrected command), questions and + plans are answered in a sheet. First answer wins -- on the phone, the web page or the device. +- **Notifications through UnifiedPush**, with no Google services: a finished reply, a card + waiting with nobody watching (an approval can be answered from the notification), a report. +- **The digital assistant**: choose LLeMbas under Default apps › Digital assistant app, and + holding the power button (or the assist gesture) opens a sheet over whatever is on screen. + Ask by typing or by voice; a spoken question is answered aloud. "Include screen" sends the + screen's text, or a screenshot, with the question -- off until turned on. Over the lock screen + it asks to unlock before sending anything. Also a Quick Settings tile and an "Ask" shortcut. +- **Share to LLeMbas**: text, links, pictures and files from any app start a chat. +- **Moria and Shire**, generated from the server's own design tokens; nine languages. +- **Updates itself** from llembas.eu (the `full` build); the `fdroid` build leaves that to F-Droid. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..fc2a71d --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Jaroslav Beneš + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..ecdc815 --- /dev/null +++ b/README.md @@ -0,0 +1,55 @@ +# LLeMbas for Android + +A native Android app for a [LLeMbas](https://github.com/LLeMbas/LLeMbas) instance: your chats +and agent chats, notifications that arrive when the app is closed, and LLeMbas as the phone's +digital assistant -- hold the power button and ask. + +- **Native, not a web view.** Kotlin and Jetpack Compose on the server's JSON API (`/api/v2`). + The installable web app keeps working; this is for what a web page on a phone cannot do. +- **No Google services.** Notifications come through [UnifiedPush](https://unifiedpush.org) + (ntfy, or any distributor you like), so the app runs on de-Googled phones and builds for F-Droid. +- **Your instance, nobody else's.** Nothing is predefined: the app talks to the address you give + it, and to nothing else. + +> **Alpha.** 0.x versions may change how things work between releases. + +## Install + +Download the APK from the [latest release](https://github.com/LLeMbas/LLeMbas-Android/releases/latest) +and check it against `SHA256SUMS`. The `full` APK updates itself from llembas.eu; the `-fdroid` +one does not. Android 10 or newer; the instance must run LLeMbas server 1.7.0 or newer. + +If your instance uses a certificate from your own certificate authority, install that CA on the +phone first (Settings › Security › Encryption & credentials › Install a certificate › CA +certificate). The app trusts CAs you installed, as the browser does. + +## Use + +- **Sign in**: type the instance's address and approve the code shown, in the browser. +- **Notifications**: install a UnifiedPush distributor (for example ntfy), then Settings › + Notifications › Turn notifications on. +- **Assistant**: Settings › Assistant › Open the assistant settings, and choose LLeMbas as the + digital assistant app. On Samsung phones also set Settings › Advanced features › Side button › + Press and hold › Digital assistant. + +There is no wake word. Android reserves always-on hotword detection for the system's own +preinstalled assistant; no app from outside can use it. + +## Build + +Builds run on GitHub Actions (`.github/workflows/ci.yml`); locally it is the usual +`./gradlew assembleFullDebug` with JDK 17 and the Android SDK. + +Three things are generated from the server and pinned, each with a lock file CI checks: + +| What | Script | From the server | +|---|---|---| +| `ui/theme/Tokens.kt` | `scripts/fetch-tokens.py ` | `tokens.css` | +| `contract/*.json` | `scripts/fetch-contract.py ` | `tests/fixtures/api_v2/` | +| `res/values*/strings.xml` | `scripts/gen-strings.py` | the translation catalogues | + +The icons come from the server's pixel leaf (`scripts/gen-icons.py`). + +## Licence + +MIT -- see [LICENSE](LICENSE). diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..a569bfd --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,131 @@ +import java.util.Properties + +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.android) + alias(libs.plugins.kotlin.compose) + alias(libs.plugins.kotlin.serialization) +} + +// The release key is never in the repository. CI writes it from secrets into a file named by +// LEMBAS_KEYSTORE; a build without one is unsigned (debug builds use the debug key as always). +val releaseKey: Properties? = + System.getenv("LEMBAS_KEYSTORE")?.takeIf { it.isNotBlank() }?.let { + Properties().apply { + setProperty("file", it) + setProperty("password", System.getenv("LEMBAS_KEYSTORE_PASSWORD") ?: "") + setProperty("alias", System.getenv("LEMBAS_KEY_ALIAS") ?: "release") + setProperty("keyPassword", System.getenv("LEMBAS_KEY_PASSWORD") ?: "") + } + } + +android { + namespace = "eu.llembas.android" + compileSdk = 36 + + defaultConfig { + applicationId = "eu.llembas.android" + minSdk = 29 + targetSdk = 36 + // The one source of the version. versionCode is derived from it, so the two cannot + // drift: 0.1.0 -> 100, 1.2.3 -> 10203. + versionName = "0.1.0" + versionCode = versionName!!.split(".").map { it.toInt() }.let { (a, b, c) -> + a * 10000 + b * 100 + c + } + } + + signingConfigs { + releaseKey?.let { key -> + create("release") { + storeFile = file(key.getProperty("file")) + storePassword = key.getProperty("password") + keyAlias = key.getProperty("alias") + keyPassword = key.getProperty("keyPassword") + } + } + } + + buildTypes { + release { + isMinifyEnabled = true + isShrinkResources = true + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + signingConfig = signingConfigs.findByName("release") + } + debug { + applicationIdSuffix = ".debug" + versionNameSuffix = "-debug" + } + } + + // `full` updates itself from llembas.eu; `fdroid` has no updater, because F-Droid updates it. + flavorDimensions += "distribution" + productFlavors { + create("full") { + dimension = "distribution" + buildConfigField("boolean", "SELF_UPDATE", "true") + } + create("fdroid") { + dimension = "distribution" + buildConfigField("boolean", "SELF_UPDATE", "false") + } + } + + buildFeatures { + compose = true + buildConfig = true + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + dependenciesInfo { + // No Google-signed dependency blob in the APK: F-Droid refuses it, and nobody reads it. + includeInApk = false + includeInBundle = false + } + + testOptions { + unitTests.isReturnDefaultValues = true + } + + sourceSets { + // The server's contract, pinned by scripts/fetch-contract.py, read by the unit tests. + getByName("test").resources.srcDir(rootProject.file("contract")) + } +} + +kotlin { + jvmToolchain(17) +} + +dependencies { + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.activity.compose) + implementation(libs.androidx.lifecycle.runtime.compose) + implementation(libs.androidx.lifecycle.viewmodel.compose) + implementation(libs.androidx.lifecycle.service) + implementation(libs.androidx.navigation.compose) + implementation(libs.androidx.datastore.preferences) + implementation(libs.androidx.browser) + implementation(platform(libs.compose.bom)) + implementation(libs.compose.ui) + implementation(libs.compose.ui.tooling.preview) + implementation(libs.compose.material3) + implementation(libs.compose.material.icons) + implementation(libs.okhttp) + implementation(libs.okhttp.sse) + implementation(libs.kotlinx.serialization.json) + implementation(libs.kotlinx.coroutines.android) + implementation(libs.markwon.core) + implementation(libs.markwon.tables) + implementation(libs.markwon.strikethrough) + implementation(libs.unifiedpush.connector) + + testImplementation(libs.junit) + testImplementation(libs.kotlinx.coroutines.test) + testImplementation(libs.okhttp.mockwebserver) +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..1e24cd4 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,19 @@ +# kotlinx.serialization: keep the generated serializers of the API models. +-keepattributes *Annotation*, InnerClasses +-dontnote kotlinx.serialization.** +-keepclassmembers class eu.llembas.android.api.** { + *** Companion; +} +-keepclasseswithmembers class eu.llembas.android.api.** { + kotlinx.serialization.KSerializer serializer(...); +} +-keep,includedescriptorclasses class eu.llembas.android.api.**$$serializer { *; } + +# Markwon references optional classes it does not need here. +-dontwarn org.commonmark.ext.gfm.strikethrough.** +-dontwarn io.noties.markwon.** + +# OkHttp's optional TLS providers. +-dontwarn org.conscrypt.** +-dontwarn org.bouncycastle.** +-dontwarn org.openjsse.** diff --git a/app/src/full/AndroidManifest.xml b/app/src/full/AndroidManifest.xml new file mode 100644 index 0000000..e50999a --- /dev/null +++ b/app/src/full/AndroidManifest.xml @@ -0,0 +1,10 @@ + + + + + + + + diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..c4b91d3 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/java/eu/llembas/android/LembasApp.kt b/app/src/main/java/eu/llembas/android/LembasApp.kt new file mode 100644 index 0000000..f935cb5 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/LembasApp.kt @@ -0,0 +1,33 @@ +package eu.llembas.android + +import android.app.Application +import android.app.NotificationChannel +import android.app.NotificationManager +import eu.llembas.android.auth.InstanceStore + +/** The process: one store of instances, and the notification channels, made once. */ +class LembasApp : Application() { + lateinit var instances: InstanceStore + private set + + override fun onCreate() { + super.onCreate() + instances = InstanceStore(this) + val manager = getSystemService(NotificationManager::class.java) + manager.createNotificationChannels( + listOf( + NotificationChannel(CHANNEL_REPLIES, getString(R.string.channel_replies), NotificationManager.IMPORTANCE_DEFAULT), + NotificationChannel(CHANNEL_ASKS, getString(R.string.channel_asks), NotificationManager.IMPORTANCE_HIGH), + NotificationChannel(CHANNEL_REPORTS, getString(R.string.channel_reports), NotificationManager.IMPORTANCE_LOW), + ), + ) + } + + companion object { + const val CHANNEL_REPLIES = "replies" + const val CHANNEL_ASKS = "asks" + const val CHANNEL_REPORTS = "reports" + } +} + +val android.content.Context.lembas: LembasApp get() = applicationContext as LembasApp diff --git a/app/src/main/java/eu/llembas/android/MainActivity.kt b/app/src/main/java/eu/llembas/android/MainActivity.kt new file mode 100644 index 0000000..4480886 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/MainActivity.kt @@ -0,0 +1,116 @@ +package eu.llembas.android + +import android.Manifest +import android.content.Intent +import android.content.pm.PackageManager +import android.os.Build +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.Surface +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.core.content.ContextCompat +import androidx.navigation.compose.NavHost +import androidx.navigation.compose.composable +import androidx.navigation.compose.rememberNavController +import eu.llembas.android.auth.Instance +import eu.llembas.android.auth.Prefs +import eu.llembas.android.push.Notifications +import eu.llembas.android.ui.chat.ChatScreen +import eu.llembas.android.ui.chats.ChatsScreen +import eu.llembas.android.ui.settings.SettingsScreen +import eu.llembas.android.ui.signin.SignInScreen +import eu.llembas.android.ui.theme.LembasTheme +import kotlinx.coroutines.flow.map + +private data class Loaded(val instance: Instance?) + +class MainActivity : ComponentActivity() { + /** A chat a notification, the assistant or a share asked to open; consumed once. */ + private val opening = mutableStateOf(null) + + override fun onCreate(savedInstanceState: Bundle?) { + enableEdgeToEdge() + super.onCreate(savedInstanceState) + take(intent) + if (Build.VERSION.SDK_INT >= 33 && + ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED + ) { + requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1) + } + setContent { + val prefs by lembas.instances.prefs.collectAsState(initial = Prefs()) + LembasTheme(prefs.theme) { + Surface(Modifier.fillMaxSize()) { Root(opening.value) { opening.value = null } } + } + } + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + take(intent) + } + + private fun take(intent: Intent?) { + intent?.getStringExtra(Notifications.EXTRA_CHAT)?.let { opening.value = it } + } + + @Composable + private fun Root(open: String?, opened: () -> Unit) { + // null while the store is read; then the instance in use, which may be none. + val loaded by remember { lembas.instances.active.map { Loaded(it) } }.collectAsState(initial = null) + val instance = loaded?.instance + when { + loaded == null -> Box(Modifier.fillMaxSize()) + + instance == null -> SignInScreen() + + else -> key(instance.id) { + val nav = rememberNavController() + LaunchedEffect(open) { + open?.let { + nav.navigate("chat/$it") + opened() + } + } + NavHost(nav, startDestination = "chats") { + composable("chats") { + ChatsScreen( + onOpen = { nav.navigate("chat/$it") }, + onNew = { nav.navigate("new") }, + onSettings = { nav.navigate("settings") }, + ) + } + composable("new") { + ChatScreen( + chatId = null, + onBack = { nav.popBackStack() }, + onOpened = { id -> + nav.navigate("chat/$id") { popUpTo("new") { inclusive = true } } + }, + ) + } + composable("chat/{id}") { entry -> + ChatScreen(chatId = entry.arguments?.getString("id"), onBack = { nav.popBackStack() }) + } + composable("settings") { + SettingsScreen(onBack = { nav.popBackStack() }, onAddInstance = { nav.navigate("add") }) + } + // Signing in to one more instance makes it the one in use, which starts a + // fresh navigation for it (the `key` above). + composable("add") { SignInScreen(onDone = { nav.popBackStack("chats", inclusive = false) }) } + } + } + } + } +} diff --git a/app/src/main/java/eu/llembas/android/api/ApiClient.kt b/app/src/main/java/eu/llembas/android/api/ApiClient.kt new file mode 100644 index 0000000..c3e64d6 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/api/ApiClient.kt @@ -0,0 +1,270 @@ +package eu.llembas.android.api + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withContext +import kotlinx.serialization.KSerializer +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put +import kotlinx.serialization.serializer +import okhttp3.Call +import okhttp3.Callback +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.MultipartBody +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody +import okhttp3.RequestBody.Companion.toRequestBody +import okhttp3.Response +import java.io.IOException +import java.util.concurrent.TimeUnit +import kotlin.coroutines.resumeWithException + +/** A refusal from the server, in its own words (`{"detail": "…"}`). */ +class ApiException(val status: Int, message: String) : IOException(message) + +private val JSON = "application/json; charset=utf-8".toMediaType() + +/** One HTTP client for the whole app: one connection pool, one TLS setup. */ +val SharedHttp: OkHttpClient by lazy { + OkHttpClient.Builder() + .connectTimeout(15, TimeUnit.SECONDS) + .readTimeout(60, TimeUnit.SECONDS) + .writeTimeout(120, TimeUnit.SECONDS) + .build() +} + +suspend fun Call.await(): Response = suspendCancellableCoroutine { cont -> + enqueue( + object : Callback { + override fun onResponse(call: Call, response: Response) = cont.resumeWith(Result.success(response)) + + override fun onFailure(call: Call, e: IOException) { + if (!cont.isCancelled) cont.resumeWithException(e) + } + }, + ) + cont.invokeOnCancellation { runCatching { cancel() } } +} + +/** The address a person typed, as the instance's base URL: https assumed, no trailing slash. */ +fun normaliseBase(typed: String): String { + var text = typed.trim().trimEnd('/') + if (!text.startsWith("http://") && !text.startsWith("https://")) text = "https://$text" + return text.toHttpUrl().toString().trimEnd('/') +} + +/** The calls that need no token: finding the instance and signing in. */ +class Doorstep(private val http: OkHttpClient = SharedHttp) { + suspend fun discover(base: String): Discovery { + val response = http.newCall(Request.Builder().url("$base/.well-known/lembas.json").build()).await() + return response.use { + if (!it.isSuccessful) throw ApiException(it.code, "Not a LLeMbas instance (${it.code}).") + LembasJson.decodeFromString(Discovery.serializer(), it.body!!.string()) + } + } + + suspend fun deviceCode(url: String, deviceName: String, model: String): DeviceCode { + val body = buildJsonObject { + put("scope", "app models") + put("client_id", "lembas-android") + put("device_name", deviceName) + put("device_host", model) + put("device_platform", "android") + } + val response = http.newCall(post(url, body)).await() + return response.use { + if (!it.isSuccessful) throw ApiException(it.code, detail(it)) + LembasJson.decodeFromString(DeviceCode.serializer(), it.body!!.string()) + } + } + + /** One poll. A pending login is a 400 with `authorization_pending` -- not a failure. */ + suspend fun deviceToken(url: String, deviceCode: String): DeviceToken { + val body = buildJsonObject { + put("grant_type", "urn:ietf:params:oauth:grant-type:device_code") + put("device_code", deviceCode) + } + val response = http.newCall(post(url, body)).await() + return response.use { LembasJson.decodeFromString(DeviceToken.serializer(), it.body!!.string()) } + } + + private fun post(url: String, body: JsonObject) = Request.Builder().url(url).post(body.toString().toRequestBody(JSON)).build() +} + +internal fun detail(response: Response): String { + val text = runCatching { response.body?.string().orEmpty() }.getOrDefault("") + val said = runCatching { + LembasJson.parseToJsonElement(text).let { it as JsonObject }["detail"]?.jsonPrimitive?.content + }.getOrNull() + return said ?: "The server answered ${response.code}." +} + +/** + * Everything the app asks one instance, with its token. Every call is the server's + * `/api/v2` (or `/v1` for speech), and every refusal comes back as an [ApiException] + * carrying the server's own sentence, which is what the app shows. + */ +class ApiClient(val base: String, private val token: String, val http: OkHttpClient = SharedHttp) { + private val v2 = "$base/api/v2" + + fun authed(url: String): Request.Builder = Request.Builder().url(url).header("Authorization", "Bearer $token").header("Accept", "application/json") + + private suspend fun call(request: Request, serializer: KSerializer): T = withContext(Dispatchers.IO) { + http.newCall(request).await().use { response -> + if (!response.isSuccessful) throw ApiException(response.code, detail(response)) + LembasJson.decodeFromString(serializer, response.body!!.string()) + } + } + + private suspend fun empty(request: Request) = withContext(Dispatchers.IO) { + http.newCall(request).await().use { response -> + if (!response.isSuccessful) throw ApiException(response.code, detail(response)) + } + } + + private suspend inline fun get(path: String): T = call(authed("$v2$path").get().build(), serializer()) + + private suspend inline fun send(method: String, path: String, body: JsonObject?): T = + call(authed("$v2$path").method(method, (body ?: JsonObject(emptyMap())).toString().toRequestBody(JSON)).build(), serializer()) + + // --- Account ----------------------------------------------------------------------------- + suspend fun me(): Me = get("/me") + + suspend fun models(chatId: String? = null): List = get(if (chatId != null) "/models?chat=$chatId" else "/models").models + + suspend fun folders(): List = get("/folders").folders + + suspend fun devices(): List = get("/devices").devices + + /** The token revokes itself (`lembas logout`'s route). */ + suspend fun signOut() = empty(authed("$base/api/v1/token").delete().build()) + + // --- Chats ------------------------------------------------------------------------------- + suspend fun chats(kind: String = "", archived: Boolean = false, before: String? = null): ChatPage { + val url = "$v2/chats".toHttpUrl().newBuilder() + .addQueryParameter("archived", archived.toString()) + .apply { if (kind.isNotEmpty()) addQueryParameter("kind", kind) } + .apply { before?.let { addQueryParameter("before", it) } } + .build() + return call(authed(url.toString()).get().build(), ChatPage.serializer()) + } + + suspend fun unread(): List = get("/chats/unread").unread + + suspend fun chat(id: String): ChatDetail = get("/chats/$id") + + suspend fun messages(chatId: String, before: String): MessagePage = get("/chats/$chatId/messages?before=$before") + + suspend fun createChat( + text: String, + attachments: List = emptyList(), + model: String? = null, + temporary: Boolean = false, + effort: String? = null, + mode: String? = null, + ): NewChat = send( + "POST", + "/chats", + buildJsonObject { + put("text", text) + put("attachments", JsonArray(attachments.map { JsonPrimitive(it) })) + model?.let { put("model", it) } + effort?.let { put("effort", it) } + mode?.let { put("mode", it) } + put("temporary", temporary) + }, + ) + + suspend fun sendMessage(chatId: String, text: String, attachments: List = emptyList()): Turn = send( + "POST", + "/chats/$chatId/messages", + buildJsonObject { + put("text", text) + put("attachments", JsonArray(attachments.map { JsonPrimitive(it) })) + }, + ) + + suspend fun updateChat(chatId: String, changes: JsonObject): Chat = send("PATCH", "/chats/$chatId", changes).chat + + suspend fun deleteChat(chatId: String) = empty(authed("$v2/chats/$chatId").delete().build()) + + suspend fun stop(chatId: String, messageId: String) = + empty(authed("$v2/chats/$chatId/messages/$messageId/stop").post(ByteArray(0).toRequestBody(null)).build()) + + suspend fun edit(chatId: String, messageId: String, text: String): Turn = + send("POST", "/chats/$chatId/messages/$messageId/edit", buildJsonObject { put("text", text) }) + + suspend fun regenerate(chatId: String, messageId: String): Turn = send("POST", "/chats/$chatId/messages/$messageId/regenerate", null) + + suspend fun continueChat(chatId: String): Turn = send("POST", "/chats/$chatId/continue", null) + + suspend fun executePlan(chatId: String): Turn = send("POST", "/chats/$chatId/plan/execute", null) + + suspend fun answer(chatId: String, cardId: String, answer: CardAnswer) { + val body = LembasJson.encodeToString(CardAnswer.serializer(), answer).toRequestBody(JSON) + empty(authed("$v2/chats/$chatId/interactions/$cardId").post(body).build()) + } + + // --- Attachments ------------------------------------------------------------------------- + suspend fun upload(name: String, mime: String, bytes: ByteArray, chatId: String? = null): Attachment { + val body = MultipartBody.Builder().setType(MultipartBody.FORM) + .addFormDataPart("file", name, bytes.toRequestBody(mime.toMediaType())) + .build() + val url = "$v2/attachments" + (chatId?.let { "?chat=$it" } ?: "") + return call(authed(url).post(body).build(), AttachmentEnvelope.serializer()).attachment + } + + suspend fun attachmentBytes(id: String): ByteArray = withContext(Dispatchers.IO) { + http.newCall(authed("$v2/attachments/$id").get().build()).await().use { + if (!it.isSuccessful) throw ApiException(it.code, detail(it)) + it.body!!.bytes() + } + } + + // --- Push -------------------------------------------------------------------------------- + suspend fun pushKey(): PushKey = get("/push") + + suspend fun registerPush(endpoint: String, p256dh: String, auth: String) { + val body = buildJsonObject { + put("endpoint", endpoint) + put("p256dh", p256dh) + put("auth", auth) + } + empty(authed("$v2/push").post(body.toString().toRequestBody(JSON)).build()) + } + + suspend fun forgetPush() = empty(authed("$v2/push").delete().build()) + + // --- Voice (/v1, the `models` scope) ----------------------------------------------------- + suspend fun transcribe(wav: ByteArray, language: String? = null): String { + val body = MultipartBody.Builder().setType(MultipartBody.FORM) + .addFormDataPart("file", "speech.wav", wav.toRequestBody("audio/wav".toMediaType())) + .apply { language?.let { addFormDataPart("language", it) } } + .build() + return call(authed("$base/v1/audio/transcriptions").post(body).build(), Transcript.serializer()).text + } + + suspend fun speech(text: String): ByteArray = withContext(Dispatchers.IO) { + val body = buildJsonObject { + put("input", text.take(20_000)) + put("response_format", "mp3") + } + http.newCall(authed("$base/v1/audio/speech").post(body.toString().toRequestBody(JSON)).build()).await().use { + if (!it.isSuccessful) throw ApiException(it.code, detail(it)) + it.body!!.bytes() + } + } + + fun streamRequest(chatId: String, messageId: String): Request = + authed("$v2/chats/$chatId/messages/$messageId/stream").header("Accept", "text/event-stream").build() + + companion object { + fun emptyBody(): RequestBody = ByteArray(0).toRequestBody(null) + } +} diff --git a/app/src/main/java/eu/llembas/android/api/LiveReply.kt b/app/src/main/java/eu/llembas/android/api/LiveReply.kt new file mode 100644 index 0000000..0f09be8 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/api/LiveReply.kt @@ -0,0 +1,72 @@ +package eu.llembas.android.api + +import kotlinx.serialization.json.JsonObject + +/** + * A reply being written, as the stream has described it so far. + * + * Every frame carries a whole block, never a delta (the server's rule, `api/v2/stream.py`), + * so applying one is replacing a field. That is what makes a dropped connection cheap: reopen + * the stream, and its first pass rebuilds this from nothing. + */ +data class LiveReply( + val messageId: String, + val steps: List = emptyList(), + val tail: Tail = Tail(), + val plan: Plan? = null, + val status: String = "", + val cards: List = emptyList(), + val jobs: List = emptyList(), + val metrics: Metrics? = null, + val steered: Set = emptySet(), + /** Set by `done`: the finished row, which replaces this in the transcript. */ + val finished: Message? = null, + val title: String? = null, + /** A queued prompt the server started when this reply ended: the next stream to follow. */ + val next: String? = null, + val closed: Boolean = false, +) { + /** The steps as the transcript draws them: the closed ones, then the open tail. */ + val shown: List + get() = buildList { + addAll(steps) + val index = (steps.maxOfOrNull { it.index } ?: -1) + 1 + if (tail.thinking.isNotEmpty()) add(Step(index = index, kind = "thinking", open = true, text = tail.thinking, label = tail.label)) + if (tail.text.isNotEmpty()) add(Step(index = index, kind = "text", open = true, markdown = tail.text)) + } + + /** Apply one frame. Unknown events are ignored: a newer server may send more. */ + fun apply(event: String, data: String): LiveReply = when (event) { + "steps" -> decode(StepsFrame.serializer(), data)?.let { copy(steps = it.steps, tail = it.tail) } ?: this + + "tail" -> decode(Tail.serializer(), data)?.let { copy(tail = it) } ?: this + + "steered" -> decode(SteeredFrame.serializer(), data)?.let { copy(steered = steered + it.ids) } ?: this + + "plan" -> copy(plan = decodePlan(data)) + + "status" -> decode(StatusFrame.serializer(), data)?.let { copy(status = it.text) } ?: this + + "ask" -> decode(AskFrame.serializer(), data)?.let { copy(cards = it.cards) } ?: this + + "jobs" -> decode(JobsFrame.serializer(), data)?.let { copy(jobs = it.jobs) } ?: this + + "metrics" -> decode(Metrics.serializer(), data)?.let { copy(metrics = it) } ?: this + + "done" -> decode(DoneFrame.serializer(), data)?.let { + copy(finished = it.message, title = it.chat.title.ifEmpty { null }, next = it.next, cards = emptyList(), status = "") + } ?: this + + "close" -> copy(closed = true) + + else -> this + } + + private fun decode(serializer: kotlinx.serialization.KSerializer, data: String): T? = + runCatching { LembasJson.decodeFromString(serializer, data) }.getOrNull() + + private fun decodePlan(data: String): Plan? = runCatching { + val element = LembasJson.parseToJsonElement(data) + if (element is JsonObject && element.isNotEmpty()) LembasJson.decodeFromJsonElement(Plan.serializer(), element) else null + }.getOrNull() +} diff --git a/app/src/main/java/eu/llembas/android/api/Models.kt b/app/src/main/java/eu/llembas/android/api/Models.kt new file mode 100644 index 0000000..d3680bc --- /dev/null +++ b/app/src/main/java/eu/llembas/android/api/Models.kt @@ -0,0 +1,348 @@ +package eu.llembas.android.api + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject + +/** + * The server's `/api/v2` shapes. Mirrors `api/v2/serialise.py` on the server; every class here + * is exercised against the pinned `contract/` files by `ContractTest`, so a field the + * server renamed fails a test here rather than on a phone. + * + * Unknown fields are ignored: adding a field is not a new API version, and an older app must + * keep reading a newer server. + */ +val LembasJson = Json { + ignoreUnknownKeys = true + explicitNulls = false + coerceInputValues = true + isLenient = false +} + +@Serializable +data class Discovery( + val service: String = "", + val version: String = "", + val name: String = "", + @SerialName("base_url") val baseUrl: String = "", + @SerialName("app_api") val appApi: Int = 0, + val login: Login = Login(), + val scopes: List = emptyList(), +) { + @Serializable + data class Login(val device: DeviceLogin = DeviceLogin()) + + @Serializable + data class DeviceLogin(val code: String = "", val token: String = "", val verify: String = "") +} + +@Serializable +data class DeviceCode( + @SerialName("device_code") val deviceCode: String, + @SerialName("user_code") val userCode: String, + @SerialName("verification_uri") val verificationUri: String = "", + @SerialName("verification_uri_complete") val verificationUriComplete: String = "", + val interval: Int = 5, + @SerialName("expires_in") val expiresIn: Int = 600, +) + +@Serializable +data class DeviceToken( + @SerialName("access_token") val accessToken: String? = null, + val scope: String = "", + val error: String? = null, + val account: Account? = null, +) + +@Serializable +data class Account(val id: String = "", val name: String = "", val email: String = "") + +@Serializable +data class Me( + val api: Int = 0, + val version: String = "", + val account: Account = Account(), + val language: String = "", + val theme: String = "", + @SerialName("default_model") val defaultModel: String? = null, + val permissions: Map = emptyMap(), + val services: Map = emptyMap(), +) + +@Serializable +data class ModelInfo( + val id: String, + val name: String = "", + val vision: Boolean = false, + val tools: Boolean = false, + val efforts: List = emptyList(), + val context: Int = 0, + val default: Boolean = false, +) + +@Serializable +data class ModelList(val models: List = emptyList()) + +@Serializable +data class Folder(val id: String, val name: String = "", @SerialName("parent_id") val parentId: String? = null, val kind: String = "", val position: Int = 0) + +@Serializable +data class FolderList(val folders: List = emptyList()) + +@Serializable +data class Device(@SerialName("token_id") val tokenId: String? = null, val directory: String = "") + +@Serializable +data class LinkedDevice(val id: String, val name: String = "", val host: String = "", val platform: String = "") + +@Serializable +data class DeviceList(val devices: List = emptyList()) + +@Serializable +data class Chat( + val id: String, + val kind: String = "chat", + val title: String = "", + val model: String = "", + @SerialName("folder_id") val folderId: String? = null, + val pinned: Boolean = false, + val archived: Boolean = false, + val temporary: Boolean = false, + val unread: Boolean = false, + val running: Boolean = false, + val mode: String = "", + val effort: String? = null, + val device: Device? = null, + @SerialName("parent_chat_id") val parentChatId: String? = null, + @SerialName("created_at") val createdAt: String? = null, + @SerialName("updated_at") val updatedAt: String? = null, + @SerialName("system_prompt") val systemPrompt: String? = null, + val plan: JsonObject? = null, +) { + val isAgent: Boolean get() = kind == "agent" +} + +@Serializable +data class ChatPage(val chats: List = emptyList(), val more: Boolean = false) + +@Serializable +data class ChatDetail(val chat: Chat, val messages: List = emptyList(), val more: Boolean = false, val live: String? = null) + +@Serializable +data class MessagePage(val messages: List = emptyList(), val more: Boolean = false) + +@Serializable +data class Unread(val unread: List = emptyList()) + +@Serializable +data class Attachment( + val id: String, + val name: String = "", + val mime: String = "", + val size: Long = 0, + val kind: String = "", + val image: Boolean = false, + val width: Int = 0, + val height: Int = 0, +) + +@Serializable +data class AttachmentEnvelope(val attachment: Attachment) + +@Serializable +data class Metrics( + @SerialName("prompt_tokens") val promptTokens: Int = 0, + @SerialName("completion_tokens") val completionTokens: Int = 0, + @SerialName("total_tokens") val totalTokens: Int = 0, + @SerialName("context_tokens") val contextTokens: Int = 0, + @SerialName("context_limit") val contextLimit: Int = 0, + val estimated: Boolean = false, + @SerialName("elapsed_ms") val elapsedMs: Long = 0, + val rounds: Int = 1, + @SerialName("thinking_ms") val thinkingMs: Long = 0, + val percent: Int = 0, + @SerialName("tok_s") val tokPerSecond: Double = 0.0, +) + +@Serializable +data class ToolBlock(val kind: String = "tool", val title: String = "", val chips: List = emptyList(), val added: Int = 0, val removed: Int = 0) + +/** One tool call. What the tool wrote varies by tool, so the free-form parts stay JSON. */ +@Serializable +data class ToolCall( + val id: String? = null, + val name: String = "", + val kind: String? = null, + val status: String? = null, + val args: JsonElement? = null, + val query: String? = null, + val purpose: String? = null, + val why: String? = null, + val text: String? = null, + val error: String? = null, + val detail: JsonElement? = null, + val results: JsonElement? = null, + val diff: String? = null, + val exit: Int? = null, + val hits: Int? = null, + val path: String? = null, + val truncated: Boolean = false, + val job: JsonElement? = null, + val children: List? = null, + val block: ToolBlock = ToolBlock(), +) + +@Serializable +data class SteerNote(val id: String = "", val text: String = "") + +/** One step of a reply: `thinking`, `text`, `tools` or `steer`. */ +@Serializable +data class Step( + val index: Int = 0, + val kind: String, + val open: Boolean = false, + val text: String? = null, + val label: String? = null, + val markdown: String? = null, + val calls: List = emptyList(), + val messages: List = emptyList(), +) + +@Serializable +data class Message( + val id: String, + val role: String, + @SerialName("created_at") val createdAt: String? = null, + val complete: Boolean = true, + val stopped: Boolean = false, + val error: String? = null, + val queued: Boolean = false, + val machine: Boolean = false, + val origin: String = "", + val model: String? = null, + val attachments: List = emptyList(), + val text: String? = null, + val steps: List = emptyList(), + val plan: JsonObject? = null, + val metrics: Metrics? = null, +) { + val isUser: Boolean get() = role == "user" +} + +@Serializable +data class Turn(val message: Message? = null, val reply: Message? = null) + +@Serializable +data class NewChat(val chat: Chat, val message: Message? = null, val reply: Message? = null) + +@Serializable +data class ChatEnvelope(val chat: Chat) + +@Serializable +data class Option(val label: String, val description: String = "", val recommended: Boolean = false) + +@Serializable +data class CardItem( + val index: Int = 0, + val key: String, + val kind: String, + val tool: String = "", + val title: String = "", + val header: String = "", + val detail: String = "", + val reason: String = "", + val purpose: String = "", + val options: List