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 <noreply@anthropic.com>
This commit is contained in:
96 files changed
+7932
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
@@ -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/*
|
||||
+16
@@ -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__/
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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 <server-ref>` | `tokens.css` |
|
||||
| `contract/*.json` | `scripts/fetch-contract.py <server-ref>` | `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).
|
||||
@@ -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)
|
||||
}
|
||||
Vendored
+19
@@ -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.**
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- The `full` build updates itself from llembas.eu; the `fdroid` build has none of this. -->
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<application>
|
||||
<receiver
|
||||
android:name="eu.llembas.android.update.InstallStatusReceiver"
|
||||
android:exported="false" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,127 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<!-- Dictation and the assistant's voice. Asked for the first time either is used. -->
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
|
||||
<queries>
|
||||
<!-- UnifiedPush distributors (ntfy and others) are found by this action. -->
|
||||
<intent>
|
||||
<action android:name="org.unifiedpush.android.distributor.REGISTER" />
|
||||
</intent>
|
||||
</queries>
|
||||
|
||||
<application
|
||||
android:name=".LembasApp"
|
||||
android:allowBackup="false"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:roundIcon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.Lembas">
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTop"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.app.shortcuts" android:resource="@xml/shortcuts" />
|
||||
</activity>
|
||||
|
||||
<!-- The assistant's sheet as an activity: the tile, the shortcut, ACTION_ASSIST, and
|
||||
the lock-screen path (it asks to unlock before sending anything). -->
|
||||
<activity
|
||||
android:name=".assist.AssistActivity"
|
||||
android:exported="true"
|
||||
android:excludeFromRecents="true"
|
||||
android:launchMode="singleTask"
|
||||
android:taskAffinity=""
|
||||
android:theme="@style/Theme.Lembas.Sheet"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.ASSIST" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".share.ShareActivity"
|
||||
android:exported="true"
|
||||
android:excludeFromRecents="true"
|
||||
android:label="@string/share_label"
|
||||
android:taskAffinity="">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.SEND" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<data android:mimeType="text/*" />
|
||||
<data android:mimeType="image/*" />
|
||||
<data android:mimeType="application/*" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.SEND_MULTIPLE" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<data android:mimeType="image/*" />
|
||||
<data android:mimeType="application/*" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- The digital assistant: Settings › Default apps › Digital assistant app. -->
|
||||
<service
|
||||
android:name=".assist.LembasAssistService"
|
||||
android:exported="true"
|
||||
android:label="@string/app_name"
|
||||
android:permission="android.permission.BIND_VOICE_INTERACTION">
|
||||
<meta-data android:name="android.voice_interaction" android:resource="@xml/assist_service" />
|
||||
<intent-filter>
|
||||
<action android:name="android.service.voice.VoiceInteractionService" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<service
|
||||
android:name=".assist.LembasAssistSessionService"
|
||||
android:exported="true"
|
||||
android:permission="android.permission.BIND_VOICE_INTERACTION" />
|
||||
|
||||
<service
|
||||
android:name=".assist.LembasRecognitionService"
|
||||
android:exported="true"
|
||||
android:label="@string/app_name">
|
||||
<intent-filter>
|
||||
<action android:name="android.speech.RecognitionService" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.speech" android:resource="@xml/recognition_service" />
|
||||
</service>
|
||||
|
||||
<service
|
||||
android:name=".assist.AskTileService"
|
||||
android:exported="true"
|
||||
android:icon="@drawable/ic_notification"
|
||||
android:label="@string/tile_ask"
|
||||
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
|
||||
<intent-filter>
|
||||
<action android:name="android.service.quicksettings.action.QS_TILE" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<service
|
||||
android:name=".push.LembasPushService"
|
||||
android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="org.unifiedpush.android.connector.PUSH_EVENT" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<receiver
|
||||
android:name=".push.CardActionReceiver"
|
||||
android:exported="false" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -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
|
||||
@@ -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<String?>(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) }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 <T> call(request: Request, serializer: KSerializer<T>): 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 <reified T> get(path: String): T = call(authed("$v2$path").get().build(), serializer())
|
||||
|
||||
private suspend inline fun <reified T> 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<ModelInfo> = get<ModelList>(if (chatId != null) "/models?chat=$chatId" else "/models").models
|
||||
|
||||
suspend fun folders(): List<Folder> = get<FolderList>("/folders").folders
|
||||
|
||||
suspend fun devices(): List<LinkedDevice> = get<DeviceList>("/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<String> = get<Unread>("/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<String> = 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<String> = 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<ChatEnvelope>("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)
|
||||
}
|
||||
}
|
||||
@@ -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<Step> = emptyList(),
|
||||
val tail: Tail = Tail(),
|
||||
val plan: Plan? = null,
|
||||
val status: String = "",
|
||||
val cards: List<Card> = emptyList(),
|
||||
val jobs: List<Job> = emptyList(),
|
||||
val metrics: Metrics? = null,
|
||||
val steered: Set<String> = 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<Step>
|
||||
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 <T> decode(serializer: kotlinx.serialization.KSerializer<T>, 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()
|
||||
}
|
||||
@@ -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<String> = 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<String, Boolean> = emptyMap(),
|
||||
val services: Map<String, Boolean> = emptyMap(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ModelInfo(
|
||||
val id: String,
|
||||
val name: String = "",
|
||||
val vision: Boolean = false,
|
||||
val tools: Boolean = false,
|
||||
val efforts: List<String> = emptyList(),
|
||||
val context: Int = 0,
|
||||
val default: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ModelList(val models: List<ModelInfo> = 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<Folder> = 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<LinkedDevice> = 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<Chat> = emptyList(), val more: Boolean = false)
|
||||
|
||||
@Serializable
|
||||
data class ChatDetail(val chat: Chat, val messages: List<Message> = emptyList(), val more: Boolean = false, val live: String? = null)
|
||||
|
||||
@Serializable
|
||||
data class MessagePage(val messages: List<Message> = emptyList(), val more: Boolean = false)
|
||||
|
||||
@Serializable
|
||||
data class Unread(val unread: List<String> = 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<String> = 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<ToolCall>? = 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<ToolCall> = emptyList(),
|
||||
val messages: List<SteerNote> = 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<Attachment> = emptyList(),
|
||||
val text: String? = null,
|
||||
val steps: List<Step> = 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<Option> = emptyList(),
|
||||
val multiple: Boolean = false,
|
||||
@SerialName("free_text") val freeText: Boolean = true,
|
||||
val editable: Boolean = false,
|
||||
val plan: JsonObject? = null,
|
||||
@SerialName("mode_choice") val modeChoice: Boolean = false,
|
||||
val job: String = "",
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class Card(
|
||||
val id: String,
|
||||
val kind: String,
|
||||
val why: String = "",
|
||||
val dismissable: Boolean = false,
|
||||
@SerialName("expires_in") val expiresIn: Int? = null,
|
||||
val items: List<CardItem> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class Plan(val title: String = "", val summary: String = "", val phases: List<Phase> = emptyList(), val steps: List<String> = emptyList()) {
|
||||
@Serializable
|
||||
data class Phase(val id: String = "", val title: String = "", val status: String = "", val tasks: List<Task> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class Task(val id: String = "", val text: String = "", val status: String = "todo", val note: String = "")
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class Job(
|
||||
val id: String,
|
||||
val kind: String = "",
|
||||
val state: String = "",
|
||||
val description: String = "",
|
||||
val agent: String = "",
|
||||
val seconds: Int = 0,
|
||||
val command: String = "",
|
||||
)
|
||||
|
||||
/** The answer to a card, as the page's form says it (see `api/v2/chats.py:answer`). */
|
||||
@Serializable
|
||||
data class CardAnswer(
|
||||
val verdict: String = "",
|
||||
val reason: String = "",
|
||||
val choices: Map<String, List<String>> = emptyMap(),
|
||||
val texts: Map<String, String> = emptyMap(),
|
||||
val asks: Map<String, String> = emptyMap(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class PushKey(val key: String = "", val registered: Boolean = false)
|
||||
|
||||
@Serializable
|
||||
data class Transcript(val text: String = "")
|
||||
|
||||
// --- The stream's frames -----------------------------------------------------------------
|
||||
@Serializable
|
||||
data class Tail(val thinking: String = "", val text: String = "", val label: String = "")
|
||||
|
||||
@Serializable
|
||||
data class StepsFrame(val steps: List<Step> = emptyList(), val tail: Tail = Tail())
|
||||
|
||||
@Serializable
|
||||
data class SteeredFrame(val ids: List<String> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class StatusFrame(val text: String = "")
|
||||
|
||||
@Serializable
|
||||
data class AskFrame(val cards: List<Card> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class JobsFrame(val jobs: List<Job> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class DoneFrame(val message: Message, val chat: DoneChat = DoneChat(), val next: String? = null) {
|
||||
@Serializable
|
||||
data class DoneChat(val id: String = "", val title: String = "")
|
||||
}
|
||||
|
||||
/** The push payload the server sends (services/push.py), as the app reads it. */
|
||||
@Serializable
|
||||
data class PushPayload(
|
||||
val title: String = "",
|
||||
val body: String = "",
|
||||
val url: String = "",
|
||||
val kind: String = "",
|
||||
@SerialName("chat_id") val chatId: String? = null,
|
||||
@SerialName("message_id") val messageId: String? = null,
|
||||
@SerialName("interaction_id") val interactionId: String? = null,
|
||||
val ask: String? = null,
|
||||
)
|
||||
@@ -0,0 +1,86 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.coroutines.channels.awaitClose
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.callbackFlow
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import okhttp3.Response
|
||||
import okhttp3.sse.EventSource
|
||||
import okhttp3.sse.EventSourceListener
|
||||
import okhttp3.sse.EventSources
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/** One server-sent event: its name and its data. */
|
||||
data class Frame(val event: String, val data: String)
|
||||
|
||||
/**
|
||||
* Follow a reply: the stream's frames, and when the connection drops before `close`, the same
|
||||
* stream opened again after a pause -- 1, 2, 4, 8 … up to 30 seconds. Nothing is replayed or
|
||||
* deduplicated: the server's first pass after a reconnect is the whole state, which is exactly
|
||||
* what [LiveReply.apply] wants.
|
||||
*
|
||||
* A refusal (a 4xx: the chat was deleted, the token signed out) ends the flow with the error;
|
||||
* only a broken connection is retried.
|
||||
*/
|
||||
class StreamClient(private val api: ApiClient) {
|
||||
private val http = api.http.newBuilder().readTimeout(0, TimeUnit.SECONDS).build()
|
||||
|
||||
fun follow(chatId: String, messageId: String): Flow<Frame> = flow {
|
||||
var wait = 1_000L
|
||||
while (true) {
|
||||
var closed = false
|
||||
var refused: ApiException? = null
|
||||
once(chatId, messageId).collect { result ->
|
||||
when (result) {
|
||||
is Outcome.Event -> {
|
||||
wait = 1_000L
|
||||
emit(result.frame)
|
||||
if (result.frame.event == "close") closed = true
|
||||
}
|
||||
|
||||
is Outcome.Refused -> refused = result.error
|
||||
|
||||
is Outcome.Dropped -> Unit
|
||||
}
|
||||
}
|
||||
refused?.let { throw it }
|
||||
if (closed) return@flow
|
||||
delay(wait)
|
||||
wait = (wait * 2).coerceAtMost(30_000L)
|
||||
}
|
||||
}
|
||||
|
||||
private sealed interface Outcome {
|
||||
data class Event(val frame: Frame) : Outcome
|
||||
data class Refused(val error: ApiException) : Outcome
|
||||
data object Dropped : Outcome
|
||||
}
|
||||
|
||||
private fun once(chatId: String, messageId: String): Flow<Outcome> = callbackFlow {
|
||||
val source = EventSources.createFactory(http).newEventSource(
|
||||
api.streamRequest(chatId, messageId),
|
||||
object : EventSourceListener() {
|
||||
override fun onEvent(eventSource: EventSource, id: String?, type: String?, data: String) {
|
||||
trySend(Outcome.Event(Frame(type ?: "message", data)))
|
||||
if (type == "close") close()
|
||||
}
|
||||
|
||||
override fun onClosed(eventSource: EventSource) {
|
||||
close()
|
||||
}
|
||||
|
||||
override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
|
||||
val code = response?.code ?: 0
|
||||
if (code in 400..499) {
|
||||
trySend(Outcome.Refused(ApiException(code, response?.let { detail(it) } ?: "Refused ($code).")))
|
||||
} else {
|
||||
trySend(Outcome.Dropped)
|
||||
}
|
||||
close()
|
||||
}
|
||||
},
|
||||
)
|
||||
awaitClose { source.cancel() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.service.quicksettings.TileService
|
||||
|
||||
/** A Quick Settings tile that opens the assistant's sheet: one more way in besides the power button. */
|
||||
class AskTileService : TileService() {
|
||||
@android.annotation.SuppressLint("StartActivityAndCollapseDeprecated")
|
||||
override fun onClick() {
|
||||
super.onClick()
|
||||
val intent = Intent(this, AssistActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
if (Build.VERSION.SDK_INT >= 34) {
|
||||
// Android 14 refuses the Intent overload; the PendingIntent one is the way now.
|
||||
startActivityAndCollapse(PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE))
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
startActivityAndCollapse(intent)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.app.KeyguardManager
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
|
||||
/**
|
||||
* The assistant as an activity: what the Quick Settings tile, the "Ask" shortcut and a plain
|
||||
* `ACTION_ASSIST` open, and where the voice-interaction session hands a question asked over the
|
||||
* lock screen. Shown over the lock screen, but it asks Android to unlock before it sends
|
||||
* anything -- and shows nothing from the account until then.
|
||||
*/
|
||||
class AssistActivity : ComponentActivity() {
|
||||
private lateinit var controller: AssistController
|
||||
private val mic = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (granted) controller.listen()
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
setShowWhenLocked(true)
|
||||
controller = AssistController(this, lifecycleScope)
|
||||
val keyguard = getSystemService(KeyguardManager::class.java)
|
||||
val waiting = intent.getStringExtra(EXTRA_QUESTION).orEmpty()
|
||||
if (keyguard.isKeyguardLocked) {
|
||||
keyguard.requestDismissKeyguard(
|
||||
this,
|
||||
object : KeyguardManager.KeyguardDismissCallback() {
|
||||
override fun onDismissSucceeded() {
|
||||
if (waiting.isNotBlank()) controller.ask(waiting)
|
||||
}
|
||||
|
||||
override fun onDismissCancelled() = finish()
|
||||
|
||||
override fun onDismissError() = finish()
|
||||
},
|
||||
)
|
||||
} else if (waiting.isNotBlank()) {
|
||||
controller.ask(waiting)
|
||||
}
|
||||
setContent {
|
||||
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
|
||||
LembasTheme(prefs.theme) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(Color.Black.copy(alpha = 0.4f))
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { finish() }
|
||||
.imePadding(),
|
||||
contentAlignment = Alignment.BottomCenter,
|
||||
) {
|
||||
Box(Modifier.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}) {
|
||||
AssistPanel(
|
||||
controller = controller,
|
||||
locked = keyguard.isKeyguardLocked,
|
||||
onUnlockAndAsk = { text ->
|
||||
keyguard.requestDismissKeyguard(
|
||||
this@AssistActivity,
|
||||
object : KeyguardManager.KeyguardDismissCallback() {
|
||||
override fun onDismissSucceeded() = controller.ask(text)
|
||||
},
|
||||
)
|
||||
},
|
||||
onOpenApp = {
|
||||
startActivity(controller.appIntent())
|
||||
finish()
|
||||
},
|
||||
onNeedMic = { mic.launch(Manifest.permission.RECORD_AUDIO) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
controller.close()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EXTRA_QUESTION = "eu.llembas.android.QUESTION"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Bitmap
|
||||
import eu.llembas.android.MainActivity
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.push.Notifications
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
data class AssistUiState(
|
||||
val signedIn: Boolean = true,
|
||||
val listening: Boolean = false,
|
||||
val busy: Boolean = false,
|
||||
val asked: String? = null,
|
||||
val chatId: String? = null,
|
||||
val reply: LiveReply? = null,
|
||||
val error: String? = null,
|
||||
/** Whether the screen goes with the question. Off until the person turns it on, every time. */
|
||||
val includeScreen: Boolean = false,
|
||||
val screenAvailable: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* The assistant's one job: take a question -- typed or spoken -- start a chat with it on the
|
||||
* instance, and stream the answer back into the sheet. Shared by the voice-interaction session
|
||||
* (power button, assist gesture) and [AssistActivity] (the tile, the shortcut, the lock screen
|
||||
* path), so both behave the same.
|
||||
*
|
||||
* The chat is an ordinary one: it is in the list on the phone and on the web afterwards. The
|
||||
* Settings switch "assistant chats are temporary" makes them temporary instead.
|
||||
*/
|
||||
class AssistController(private val context: Context, private val scope: CoroutineScope) {
|
||||
private val _state = MutableStateFlow(AssistUiState())
|
||||
val state = _state.asStateFlow()
|
||||
private val recorder = Recorder(scope)
|
||||
private val speaker = Speaker(context)
|
||||
private var following: Job? = null
|
||||
private var screenText: String? = null
|
||||
private var screenshot: Bitmap? = null
|
||||
|
||||
init {
|
||||
scope.launch { _state.update { it.copy(signedIn = context.lembas.instances.current() != null) } }
|
||||
}
|
||||
|
||||
fun offerScreen(text: String?, image: Bitmap?) {
|
||||
if (!text.isNullOrBlank()) screenText = text.take(MAX_SCREEN_CHARS)
|
||||
if (image != null) screenshot = image
|
||||
_state.update { it.copy(screenAvailable = screenText != null || screenshot != null) }
|
||||
}
|
||||
|
||||
fun includeScreen(on: Boolean) = _state.update { it.copy(includeScreen = on) }
|
||||
|
||||
@android.annotation.SuppressLint("MissingPermission")
|
||||
fun listen() {
|
||||
speaker.stop()
|
||||
recorder.start()
|
||||
_state.update { it.copy(listening = true, error = null) }
|
||||
}
|
||||
|
||||
/** Stop listening, write down what was said, and ask it. */
|
||||
fun heard() {
|
||||
scope.launch {
|
||||
val wav = recorder.stop()
|
||||
_state.update { it.copy(listening = false) }
|
||||
if (wav.isEmpty()) return@launch
|
||||
try {
|
||||
_state.update { it.copy(busy = true) }
|
||||
val text = context.lembas.instances.client()?.transcribe(wav).orEmpty()
|
||||
_state.update { it.copy(busy = false) }
|
||||
if (text.isNotBlank()) ask(text, spoken = true)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(busy = false, error = e.message) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun ask(question: String, spoken: Boolean = false) {
|
||||
if (question.isBlank()) return
|
||||
following?.cancel()
|
||||
following = scope.launch {
|
||||
_state.update { it.copy(busy = true, asked = question, reply = null, error = null) }
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: error("Not signed in.")
|
||||
val prefs = context.lembas.instances.prefs.first()
|
||||
val withScreen = _state.value.includeScreen
|
||||
val attachments = buildList {
|
||||
if (withScreen) {
|
||||
screenshot?.let { shot -> add(api.upload("screen.png", "image/png", png(shot)).id) }
|
||||
}
|
||||
}
|
||||
val text = if (withScreen && screenText != null) "$question\n\n---\nOn my screen:\n\n$screenText" else question
|
||||
val made = api.createChat(text, attachments, temporary = prefs.assistantTemporary)
|
||||
_state.update { it.copy(chatId = made.chat.id) }
|
||||
val reply = made.reply ?: return@launch
|
||||
var live = LiveReply(reply.id)
|
||||
StreamClient(api).follow(made.chat.id, reply.id).collect { frame ->
|
||||
live = live.apply(frame.event, frame.data)
|
||||
_state.update { it.copy(reply = live, busy = live.finished == null) }
|
||||
}
|
||||
val finished = live.finished
|
||||
if (spoken && prefs.readAloudSpoken && finished != null) {
|
||||
val words = finished.steps.filter { it.kind == "text" }.joinToString("\n\n") { it.markdown.orEmpty() }
|
||||
if (words.isNotBlank()) speaker.play(api.speech(plain(words)))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = e.message ?: e.javaClass.simpleName) }
|
||||
} finally {
|
||||
_state.update { it.copy(busy = false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Carry on in the app, at this chat. The caller starts it: a session and an activity
|
||||
* start activities differently. */
|
||||
fun appIntent(): Intent = Intent(context, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
.apply { _state.value.chatId?.let { putExtra(Notifications.EXTRA_CHAT, it) } }
|
||||
|
||||
fun close() {
|
||||
following?.cancel()
|
||||
speaker.stop()
|
||||
scope.launch { recorder.stop() }
|
||||
}
|
||||
|
||||
private suspend fun png(bitmap: Bitmap): ByteArray = withContext(Dispatchers.Default) {
|
||||
ByteArrayOutputStream().use { out ->
|
||||
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
|
||||
out.toByteArray()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val MAX_SCREEN_CHARS = 8_000
|
||||
|
||||
/** Markdown as something a voice can read: no fences, marks or link targets. */
|
||||
fun plain(markdown: String): String = markdown
|
||||
.replace(Regex("```[\\s\\S]*?```"), " ")
|
||||
.replace(Regex("!?\\[([^\\]]*)]\\([^)]*\\)"), "$1")
|
||||
.replace(Regex("[*_`#>|~]"), "")
|
||||
.replace(Regex("\\s+"), " ")
|
||||
.trim()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Send
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TextField
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.ui.chat.Steps
|
||||
|
||||
/**
|
||||
* The assistant's sheet: a question box, the microphone, "Include screen", and the answer as it
|
||||
* is written. Nothing from the account -- no chat list, no history -- is on it, which is what
|
||||
* lets it open over the lock screen (sending from there asks to unlock first: [locked]).
|
||||
*/
|
||||
@Composable
|
||||
fun AssistPanel(controller: AssistController, locked: Boolean, onUnlockAndAsk: (String) -> Unit, onOpenApp: () -> Unit, onNeedMic: () -> Unit) {
|
||||
val state by controller.state.collectAsState()
|
||||
val context = LocalContext.current
|
||||
var text by remember { mutableStateOf("") }
|
||||
val focus = remember { FocusRequester() }
|
||||
LaunchedEffect(Unit) { runCatching { focus.requestFocus() } }
|
||||
|
||||
Surface(
|
||||
shape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp),
|
||||
tonalElevation = 3.dp,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(Modifier.padding(16.dp).navigationBarsPadding(), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
if (!state.signedIn) {
|
||||
Text(stringResource(R.string.assist_signed_out))
|
||||
TextButton(onClick = onOpenApp) { Text(stringResource(R.string.assist_open_app)) }
|
||||
return@Column
|
||||
}
|
||||
state.asked?.let { Text(it, style = MaterialTheme.typography.titleSmall) }
|
||||
if (state.busy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
state.reply?.let { reply ->
|
||||
Column(Modifier.heightIn(max = 420.dp).verticalScroll(rememberScrollState())) {
|
||||
Steps(reply.finished?.steps ?: reply.shown)
|
||||
}
|
||||
}
|
||||
state.error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||
if (state.screenAvailable && !locked) {
|
||||
FilterChip(
|
||||
selected = state.includeScreen,
|
||||
onClick = { controller.includeScreen(!state.includeScreen) },
|
||||
label = { Text(stringResource(R.string.assist_include_screen)) },
|
||||
)
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
TextField(
|
||||
value = text,
|
||||
onValueChange = { text = it },
|
||||
placeholder = { Text(stringResource(if (state.listening) R.string.listening else R.string.assist_hint)) },
|
||||
modifier = Modifier.weight(1f).focusRequester(focus),
|
||||
)
|
||||
IconButton(onClick = {
|
||||
when {
|
||||
locked -> onUnlockAndAsk(text)
|
||||
|
||||
state.listening -> controller.heard()
|
||||
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) ==
|
||||
PackageManager.PERMISSION_GRANTED -> controller.listen()
|
||||
|
||||
else -> onNeedMic()
|
||||
}
|
||||
}) {
|
||||
Icon(if (state.listening) Icons.Filled.Stop else Icons.Filled.Mic, contentDescription = stringResource(R.string.dictate))
|
||||
}
|
||||
IconButton(enabled = text.isNotBlank() && !state.busy, onClick = {
|
||||
if (locked) onUnlockAndAsk(text) else controller.ask(text)
|
||||
text = ""
|
||||
}) {
|
||||
Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send))
|
||||
}
|
||||
}
|
||||
if (state.chatId != null) {
|
||||
TextButton(onClick = onOpenApp) { Text(stringResource(R.string.assist_open_in_app)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.app.KeyguardManager
|
||||
import android.app.assist.AssistStructure
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Bitmap
|
||||
import android.os.Bundle
|
||||
import android.service.voice.VoiceInteractionService
|
||||
import android.service.voice.VoiceInteractionSession
|
||||
import android.service.voice.VoiceInteractionSessionService
|
||||
import android.view.View
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import androidx.compose.ui.platform.ViewCompositionStrategy
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.lifecycle.LifecycleRegistry
|
||||
import androidx.lifecycle.setViewTreeLifecycleOwner
|
||||
import androidx.savedstate.SavedStateRegistry
|
||||
import androidx.savedstate.SavedStateRegistryController
|
||||
import androidx.savedstate.SavedStateRegistryOwner
|
||||
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
|
||||
/**
|
||||
* The digital assistant. Being the device's voice-interaction service is what Settings ›
|
||||
* Default apps › Digital assistant app chooses, and what the power button's long press, the
|
||||
* assist gesture and a headset's button open. The service itself does nothing until asked:
|
||||
* there is no hotword here -- Android keeps always-on hotword detection for the system's own
|
||||
* preinstalled assistant (`CAPTURE_AUDIO_HOTWORD` is a privileged permission).
|
||||
*/
|
||||
class LembasAssistService : VoiceInteractionService()
|
||||
|
||||
class LembasAssistSessionService : VoiceInteractionSessionService() {
|
||||
override fun onNewSession(args: Bundle?): VoiceInteractionSession = LembasAssistSession(this)
|
||||
}
|
||||
|
||||
/**
|
||||
* One invocation: a sheet over whatever is on screen. A Compose view in a window that is not an
|
||||
* activity's, so this session is its own lifecycle and saved-state owner for the view tree.
|
||||
*/
|
||||
class LembasAssistSession(context: Context) :
|
||||
VoiceInteractionSession(context),
|
||||
LifecycleOwner,
|
||||
SavedStateRegistryOwner {
|
||||
private val registry = LifecycleRegistry(this)
|
||||
private val saved = SavedStateRegistryController.create(this)
|
||||
private var scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
private var controller = AssistController(context, scope)
|
||||
|
||||
override val lifecycle: Lifecycle get() = registry
|
||||
override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
saved.performRestore(null)
|
||||
registry.currentState = Lifecycle.State.CREATED
|
||||
}
|
||||
|
||||
override fun onCreateContentView(): View {
|
||||
val theme = runBlocking { context.lembas.instances.prefs.first() }.theme
|
||||
return ComposeView(context).apply {
|
||||
setViewTreeLifecycleOwner(this@LembasAssistSession)
|
||||
setViewTreeSavedStateRegistryOwner(this@LembasAssistSession)
|
||||
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnDetachedFromWindow)
|
||||
setContent {
|
||||
LembasTheme(theme) {
|
||||
AssistPanel(
|
||||
controller = controller,
|
||||
locked = locked(),
|
||||
onUnlockAndAsk = { text -> handOff(text) },
|
||||
onOpenApp = {
|
||||
startAssistantActivity(controller.appIntent())
|
||||
hide()
|
||||
},
|
||||
onNeedMic = { handOff("") },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onShow(args: Bundle?, showFlags: Int) {
|
||||
super.onShow(args, showFlags)
|
||||
if (!scope.isActiveScope()) {
|
||||
scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
controller = AssistController(context, scope)
|
||||
}
|
||||
registry.currentState = Lifecycle.State.RESUMED
|
||||
}
|
||||
|
||||
override fun onHide() {
|
||||
super.onHide()
|
||||
controller.close()
|
||||
registry.currentState = Lifecycle.State.CREATED
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
controller.close()
|
||||
scope.cancel()
|
||||
registry.currentState = Lifecycle.State.DESTROYED
|
||||
}
|
||||
|
||||
/** What is on screen, if the person allowed it (Settings › "Use text from screen"). */
|
||||
override fun onHandleAssist(state: VoiceInteractionSession.AssistState) {
|
||||
super.onHandleAssist(state)
|
||||
val structure = state.assistStructure ?: return
|
||||
val text = buildString {
|
||||
for (i in 0 until structure.windowNodeCount) collect(structure.getWindowNodeAt(i).rootViewNode, this)
|
||||
}
|
||||
controller.offerScreen(text, null)
|
||||
}
|
||||
|
||||
/** And a picture of it, if allowed ("Use screenshot"). Sent only when "Include screen" is on. */
|
||||
override fun onHandleScreenshot(screenshot: Bitmap?) {
|
||||
super.onHandleScreenshot(screenshot)
|
||||
controller.offerScreen(null, screenshot)
|
||||
}
|
||||
|
||||
private fun collect(node: AssistStructure.ViewNode?, out: StringBuilder) {
|
||||
if (node == null || out.length > AssistController.MAX_SCREEN_CHARS) return
|
||||
node.text?.toString()?.trim()?.takeIf { it.isNotEmpty() }?.let { out.appendLine(it) }
|
||||
for (i in 0 until node.childCount) collect(node.getChildAt(i), out)
|
||||
}
|
||||
|
||||
private fun locked(): Boolean = context.getSystemService(KeyguardManager::class.java).isKeyguardLocked
|
||||
|
||||
/**
|
||||
* Over the lock screen nothing is sent from here: the question goes to [AssistActivity],
|
||||
* which asks Android to unlock first and only then sends it. The microphone's permission
|
||||
* prompt needs an activity too.
|
||||
*/
|
||||
private fun handOff(text: String) {
|
||||
startAssistantActivity(
|
||||
Intent(context, AssistActivity::class.java)
|
||||
.putExtra(AssistActivity.EXTRA_QUESTION, text)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
hide()
|
||||
}
|
||||
|
||||
private fun CoroutineScope.isActiveScope(): Boolean = coroutineContext[kotlinx.coroutines.Job]?.isActive == true
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Bundle
|
||||
import android.speech.RecognitionService
|
||||
import android.speech.SpeechRecognizer
|
||||
import eu.llembas.android.lembas
|
||||
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
|
||||
|
||||
/**
|
||||
* Speech recognition through the instance (`/v1/audio/transcriptions`). Android requires a
|
||||
* digital assistant to name a recognition service; this is it, and any app that asks the
|
||||
* system's recognizer while LLeMbas is the assistant is answered by the instance's
|
||||
* speech-to-text. Listening ends when the caller says stop, or after [LIMIT_MS].
|
||||
*/
|
||||
class LembasRecognitionService : RecognitionService() {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
private val recorder = Recorder(scope)
|
||||
private var callback: RecognitionService.Callback? = null
|
||||
private var limit: Job? = null
|
||||
|
||||
override fun onStartListening(intent: Intent?, listener: RecognitionService.Callback) {
|
||||
if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
|
||||
listener.error(SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS)
|
||||
return
|
||||
}
|
||||
callback = listener
|
||||
recorder.start()
|
||||
listener.readyForSpeech(Bundle())
|
||||
listener.beginningOfSpeech()
|
||||
limit = scope.launch {
|
||||
delay(LIMIT_MS)
|
||||
finish()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStopListening(listener: RecognitionService.Callback) {
|
||||
finish()
|
||||
}
|
||||
|
||||
override fun onCancel(listener: RecognitionService.Callback) {
|
||||
limit?.cancel()
|
||||
callback = null
|
||||
scope.launch { recorder.stop() }
|
||||
}
|
||||
|
||||
private fun finish() {
|
||||
val listener = callback ?: return
|
||||
callback = null
|
||||
limit?.cancel()
|
||||
scope.launch {
|
||||
val wav = recorder.stop()
|
||||
listener.endOfSpeech()
|
||||
try {
|
||||
val text = lembas.instances.client()?.transcribe(wav).orEmpty()
|
||||
if (text.isBlank()) {
|
||||
listener.error(SpeechRecognizer.ERROR_NO_MATCH)
|
||||
} else {
|
||||
listener.results(Bundle().apply { putStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION, arrayListOf(text)) })
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
listener.error(SpeechRecognizer.ERROR_NETWORK)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
scope.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val LIMIT_MS = 15_000L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.media.AudioAttributes
|
||||
import android.media.AudioFormat
|
||||
import android.media.AudioRecord
|
||||
import android.media.MediaPlayer
|
||||
import android.media.MediaRecorder
|
||||
import androidx.annotation.RequiresPermission
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.File
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/**
|
||||
* Speech in: 16 kHz mono PCM, handed over as a WAV file. WAV because every speech-to-text
|
||||
* endpoint reads it (the server passes the file through to whatever its administrator set up),
|
||||
* and a minute of it is under 2 MB -- well inside `/v1/audio/transcriptions`' 25 MB.
|
||||
*
|
||||
* Nothing is recorded until [start], nothing is kept after [stop], and nothing is sent anywhere
|
||||
* but the instance the person is signed in to.
|
||||
*/
|
||||
class Recorder(private val scope: CoroutineScope) {
|
||||
private var record: AudioRecord? = null
|
||||
private var job: Job? = null
|
||||
private val pcm = ByteArrayOutputStream()
|
||||
|
||||
val recording: Boolean get() = record != null
|
||||
|
||||
@RequiresPermission(Manifest.permission.RECORD_AUDIO)
|
||||
fun start() {
|
||||
if (record != null) return
|
||||
pcm.reset()
|
||||
val min = AudioRecord.getMinBufferSize(RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)
|
||||
val audio = AudioRecord(
|
||||
MediaRecorder.AudioSource.VOICE_RECOGNITION,
|
||||
RATE,
|
||||
AudioFormat.CHANNEL_IN_MONO,
|
||||
AudioFormat.ENCODING_PCM_16BIT,
|
||||
maxOf(min, RATE),
|
||||
)
|
||||
record = audio
|
||||
audio.startRecording()
|
||||
job = scope.launch(Dispatchers.IO) {
|
||||
val buffer = ByteArray(maxOf(min, 4096))
|
||||
while (isActive && pcm.size() < MAX_BYTES) {
|
||||
val read = audio.read(buffer, 0, buffer.size)
|
||||
if (read > 0) {
|
||||
pcm.write(buffer, 0, read)
|
||||
} else if (read < 0) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop, and the recording as a WAV file's bytes (empty if nothing was heard). */
|
||||
suspend fun stop(): ByteArray {
|
||||
val audio = record ?: return ByteArray(0)
|
||||
record = null
|
||||
// Stop first: that returns the blocked `read`, so the loop sees it is cancelled and
|
||||
// ends, and only then is the buffer read -- never while it is still being written.
|
||||
withContext(Dispatchers.IO) { runCatching { audio.stop() } }
|
||||
job?.cancel()
|
||||
job?.join()
|
||||
audio.release()
|
||||
val body = pcm.toByteArray()
|
||||
pcm.reset()
|
||||
return if (body.isEmpty()) body else wav(body)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val RATE = 16_000
|
||||
private const val MAX_BYTES = RATE * 2 * 120 // two minutes
|
||||
|
||||
fun wav(pcm: ByteArray): ByteArray {
|
||||
val header = ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN).apply {
|
||||
put("RIFF".toByteArray())
|
||||
putInt(36 + pcm.size)
|
||||
put("WAVE".toByteArray())
|
||||
put("fmt ".toByteArray())
|
||||
putInt(16)
|
||||
putShort(1)
|
||||
putShort(1)
|
||||
putInt(RATE)
|
||||
putInt(RATE * 2)
|
||||
putShort(2)
|
||||
putShort(16)
|
||||
put("data".toByteArray())
|
||||
putInt(pcm.size)
|
||||
}
|
||||
return header.array() + pcm
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Speech out: the instance's text-to-speech, played once. */
|
||||
class Speaker(private val context: Context) {
|
||||
private var player: MediaPlayer? = null
|
||||
|
||||
suspend fun play(mp3: ByteArray) {
|
||||
stop()
|
||||
val file = withContext(Dispatchers.IO) {
|
||||
File.createTempFile("reply", ".mp3", context.cacheDir).apply { writeBytes(mp3) }
|
||||
}
|
||||
player = MediaPlayer().apply {
|
||||
setAudioAttributes(
|
||||
AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ASSISTANT)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build(),
|
||||
)
|
||||
setDataSource(file.absolutePath)
|
||||
setOnCompletionListener {
|
||||
it.release()
|
||||
file.delete()
|
||||
player = null
|
||||
}
|
||||
prepare()
|
||||
start()
|
||||
}
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
player?.runCatching {
|
||||
stop()
|
||||
release()
|
||||
}
|
||||
player = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package eu.llembas.android.auth
|
||||
|
||||
import android.content.Context
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import android.util.Base64
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
import java.security.KeyStore
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
/** One instance this phone is signed in to. The token is stored encrypted, never in the clear. */
|
||||
@Serializable
|
||||
data class Instance(val id: String, val base: String, val name: String, val email: String, val sealedToken: String)
|
||||
|
||||
/**
|
||||
* The token's lock: an AES key that lives in the Android Keystore and never leaves it. A copy
|
||||
* of the app's data -- a backup, a rooted read of the files -- carries ciphertext only.
|
||||
*/
|
||||
object TokenCipher {
|
||||
private const val ALIAS = "lembas-token-key"
|
||||
private const val TRANSFORM = "AES/GCM/NoPadding"
|
||||
|
||||
private fun key(): SecretKey {
|
||||
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||
(store.getEntry(ALIAS, null) as? KeyStore.SecretKeyEntry)?.let { return it.secretKey }
|
||||
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
|
||||
generator.init(
|
||||
KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.setKeySize(256)
|
||||
.build(),
|
||||
)
|
||||
return generator.generateKey()
|
||||
}
|
||||
|
||||
fun seal(plain: String): String {
|
||||
val cipher = Cipher.getInstance(TRANSFORM).apply { init(Cipher.ENCRYPT_MODE, key()) }
|
||||
val sealed = cipher.iv + cipher.doFinal(plain.toByteArray(Charsets.UTF_8))
|
||||
return Base64.encodeToString(sealed, Base64.NO_WRAP)
|
||||
}
|
||||
|
||||
fun open(sealed: String): String {
|
||||
val bytes = Base64.decode(sealed, Base64.NO_WRAP)
|
||||
val cipher = Cipher.getInstance(TRANSFORM).apply {
|
||||
init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, bytes.copyOfRange(0, 12)))
|
||||
}
|
||||
return String(cipher.doFinal(bytes.copyOfRange(12, bytes.size)), Charsets.UTF_8)
|
||||
}
|
||||
}
|
||||
|
||||
private val Context.store by preferencesDataStore(name = "instances")
|
||||
private val INSTANCES = stringPreferencesKey("instances")
|
||||
private val ACTIVE = stringPreferencesKey("active")
|
||||
private val PREFS = stringPreferencesKey("prefs")
|
||||
|
||||
/** What the person chose in Settings, for this phone. */
|
||||
@Serializable
|
||||
data class Prefs(val theme: String = "", val assistantTemporary: Boolean = false, val readAloudSpoken: Boolean = true)
|
||||
|
||||
class InstanceStore(private val context: Context) {
|
||||
private val listSerializer = ListSerializer(Instance.serializer())
|
||||
|
||||
val instances: Flow<List<Instance>> = context.store.data.map { prefs ->
|
||||
prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
|
||||
}
|
||||
|
||||
val active: Flow<Instance?> = context.store.data.map { prefs ->
|
||||
val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
|
||||
all.firstOrNull { it.id == prefs[ACTIVE] } ?: all.firstOrNull()
|
||||
}
|
||||
|
||||
val prefs: Flow<Prefs> = context.store.data.map { p ->
|
||||
p[PREFS]?.let { runCatching { LembasJson.decodeFromString(Prefs.serializer(), it) }.getOrNull() } ?: Prefs()
|
||||
}
|
||||
|
||||
suspend fun current(): Instance? = active.first()
|
||||
|
||||
suspend fun client(): ApiClient? = current()?.let { clientFor(it) }
|
||||
|
||||
fun clientFor(instance: Instance): ApiClient = ApiClient(instance.base, TokenCipher.open(instance.sealedToken))
|
||||
|
||||
suspend fun add(base: String, name: String, email: String, token: String): Instance {
|
||||
val instance = Instance(
|
||||
id = "$email@$base",
|
||||
base = base,
|
||||
name = name,
|
||||
email = email,
|
||||
sealedToken = TokenCipher.seal(token),
|
||||
)
|
||||
context.store.edit { prefs ->
|
||||
val all = prefs[INSTANCES]?.let { LembasJson.decodeFromString(listSerializer, it) } ?: emptyList()
|
||||
prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, all.filter { it.id != instance.id } + instance)
|
||||
prefs[ACTIVE] = instance.id
|
||||
}
|
||||
return instance
|
||||
}
|
||||
|
||||
suspend fun use(id: String) {
|
||||
context.store.edit { it[ACTIVE] = id }
|
||||
}
|
||||
|
||||
suspend fun remove(id: String) {
|
||||
context.store.edit { prefs ->
|
||||
val all = prefs[INSTANCES]?.let { LembasJson.decodeFromString(listSerializer, it) } ?: emptyList()
|
||||
prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, all.filter { it.id != id })
|
||||
if (prefs[ACTIVE] == id) prefs.remove(ACTIVE)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun savePrefs(change: (Prefs) -> Prefs) {
|
||||
context.store.edit { p ->
|
||||
val now = p[PREFS]?.let { runCatching { LembasJson.decodeFromString(Prefs.serializer(), it) }.getOrNull() } ?: Prefs()
|
||||
p[PREFS] = LembasJson.encodeToString(Prefs.serializer(), change(now))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package eu.llembas.android.push
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.app.Notification
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import eu.llembas.android.LembasApp
|
||||
import eu.llembas.android.MainActivity
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.PushPayload
|
||||
import eu.llembas.android.auth.Instance
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import org.unifiedpush.android.connector.FailedReason
|
||||
import org.unifiedpush.android.connector.PushService
|
||||
import org.unifiedpush.android.connector.UnifiedPush
|
||||
import org.unifiedpush.android.connector.data.PushEndpoint
|
||||
import org.unifiedpush.android.connector.data.PushMessage
|
||||
|
||||
/** Work that outlives a callback: a registration, a notification's button. */
|
||||
private val background = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
|
||||
/**
|
||||
* Notifications without Google: UnifiedPush. The server already sends Web Push (RFC 8291,
|
||||
* signed with its VAPID key) to browsers, and a UnifiedPush endpoint *is* a Web Push endpoint,
|
||||
* so the server sends to this phone with the code it sends to a browser with. The distributor
|
||||
* (ntfy, or any other) carries the encrypted message; only this app can read it.
|
||||
*
|
||||
* One registration per instance, named by the instance's id.
|
||||
*/
|
||||
object Push {
|
||||
fun distributors(context: Context): List<String> = UnifiedPush.getDistributors(context)
|
||||
|
||||
/** Pick (or reuse) a distributor and register this instance with it. */
|
||||
fun enable(activity: Activity, instance: Instance, done: (Boolean) -> Unit) {
|
||||
background.launch {
|
||||
val key = runCatching { activity.lembas.instances.clientFor(instance).pushKey().key }.getOrNull()
|
||||
activity.runOnUiThread {
|
||||
UnifiedPush.tryUseCurrentOrDefaultDistributor(activity) { ok ->
|
||||
if (ok) {
|
||||
UnifiedPush.register(activity, instance.id, activity.getString(R.string.app_name), key?.takeIf { it.length == 87 })
|
||||
}
|
||||
done(ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun disable(context: Context, instance: Instance) {
|
||||
UnifiedPush.unregister(context, instance.id)
|
||||
background.launch { runCatching { context.lembas.instances.clientFor(instance).forgetPush() } }
|
||||
}
|
||||
|
||||
suspend fun instance(context: Context, id: String): Instance? = context.lembas.instances.instances.first().firstOrNull { it.id == id }
|
||||
}
|
||||
|
||||
class LembasPushService : PushService() {
|
||||
override fun onNewEndpoint(endpoint: PushEndpoint, instance: String) {
|
||||
val keys = endpoint.pubKeySet ?: return
|
||||
background.launch {
|
||||
val found = Push.instance(this@LembasPushService, instance) ?: return@launch
|
||||
runCatching { lembas.instances.clientFor(found).registerPush(endpoint.url, keys.pubKey, keys.auth) }
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMessage(message: PushMessage, instance: String) {
|
||||
if (!message.decrypted) return
|
||||
val payload = runCatching {
|
||||
LembasJson.decodeFromString(PushPayload.serializer(), message.content.toString(Charsets.UTF_8))
|
||||
}.getOrNull() ?: return
|
||||
Notifications.show(this, instance, payload)
|
||||
}
|
||||
|
||||
override fun onRegistrationFailed(reason: FailedReason, instance: String) = Unit
|
||||
|
||||
override fun onUnregistered(instance: String) {
|
||||
background.launch {
|
||||
val found = Push.instance(this@LembasPushService, instance) ?: return@launch
|
||||
runCatching { lembas.instances.clientFor(found).forgetPush() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
object Notifications {
|
||||
const val EXTRA_CHAT = "eu.llembas.android.CHAT"
|
||||
const val EXTRA_INSTANCE = "eu.llembas.android.INSTANCE"
|
||||
|
||||
fun show(context: Context, instance: String, payload: PushPayload) {
|
||||
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) return
|
||||
val chatId = payload.chatId ?: payload.url.removePrefix("/chat/").takeIf { payload.url.startsWith("/chat/") }
|
||||
val id = (chatId ?: payload.url).hashCode()
|
||||
val open = PendingIntent.getActivity(
|
||||
context,
|
||||
id,
|
||||
Intent(context, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
.putExtra(EXTRA_CHAT, chatId)
|
||||
.putExtra(EXTRA_INSTANCE, instance),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
val channel = when (payload.kind) {
|
||||
"ask" -> LembasApp.CHANNEL_ASKS
|
||||
"report" -> LembasApp.CHANNEL_REPORTS
|
||||
else -> LembasApp.CHANNEL_REPLIES
|
||||
}
|
||||
val builder = NotificationCompat.Builder(context, channel)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(payload.title)
|
||||
.setContentText(payload.body)
|
||||
.setStyle(NotificationCompat.BigTextStyle().bigText(payload.body))
|
||||
.setAutoCancel(true)
|
||||
.setContentIntent(open)
|
||||
.setCategory(if (payload.kind == "ask") Notification.CATEGORY_REMINDER else Notification.CATEGORY_MESSAGE)
|
||||
// The body can name a command or a file; on a locked screen only the title shows.
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
|
||||
// An approval can be answered from here: once, or no. "Always" and a corrected command
|
||||
// need the card itself, so they stay in the app.
|
||||
if (payload.kind == "ask" && payload.ask == "approval" && chatId != null && payload.interactionId != null) {
|
||||
builder.addAction(0, context.getString(R.string.card_allow_once), answer(context, instance, chatId, payload.interactionId, "allow", id))
|
||||
builder.addAction(0, context.getString(R.string.card_deny), answer(context, instance, chatId, payload.interactionId, "deny", id))
|
||||
}
|
||||
NotificationManagerCompat.from(context).notify(id, builder.build())
|
||||
}
|
||||
|
||||
private fun answer(context: Context, instance: String, chat: String, card: String, verdict: String, notification: Int): PendingIntent =
|
||||
PendingIntent.getBroadcast(
|
||||
context,
|
||||
(card + verdict).hashCode(),
|
||||
Intent(context, CardActionReceiver::class.java)
|
||||
.putExtra("instance", instance)
|
||||
.putExtra("chat", chat)
|
||||
.putExtra("card", card)
|
||||
.putExtra("verdict", verdict)
|
||||
.putExtra("notification", notification),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
}
|
||||
|
||||
/** A notification's Allow once / Deny: the same answer the card would send. */
|
||||
class CardActionReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val pending = goAsync()
|
||||
val instance = intent.getStringExtra("instance") ?: return pending.finish()
|
||||
val chat = intent.getStringExtra("chat") ?: return pending.finish()
|
||||
val card = intent.getStringExtra("card") ?: return pending.finish()
|
||||
val verdict = intent.getStringExtra("verdict") ?: return pending.finish()
|
||||
background.launch {
|
||||
try {
|
||||
val found = Push.instance(context, instance)
|
||||
if (found != null) {
|
||||
// A 409 means it was answered elsewhere first; either way the card is settled.
|
||||
runCatching { context.lembas.instances.clientFor(found).answer(chat, card, CardAnswer(verdict = verdict)) }
|
||||
}
|
||||
NotificationManagerCompat.from(context).cancel(intent.getIntExtra("notification", 0))
|
||||
} finally {
|
||||
pending.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package eu.llembas.android.share
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.provider.OpenableColumns
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.IntentCompat
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import eu.llembas.android.MainActivity
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.push.Notifications
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* "Share to LLeMbas": text, a link, a picture or a file from any app starts a new chat with it.
|
||||
* Files are uploaded first and bound to the first message, as the composer's are.
|
||||
*/
|
||||
class ShareActivity : ComponentActivity() {
|
||||
private val failure = mutableStateOf<String?>(null)
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContent {
|
||||
LembasTheme {
|
||||
Surface(Modifier.fillMaxSize()) {
|
||||
Column(
|
||||
Modifier.fillMaxSize().padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
val error = failure.value
|
||||
if (error == null) {
|
||||
CircularProgressIndicator()
|
||||
Text(stringResource(R.string.share_sending))
|
||||
} else {
|
||||
Text(error, color = MaterialTheme.colorScheme.error)
|
||||
TextButton(onClick = { finish() }) { Text(stringResource(R.string.close)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
lifecycleScope.launch { share(intent) }
|
||||
}
|
||||
|
||||
private suspend fun share(intent: Intent) {
|
||||
try {
|
||||
val api = lembas.instances.client() ?: run {
|
||||
startActivity(Intent(this, MainActivity::class.java))
|
||||
finish()
|
||||
return
|
||||
}
|
||||
val text = listOfNotNull(
|
||||
intent.getStringExtra(Intent.EXTRA_SUBJECT),
|
||||
intent.getStringExtra(Intent.EXTRA_TEXT),
|
||||
).joinToString("\n\n").trim()
|
||||
val uris = when (intent.action) {
|
||||
Intent.ACTION_SEND -> listOfNotNull(IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java))
|
||||
|
||||
Intent.ACTION_SEND_MULTIPLE ->
|
||||
IntentCompat.getParcelableArrayListExtra(intent, Intent.EXTRA_STREAM, Uri::class.java).orEmpty()
|
||||
|
||||
else -> emptyList()
|
||||
}
|
||||
val files = uris.map { uri ->
|
||||
val (name, bytes) = withContext(Dispatchers.IO) {
|
||||
val name = contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->
|
||||
if (c.moveToFirst()) c.getString(0) else null
|
||||
} ?: "shared"
|
||||
name to (contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0))
|
||||
}
|
||||
api.upload(name, contentResolver.getType(uri) ?: "application/octet-stream", bytes).id
|
||||
}
|
||||
if (text.isBlank() && files.isEmpty()) {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
val made = api.createChat(text.ifBlank { getString(R.string.share_default_prompt) }, files)
|
||||
startActivity(
|
||||
Intent(this, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
.putExtra(Notifications.EXTRA_CHAT, made.chat.id),
|
||||
)
|
||||
finish()
|
||||
} catch (e: Exception) {
|
||||
failure.value = e.message ?: e.javaClass.simpleName
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package eu.llembas.android.ui
|
||||
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.text.method.LinkMovementMethod
|
||||
import android.util.TypedValue
|
||||
import android.widget.TextView
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import io.noties.markwon.AbstractMarkwonPlugin
|
||||
import io.noties.markwon.Markwon
|
||||
import io.noties.markwon.MarkwonConfiguration
|
||||
import io.noties.markwon.core.MarkwonTheme
|
||||
import io.noties.markwon.ext.strikethrough.StrikethroughPlugin
|
||||
import io.noties.markwon.ext.tables.TablePlugin
|
||||
|
||||
/** Schemes a link from a model may open. Anything else -- `javascript:`, `intent:`, `file:` -- is inert. */
|
||||
private val OPENABLE = setOf("http", "https", "mailto")
|
||||
|
||||
/**
|
||||
* Markdown from a model, drawn natively. Model output is untrusted here exactly as on the web
|
||||
* page, so the rules are the server's: no images are loaded at all (an image URL can carry what
|
||||
* the model read out of a page to somebody else's server), raw HTML is shown as text (there is
|
||||
* no HTML plugin), and a link opens outside the app, in the browser, and only for the schemes
|
||||
* above.
|
||||
*/
|
||||
fun markwon(context: Context, codeBg: Int, link: Int): Markwon = Markwon.builder(context)
|
||||
.usePlugin(StrikethroughPlugin.create())
|
||||
.usePlugin(TablePlugin.create(context))
|
||||
.usePlugin(
|
||||
object : AbstractMarkwonPlugin() {
|
||||
override fun configureTheme(builder: MarkwonTheme.Builder) {
|
||||
builder.codeBackgroundColor(codeBg).codeBlockBackgroundColor(codeBg).linkColor(link)
|
||||
}
|
||||
|
||||
override fun configureConfiguration(builder: MarkwonConfiguration.Builder) {
|
||||
builder.linkResolver { view, url ->
|
||||
val uri = Uri.parse(url)
|
||||
if (uri.scheme?.lowercase() in OPENABLE) {
|
||||
try {
|
||||
view.context.startActivity(Intent(Intent.ACTION_VIEW, uri).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
} catch (_: ActivityNotFoundException) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
.build()
|
||||
|
||||
@Composable
|
||||
fun MarkdownText(markdown: String, modifier: Modifier = Modifier, color: Color? = null) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
val ink = (color ?: palette.ink).toArgb()
|
||||
val engine = remember(palette) { markwon(context, palette.codeBg.toArgb(), palette.accent.toArgb()) }
|
||||
AndroidView(
|
||||
modifier = modifier,
|
||||
factory = { ctx ->
|
||||
TextView(ctx).apply {
|
||||
setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f)
|
||||
setTextIsSelectable(true)
|
||||
movementMethod = LinkMovementMethod.getInstance()
|
||||
}
|
||||
},
|
||||
update = { view ->
|
||||
view.setTextColor(ink)
|
||||
engine.setMarkdown(view, markdown)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Article
|
||||
import androidx.compose.material.icons.filled.AttachFile
|
||||
import androidx.compose.material.icons.filled.Build
|
||||
import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.Groups
|
||||
import androidx.compose.material.icons.filled.Language
|
||||
import androidx.compose.material.icons.filled.Psychology
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.ToolCall
|
||||
import eu.llembas.android.ui.MarkdownText
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
|
||||
private val Rounded = RoundedCornerShape(10.dp)
|
||||
|
||||
/** The person's own turn: their words as typed (never markdown), and what they attached. */
|
||||
@Composable
|
||||
fun UserBubble(message: Message, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
Column(
|
||||
modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = 48.dp)
|
||||
.background(palette.bubbleUser, Rounded)
|
||||
.border(1.dp, palette.border, Rounded)
|
||||
.padding(12.dp),
|
||||
) {
|
||||
if (!message.text.isNullOrBlank()) Text(message.text, color = palette.ink)
|
||||
message.attachments.forEach { a ->
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 6.dp)) {
|
||||
Icon(Icons.Filled.AttachFile, contentDescription = null, modifier = Modifier.size(16.dp), tint = palette.inkMuted)
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Text(a.name, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
if (message.queued) {
|
||||
Text(stringResource(R.string.queued), style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A reply's steps, in the order they happened: the same table of contents the web page draws. */
|
||||
@Composable
|
||||
fun Steps(steps: List<Step>, modifier: Modifier = Modifier) {
|
||||
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
steps.forEach { step ->
|
||||
when (step.kind) {
|
||||
"thinking" -> Thinking(step)
|
||||
"text" -> MarkdownText(step.markdown.orEmpty(), modifier = Modifier.fillMaxWidth())
|
||||
"tools" -> step.calls.forEach { ToolCallBlock(it) }
|
||||
"steer" -> step.messages.forEach { Steered(it.text) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Thinking(step: Step) {
|
||||
val palette = LocalPalette.current
|
||||
var open by rememberSaveable(step.index, step.open) { mutableStateOf(false) }
|
||||
Column(
|
||||
Modifier.fillMaxWidth().background(palette.bgSunken, Rounded).clickable { open = !open }.padding(10.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Psychology, contentDescription = null, modifier = Modifier.size(16.dp), tint = palette.inkFaint)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
stringResource(if (step.open) R.string.thinking else R.string.thought) + (step.label?.let { " $it" } ?: ""),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = palette.inkMuted,
|
||||
)
|
||||
}
|
||||
AnimatedVisibility(open) {
|
||||
Text(step.text.orEmpty(), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, modifier = Modifier.padding(top = 6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Steered(text: String) {
|
||||
val palette = LocalPalette.current
|
||||
Row(Modifier.fillMaxWidth().padding(start = 24.dp)) {
|
||||
Text("↳ $text", style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
|
||||
private fun iconFor(kind: String): ImageVector = when (kind) {
|
||||
"shell" -> Icons.Filled.Terminal
|
||||
"edit" -> Icons.Filled.Edit
|
||||
"read" -> Icons.AutoMirrored.Filled.Article
|
||||
"search" -> Icons.Filled.Search
|
||||
"web" -> Icons.Filled.Language
|
||||
"task" -> Icons.Filled.Groups
|
||||
else -> Icons.Filled.Build
|
||||
}
|
||||
|
||||
/**
|
||||
* One tool call, the way its kind is read (`services/tool_blocks.py`): a command shows the
|
||||
* command, an edit its change, a read the file. What came back is behind a tap, in its own
|
||||
* scroller, so a megabyte of output never becomes the page.
|
||||
*/
|
||||
@Composable
|
||||
fun ToolCallBlock(call: ToolCall, depth: Int = 0) {
|
||||
val palette = LocalPalette.current
|
||||
var open by rememberSaveable(call.id ?: call.block.title) { mutableStateOf(call.block.kind == "edit") }
|
||||
val failed = call.status == "error" || !call.error.isNullOrEmpty()
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = (depth * 16).dp)
|
||||
.border(1.dp, if (failed) palette.danger else palette.border, Rounded)
|
||||
.clickable { open = !open }
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(iconFor(call.block.kind), contentDescription = null, modifier = Modifier.size(16.dp), tint = palette.inkMuted)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
call.block.title.ifBlank { call.name },
|
||||
fontFamily = if (call.block.kind == "shell") FontFamily.Monospace else null,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
maxLines = if (open) 6 else 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
call.block.chips.forEach { chip ->
|
||||
Text(chip, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, modifier = Modifier.padding(start = 6.dp))
|
||||
}
|
||||
}
|
||||
call.purpose?.takeIf { it.isNotBlank() }?.let {
|
||||
Text(it, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
|
||||
}
|
||||
AnimatedVisibility(open) {
|
||||
val output = listOfNotNull(call.diff, call.text, call.error).joinToString("\n").trim()
|
||||
Column {
|
||||
if (output.isNotEmpty()) {
|
||||
Text(
|
||||
output,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = 12.sp,
|
||||
color = if (failed) palette.danger else palette.ink,
|
||||
modifier = Modifier
|
||||
.padding(top = 8.dp)
|
||||
.fillMaxWidth()
|
||||
.heightIn(max = 320.dp)
|
||||
.background(palette.codeBg, Rounded)
|
||||
.verticalScroll(rememberScrollState())
|
||||
.horizontalScroll(rememberScrollState())
|
||||
.padding(8.dp),
|
||||
)
|
||||
}
|
||||
if (call.truncated) {
|
||||
Text(stringResource(R.string.output_cut), style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
|
||||
}
|
||||
call.children?.forEach { ToolCallBlock(it, depth + 1) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A finished or failed reply's foot: what it cost, and why it stopped if it did. */
|
||||
@Composable
|
||||
fun ReplyFoot(message: Message) {
|
||||
val palette = LocalPalette.current
|
||||
message.error?.let {
|
||||
Text(it, color = palette.danger, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
val m = message.metrics ?: return
|
||||
if (m.completionTokens == 0 && m.elapsedMs == 0L) return
|
||||
val parts = buildList {
|
||||
message.model?.let { add(it) }
|
||||
if (m.completionTokens > 0) add("${if (m.estimated) "~" else ""}${m.completionTokens} tok")
|
||||
if (m.tokPerSecond > 0) add("${"%.1f".format(m.tokPerSecond)} tok/s")
|
||||
if (m.percent > 0) add("${m.percent}%")
|
||||
}
|
||||
Text(parts.joinToString(" · "), style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, modifier = Modifier.widthIn(max = 600.dp))
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
@file:OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class, androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.RadioButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Card
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.CardItem
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.Plan
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
|
||||
/** The sentinel the web card's "Something else" row submits (`interaction.OTHER`). */
|
||||
private const val OTHER = "__other__"
|
||||
|
||||
/**
|
||||
* A card the reply is waiting on, with the controls the web page gives it. Whatever is pressed
|
||||
* becomes a [CardAnswer] in the page form's own terms, so the server reads it through the same
|
||||
* lines (`answer_card`) and first answer wins wherever it was given.
|
||||
*/
|
||||
@Composable
|
||||
fun CardSheet(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
Column(
|
||||
Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(20.dp).navigationBarsPadding(),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
if (card.why.isNotBlank()) {
|
||||
Text(card.why, style = MaterialTheme.typography.labelMedium, color = LocalPalette.current.inkMuted)
|
||||
}
|
||||
when (card.kind) {
|
||||
"approval" -> Approval(card, onAnswer)
|
||||
"plan" -> PlanCard(card, onAnswer)
|
||||
else -> Questions(card, onAnswer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Approval(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val edits = remember { mutableStateMapOf<String, String>() }
|
||||
var reason by remember { mutableStateOf("") }
|
||||
var refusing by remember { mutableStateOf(false) }
|
||||
Text(stringResource(R.string.card_approval), style = MaterialTheme.typography.titleMedium)
|
||||
card.items.forEach { item ->
|
||||
if (item.editable) {
|
||||
OutlinedTextField(
|
||||
value = edits[item.key] ?: item.title,
|
||||
onValueChange = { edits[item.key] = it },
|
||||
textStyle = MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
} else {
|
||||
Text(item.title, fontFamily = FontFamily.Monospace)
|
||||
}
|
||||
if (item.detail.isNotBlank()) Text(item.detail, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
if (item.purpose.isNotBlank()) Text(item.purpose, style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
}
|
||||
// A corrected command goes with an allow, never with a refusal.
|
||||
val texts = edits.filter { (key, value) -> card.items.firstOrNull { it.key == key }?.title != value }
|
||||
if (refusing) {
|
||||
OutlinedTextField(
|
||||
value = reason,
|
||||
onValueChange = { reason = it },
|
||||
label = { Text(stringResource(R.string.card_reason)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(onClick = { onAnswer(CardAnswer(verdict = "deny", reason = reason)) }) { Text(stringResource(R.string.card_deny)) }
|
||||
TextButton(onClick = { refusing = false }) { Text(stringResource(R.string.cancel)) }
|
||||
}
|
||||
} else {
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(onClick = { onAnswer(CardAnswer(verdict = "allow", texts = texts)) }) { Text(stringResource(R.string.card_allow_once)) }
|
||||
OutlinedButton(onClick = { onAnswer(CardAnswer(verdict = "allow_always", texts = texts)) }) {
|
||||
Text(stringResource(R.string.card_allow_always))
|
||||
}
|
||||
TextButton(onClick = { refusing = true }) { Text(stringResource(R.string.card_deny)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Questions(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val picked = remember { mutableStateMapOf<String, Set<String>>() }
|
||||
val typed = remember { mutableStateMapOf<String, String>() }
|
||||
card.items.forEach { item ->
|
||||
if (item.header.isNotBlank()) Text(item.header, style = MaterialTheme.typography.labelMedium, color = palette.inkMuted)
|
||||
Text(item.title, style = MaterialTheme.typography.titleMedium)
|
||||
item.options.forEach { option ->
|
||||
val chosen = option.label in (picked[item.key] ?: emptySet())
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().clickable { picked[item.key] = toggle(item, picked[item.key], option.label) },
|
||||
) {
|
||||
if (item.multiple) {
|
||||
Checkbox(checked = chosen, onCheckedChange = { picked[item.key] = toggle(item, picked[item.key], option.label) })
|
||||
} else {
|
||||
RadioButton(selected = chosen, onClick = { picked[item.key] = toggle(item, picked[item.key], option.label) })
|
||||
}
|
||||
Column {
|
||||
Text(option.label + if (option.recommended) " · " + stringResource(R.string.card_recommended) else "")
|
||||
if (option.description.isNotBlank()) {
|
||||
Text(option.description, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (item.freeText) {
|
||||
OutlinedTextField(
|
||||
value = typed[item.key].orEmpty(),
|
||||
onValueChange = { typed[item.key] = it },
|
||||
label = { Text(stringResource(if (item.options.isEmpty()) R.string.card_answer else R.string.card_something_else)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
val ready = card.items.all { !picked[it.key].isNullOrEmpty() || !typed[it.key].isNullOrBlank() }
|
||||
Button(
|
||||
enabled = ready,
|
||||
onClick = {
|
||||
val choices = card.items.associate { item ->
|
||||
val picks = picked[item.key].orEmpty().toList()
|
||||
// Typed beside options is "something else": the sentinel says so, as the page's does.
|
||||
item.key to if (!typed[item.key].isNullOrBlank() && item.options.isNotEmpty()) picks + OTHER else picks
|
||||
}.filterValues { it.isNotEmpty() }
|
||||
onAnswer(CardAnswer(choices = choices, texts = typed.filterValues { it.isNotBlank() }))
|
||||
},
|
||||
) { Text(stringResource(R.string.card_send)) }
|
||||
}
|
||||
|
||||
private fun toggle(item: CardItem, now: Set<String>?, label: String): Set<String> {
|
||||
val set = now.orEmpty()
|
||||
return when {
|
||||
!item.multiple -> setOf(label)
|
||||
label in set -> set - label
|
||||
else -> set + label
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PlanCard(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
val item = card.items.firstOrNull() ?: return
|
||||
var mode by remember { mutableStateOf("edit") }
|
||||
var revising by remember { mutableStateOf(false) }
|
||||
var feedback by remember { mutableStateOf("") }
|
||||
val plan = item.plan?.let { runCatching { LembasJson.decodeFromJsonElement(Plan.serializer(), it) }.getOrNull() }
|
||||
Text(plan?.title?.ifBlank { null } ?: item.title, style = MaterialTheme.typography.titleMedium)
|
||||
plan?.let { PlanBody(it) }
|
||||
if (item.modeChoice) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
RadioButton(selected = mode == "edit", onClick = { mode = "edit" })
|
||||
Text(stringResource(R.string.mode_edit))
|
||||
RadioButton(selected = mode == "manual", onClick = { mode = "manual" })
|
||||
Text(stringResource(R.string.mode_manual))
|
||||
}
|
||||
}
|
||||
if (revising) {
|
||||
OutlinedTextField(
|
||||
value = feedback,
|
||||
onValueChange = { feedback = it },
|
||||
label = { Text(stringResource(R.string.plan_what_to_change)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Button(onClick = { onAnswer(CardAnswer(verdict = "deny", reason = feedback)) }) { Text(stringResource(R.string.card_send)) }
|
||||
} else {
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(onClick = {
|
||||
onAnswer(CardAnswer(verdict = "allow", choices = if (item.modeChoice) mapOf(item.key to listOf(mode)) else emptyMap()))
|
||||
}) { Text(stringResource(R.string.plan_approve)) }
|
||||
OutlinedButton(onClick = { revising = true }) { Text(stringResource(R.string.plan_revise)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A plan's phases and tasks, ticked as the reply works through them. */
|
||||
@Composable
|
||||
fun PlanBody(plan: Plan) {
|
||||
val palette = LocalPalette.current
|
||||
if (plan.summary.isNotBlank()) Text(plan.summary, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
plan.phases.forEach { phase ->
|
||||
if (plan.phases.size > 1) Text(phase.title, style = MaterialTheme.typography.labelLarge)
|
||||
phase.tasks.forEach { task ->
|
||||
val mark = when (task.status) {
|
||||
"done" -> "✓"
|
||||
"doing" -> "▸"
|
||||
"dropped" -> "–"
|
||||
else -> "○"
|
||||
}
|
||||
Text("$mark ${task.text}", style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.pm.PackageManager
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.Send
|
||||
import androidx.compose.material.icons.filled.AttachFile
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.AssistChip
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.InputChip
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SheetValue
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TextField
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.assist.Recorder
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit = {}, model: ChatViewModel = viewModel(key = chatId ?: "new")) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
val palette = LocalPalette.current
|
||||
val list = rememberLazyListState()
|
||||
val snackbar = remember { SnackbarHostState() }
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
var editing by remember { mutableStateOf<Message?>(null) }
|
||||
|
||||
LaunchedEffect(chatId) { model.open(chatId) }
|
||||
// A new chat gets its id from its first message; the route follows, so Back and a
|
||||
// rotation land on the chat rather than on an empty composer.
|
||||
LaunchedEffect(state.chat?.id) { state.chat?.id?.let { if (it != chatId) onOpened(it) } }
|
||||
LaunchedEffect(state.error, state.notice) {
|
||||
(state.error ?: state.notice)?.let {
|
||||
snackbar.showSnackbar(it)
|
||||
model.clearError()
|
||||
}
|
||||
}
|
||||
val live = state.live
|
||||
val rows = state.messages
|
||||
LaunchedEffect(rows.size, live?.shown?.size) {
|
||||
if (rows.isNotEmpty()) list.animateScrollToItem(rows.size - 1)
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
snackbarHost = { SnackbarHost(snackbar) },
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
|
||||
}
|
||||
},
|
||||
title = {
|
||||
Text(
|
||||
state.chat?.title?.ifBlank { null } ?: stringResource(R.string.new_chat),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
},
|
||||
actions = {
|
||||
if (state.chat != null) {
|
||||
IconButton(onClick = { menu = true }) {
|
||||
Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.more))
|
||||
}
|
||||
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.continue_reply)) }, onClick = {
|
||||
menu = false
|
||||
model.continueChat()
|
||||
})
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.archive)) }, onClick = {
|
||||
menu = false
|
||||
model.change("archived", "true")
|
||||
onBack()
|
||||
})
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.delete)) }, onClick = {
|
||||
menu = false
|
||||
model.delete(onBack)
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
Column(Modifier.background(palette.surface).navigationBarsPadding().imePadding()) {
|
||||
if (state.loading || state.uploading) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
live?.plan?.let { plan ->
|
||||
Column(Modifier.fillMaxWidth().heightIn(max = 180.dp).padding(horizontal = 16.dp, vertical = 8.dp)) {
|
||||
PlanBody(plan)
|
||||
}
|
||||
}
|
||||
state.chat?.plan?.let { _ ->
|
||||
if (live == null && state.chat?.mode == "plan") {
|
||||
TextButton(onClick = { model.executePlan() }, modifier = Modifier.padding(horizontal = 8.dp)) {
|
||||
Text(stringResource(R.string.plan_carry_out))
|
||||
}
|
||||
}
|
||||
}
|
||||
if (live != null && live.jobs.isNotEmpty()) {
|
||||
Row(Modifier.horizontalScroll(rememberScrollState()).padding(horizontal = 12.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
live.jobs.forEach { job ->
|
||||
AssistChip(onClick = {}, label = { Text("${job.id} · ${job.description.ifBlank { job.command }} · ${job.state}", maxLines = 1) })
|
||||
}
|
||||
}
|
||||
}
|
||||
if (live != null && live.status.isNotBlank()) {
|
||||
Text(live.status, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, modifier = Modifier.padding(horizontal = 16.dp))
|
||||
}
|
||||
Composer(model, state)
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
LazyColumn(
|
||||
state = list,
|
||||
modifier = Modifier.fillMaxSize().padding(padding),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
if (state.more) {
|
||||
item { TextButton(onClick = model::older) { Text(stringResource(R.string.older)) } }
|
||||
}
|
||||
if (rows.isEmpty() && !state.loading) {
|
||||
item {
|
||||
Box(Modifier.fillMaxWidth().padding(top = 96.dp), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.empty_chat), color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
items(rows, key = { it.id }) { message ->
|
||||
when {
|
||||
message.isUser -> Column {
|
||||
UserBubble(message)
|
||||
if (!message.machine && live == null) {
|
||||
TextButton(onClick = { editing = message }, modifier = Modifier.align(Alignment.End)) {
|
||||
Text(stringResource(R.string.edit))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
live != null && live.messageId == message.id && live.finished == null -> Column {
|
||||
Steps(live.shown)
|
||||
if (live.shown.isEmpty()) Text(stringResource(R.string.loading_line), color = palette.inkFaint)
|
||||
live.metrics?.let { m -> ReplyFoot(message.copy(metrics = m)) }
|
||||
}
|
||||
|
||||
else -> Column {
|
||||
Steps(message.steps)
|
||||
ReplyFoot(message)
|
||||
if (live == null && message == rows.lastOrNull()) {
|
||||
Row {
|
||||
TextButton(onClick = { model.regenerate(message) }) { Text(stringResource(R.string.regenerate)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A card the reply is waiting on, as a sheet over the chat. One at a time, in the order asked.
|
||||
live?.cards?.firstOrNull()?.let { card ->
|
||||
ModalBottomSheet(
|
||||
onDismissRequest = {},
|
||||
// Not dismissable by a swipe: the reply is stopped until the card is answered, and
|
||||
// a card swiped away would leave it waiting with nothing on screen to say why.
|
||||
sheetState = rememberModalBottomSheetState(
|
||||
skipPartiallyExpanded = true,
|
||||
confirmValueChange = { it != SheetValue.Hidden },
|
||||
),
|
||||
) {
|
||||
CardSheet(card) { answer -> model.answer(card, answer) }
|
||||
}
|
||||
}
|
||||
|
||||
editing?.let { message ->
|
||||
var text by remember(message.id) { mutableStateOf(message.text.orEmpty()) }
|
||||
AlertDialog(
|
||||
onDismissRequest = { editing = null },
|
||||
title = { Text(stringResource(R.string.edit)) },
|
||||
text = { OutlinedTextField(value = text, onValueChange = { text = it }, modifier = Modifier.fillMaxWidth()) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
model.edit(message, text)
|
||||
editing = null
|
||||
}) { Text(stringResource(R.string.card_send)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { editing = null }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
@Composable
|
||||
private fun Composer(model: ChatViewModel, state: ChatState) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var text by rememberSaveable { mutableStateOf("") }
|
||||
var chosenModel by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var planMode by rememberSaveable { mutableStateOf(false) }
|
||||
var listening by remember { mutableStateOf(false) }
|
||||
val recorder = remember { Recorder(scope) }
|
||||
val pick = rememberLauncherForActivityResult(ActivityResultContracts.GetMultipleContents()) { model.attach(it) }
|
||||
val askMic = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (granted) {
|
||||
recorder.start()
|
||||
listening = true
|
||||
}
|
||||
}
|
||||
val chat = state.chat
|
||||
val current = chat?.model ?: chosenModel ?: state.models.firstOrNull { it.default }?.id
|
||||
val running = state.live != null && state.live.finished == null
|
||||
|
||||
Column(Modifier.fillMaxWidth().padding(8.dp)) {
|
||||
if (state.pending.isNotEmpty()) {
|
||||
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
state.pending.forEach { a ->
|
||||
InputChip(
|
||||
selected = false,
|
||||
onClick = { model.unattach(a) },
|
||||
label = { Text(a.name, maxLines = 1) },
|
||||
trailingIcon = { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.remove)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
ModelChip(state.models, current) { id ->
|
||||
if (chat == null) chosenModel = id else model.change("model", id)
|
||||
}
|
||||
val efforts = state.models.firstOrNull { it.id == current }?.efforts.orEmpty()
|
||||
if (efforts.isNotEmpty()) {
|
||||
EffortChip(efforts, chat?.effort) { model.change("effort", it ?: "off") }
|
||||
}
|
||||
if (chat == null || !chat.isAgent) {
|
||||
FilterChip(
|
||||
selected = if (chat == null) planMode else chat.mode == "plan",
|
||||
onClick = {
|
||||
if (chat == null) planMode = !planMode else model.change("mode", if (chat.mode == "plan") "" else "plan")
|
||||
},
|
||||
label = { Text(stringResource(R.string.mode_plan)) },
|
||||
)
|
||||
} else {
|
||||
AssistChip(onClick = {}, label = { Text(chat.mode.replaceFirstChar { it.uppercase() }) })
|
||||
}
|
||||
}
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
IconButton(onClick = { pick.launch("*/*") }) {
|
||||
Icon(Icons.Filled.AttachFile, contentDescription = stringResource(R.string.attach))
|
||||
}
|
||||
TextField(
|
||||
value = text,
|
||||
onValueChange = { text = it },
|
||||
placeholder = { Text(stringResource(if (listening) R.string.listening else R.string.composer_hint)) },
|
||||
modifier = Modifier.weight(1f).heightIn(max = 200.dp),
|
||||
)
|
||||
IconButton(onClick = {
|
||||
if (listening) {
|
||||
listening = false
|
||||
scope.launch {
|
||||
val wav = recorder.stop()
|
||||
if (wav.isNotEmpty()) {
|
||||
runCatching { context.lembas.instances.client()?.transcribe(wav) }
|
||||
.onSuccess { heard -> if (!heard.isNullOrBlank()) text = (text + " " + heard).trim() }
|
||||
}
|
||||
}
|
||||
} else if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
|
||||
recorder.start()
|
||||
listening = true
|
||||
} else {
|
||||
askMic.launch(Manifest.permission.RECORD_AUDIO)
|
||||
}
|
||||
}) {
|
||||
Icon(if (listening) Icons.Filled.Stop else Icons.Filled.Mic, contentDescription = stringResource(R.string.dictate))
|
||||
}
|
||||
if (running && text.isBlank()) {
|
||||
IconButton(onClick = model::stop) { Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop)) }
|
||||
} else {
|
||||
IconButton(
|
||||
enabled = text.isNotBlank() || state.pending.isNotEmpty(),
|
||||
onClick = {
|
||||
model.send(text, model = chosenModel, mode = if (planMode) "plan" else null)
|
||||
text = ""
|
||||
},
|
||||
) { Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ModelChip(models: List<ModelInfo>, current: String?, onPick: (String) -> Unit) {
|
||||
var open by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
AssistChip(onClick = { open = true }, label = { Text(models.firstOrNull { it.id == current }?.name ?: current ?: "—", maxLines = 1) })
|
||||
DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
|
||||
models.forEach { m ->
|
||||
DropdownMenuItem(text = { Text(m.name) }, onClick = {
|
||||
open = false
|
||||
onPick(m.id)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EffortChip(efforts: List<String>, current: String?, onPick: (String?) -> Unit) {
|
||||
var open by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
AssistChip(onClick = { open = true }, label = { Text(current ?: stringResource(R.string.effort_off)) })
|
||||
DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.effort_off)) }, onClick = {
|
||||
open = false
|
||||
onPick(null)
|
||||
})
|
||||
efforts.forEach { e ->
|
||||
DropdownMenuItem(text = { Text(e) }, onClick = {
|
||||
open = false
|
||||
onPick(e)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.app.Application
|
||||
import android.net.Uri
|
||||
import android.provider.OpenableColumns
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.Attachment
|
||||
import eu.llembas.android.api.Card
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.api.Turn
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
|
||||
data class ChatState(
|
||||
val chat: Chat? = null,
|
||||
val messages: List<Message> = emptyList(),
|
||||
val more: Boolean = false,
|
||||
val live: LiveReply? = null,
|
||||
val models: List<ModelInfo> = emptyList(),
|
||||
val pending: List<Attachment> = emptyList(),
|
||||
val uploading: Boolean = false,
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
/** A card somebody answered elsewhere first: said once, then cleared. */
|
||||
val notice: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* One chat: its transcript, the reply being written, and every control. A new chat has no id
|
||||
* until its first message makes it, as on the web page -- there is no empty chat.
|
||||
*/
|
||||
class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ChatState())
|
||||
val state = _state.asStateFlow()
|
||||
private var following: Job? = null
|
||||
private var api: ApiClient? = null
|
||||
|
||||
private suspend fun api(): ApiClient = api ?: getApplication<Application>().lembas.instances.client()?.also { api = it }
|
||||
?: throw ApiException(401, "Not signed in.")
|
||||
|
||||
private fun fail(e: Throwable) {
|
||||
_state.update { it.copy(error = e.message ?: e.javaClass.simpleName, loading = false, uploading = false) }
|
||||
}
|
||||
|
||||
fun clearError() = _state.update { it.copy(error = null, notice = null) }
|
||||
|
||||
fun open(chatId: String?) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val client = api()
|
||||
_state.update { it.copy(loading = chatId != null) }
|
||||
val models = runCatching { client.models(chatId) }.getOrDefault(emptyList())
|
||||
if (chatId == null) {
|
||||
_state.update { it.copy(models = models, loading = false) }
|
||||
return@launch
|
||||
}
|
||||
val detail = client.chat(chatId)
|
||||
_state.update {
|
||||
it.copy(chat = detail.chat, messages = detail.messages, more = detail.more, models = models, loading = false)
|
||||
}
|
||||
detail.live?.let { follow(it) }
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun older() {
|
||||
val chat = _state.value.chat ?: return
|
||||
val first = _state.value.messages.firstOrNull() ?: return
|
||||
viewModelScope.launch {
|
||||
runCatching { api().messages(chat.id, first.id) }
|
||||
.onSuccess { page -> _state.update { it.copy(messages = page.messages + it.messages, more = page.more) } }
|
||||
.onFailure(::fail)
|
||||
}
|
||||
}
|
||||
|
||||
/** Follow a reply to its end, then whatever the queue started after it. */
|
||||
private fun follow(messageId: String) {
|
||||
val chat = _state.value.chat ?: return
|
||||
following?.cancel()
|
||||
following = viewModelScope.launch {
|
||||
_state.update { it.copy(live = LiveReply(messageId)) }
|
||||
try {
|
||||
StreamClient(api()).follow(chat.id, messageId).collect { frame ->
|
||||
_state.update { s -> s.copy(live = (s.live ?: LiveReply(messageId)).apply(frame.event, frame.data)) }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
val ended = _state.value.live
|
||||
_state.update { s ->
|
||||
val finished = ended?.finished
|
||||
s.copy(
|
||||
live = null,
|
||||
messages = if (finished != null) s.messages.map { if (it.id == finished.id) finished else it } else s.messages,
|
||||
chat = s.chat?.let { c -> ended?.title?.let { c.copy(title = it) } ?: c },
|
||||
)
|
||||
}
|
||||
// The queue handed a waiting prompt to a fresh reply: the transcript has moved on
|
||||
// the server, so it is read again rather than patched.
|
||||
ended?.next?.let { next ->
|
||||
refresh()
|
||||
follow(next)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun refresh() {
|
||||
val chat = _state.value.chat ?: return
|
||||
runCatching { api().chat(chat.id) }.onSuccess { d ->
|
||||
_state.update { it.copy(chat = d.chat, messages = d.messages, more = d.more) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun took(turn: Turn) {
|
||||
_state.update { s ->
|
||||
s.copy(messages = s.messages.filterNot { m -> m.id == turn.message?.id || m.id == turn.reply?.id } + listOfNotNull(turn.message, turn.reply))
|
||||
}
|
||||
turn.reply?.let { follow(it.id) }
|
||||
}
|
||||
|
||||
fun send(text: String, model: String? = null, mode: String? = null, effort: String? = null, temporary: Boolean = false) {
|
||||
val files = _state.value.pending.map { it.id }
|
||||
if (text.isBlank() && files.isEmpty()) return
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val client = api()
|
||||
val chat = _state.value.chat
|
||||
_state.update { it.copy(pending = emptyList()) }
|
||||
if (chat == null) {
|
||||
val made = client.createChat(text, files, model = model, temporary = temporary, effort = effort, mode = mode)
|
||||
_state.update { it.copy(chat = made.chat, messages = listOfNotNull(made.message, made.reply)) }
|
||||
made.reply?.let { follow(it.id) }
|
||||
} else {
|
||||
took(client.sendMessage(chat.id, text, files))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
val chat = _state.value.chat ?: return
|
||||
val live = _state.value.live ?: return
|
||||
viewModelScope.launch { runCatching { api().stop(chat.id, live.messageId) }.onFailure(::fail) }
|
||||
}
|
||||
|
||||
fun regenerate(message: Message) = control { api, chat ->
|
||||
val turn = api.regenerate(chat.id, message.id)
|
||||
_state.update { s -> s.copy(messages = s.messages.map { if (it.id == message.id) turn.reply ?: it else it }) }
|
||||
turn.reply?.let { follow(it.id) }
|
||||
}
|
||||
|
||||
fun edit(message: Message, text: String) = control { api, chat ->
|
||||
val turn = api.edit(chat.id, message.id, text)
|
||||
// Everything after the edited turn is gone on the server; read it back.
|
||||
refresh()
|
||||
turn.reply?.let { follow(it.id) }
|
||||
}
|
||||
|
||||
fun continueChat() = control { api, chat -> took(api.continueChat(chat.id)) }
|
||||
|
||||
fun executePlan() = control { api, chat ->
|
||||
took(api.executePlan(chat.id))
|
||||
refresh()
|
||||
}
|
||||
|
||||
fun answer(card: Card, answer: CardAnswer) = control { api, chat ->
|
||||
try {
|
||||
api.answer(chat.id, card.id, answer)
|
||||
} catch (e: ApiException) {
|
||||
// First answer wins -- on the phone, the page or the device. A 409 is "somebody
|
||||
// already answered", and the stream's next `ask` frame clears the card.
|
||||
if (e.status != 409) throw e
|
||||
_state.update { it.copy(notice = e.message) }
|
||||
}
|
||||
_state.update { s -> s.copy(live = s.live?.let { l -> l.copy(cards = l.cards.filterNot { it.id == card.id }) }) }
|
||||
}
|
||||
|
||||
fun change(key: String, value: String?) = control { api, chat ->
|
||||
val updated = api.updateChat(chat.id, JsonObject(mapOf(key to JsonPrimitive(value))))
|
||||
_state.update { it.copy(chat = updated) }
|
||||
}
|
||||
|
||||
fun delete(then: () -> Unit) = control { api, chat ->
|
||||
api.deleteChat(chat.id)
|
||||
then()
|
||||
}
|
||||
|
||||
fun attach(uris: List<Uri>) {
|
||||
if (uris.isEmpty()) return
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(uploading = true) }
|
||||
try {
|
||||
val resolver = getApplication<Application>().contentResolver
|
||||
for (uri in uris) {
|
||||
val (name, bytes) = withContext(Dispatchers.IO) {
|
||||
val name = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->
|
||||
if (c.moveToFirst()) c.getString(0) else null
|
||||
} ?: "file"
|
||||
name to (resolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0))
|
||||
}
|
||||
val mime = resolver.getType(uri) ?: "application/octet-stream"
|
||||
val stored = api().upload(name, mime, bytes, _state.value.chat?.id)
|
||||
_state.update { it.copy(pending = it.pending + stored) }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
_state.update { it.copy(uploading = false) }
|
||||
}
|
||||
}
|
||||
|
||||
fun unattach(attachment: Attachment) {
|
||||
_state.update { s -> s.copy(pending = s.pending.filterNot { it.id == attachment.id }) }
|
||||
}
|
||||
|
||||
private fun control(block: suspend (ApiClient, Chat) -> Unit) {
|
||||
val chat = _state.value.chat ?: return
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
block(api(), chat)
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.chats
|
||||
|
||||
import android.app.Application
|
||||
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
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Chat
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.ExtendedFloatingActionButton
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.ListItem
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.PrimaryTabRow
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SwipeToDismissBox
|
||||
import androidx.compose.material3.Tab
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
|
||||
import androidx.compose.material3.rememberSwipeToDismissBoxState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
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.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.put
|
||||
|
||||
data class ChatsState(val chats: List<Chat> = emptyList(), val more: Boolean = false, val loading: Boolean = false, val error: String? = null)
|
||||
|
||||
class ChatsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ChatsState())
|
||||
val state = _state.asStateFlow()
|
||||
private var kind = "chat"
|
||||
|
||||
fun load(kind: String) {
|
||||
this.kind = kind
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val api = getApplication<Application>().lembas.instances.client() ?: return@launch
|
||||
val page = api.chats(kind = kind)
|
||||
_state.value = ChatsState(chats = page.chats, more = page.more)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = e.message) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun more() {
|
||||
val last = _state.value.chats.lastOrNull() ?: return
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val api = getApplication<Application>().lembas.instances.client() ?: return@launch
|
||||
val page = api.chats(kind = kind, before = last.id)
|
||||
_state.update { it.copy(chats = it.chats + page.chats, more = page.more) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = e.message) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Out of the way, and reversible: the web UI's Archive. */
|
||||
fun archive(chat: Chat) {
|
||||
_state.update { s -> s.copy(chats = s.chats.filterNot { it.id == chat.id }) }
|
||||
viewModelScope.launch {
|
||||
runCatching {
|
||||
getApplication<Application>().lembas.instances.client()
|
||||
?.updateChat(chat.id, buildJsonObject { put("archived", true) })
|
||||
}.onFailure { e ->
|
||||
_state.update { it.copy(error = e.message) }
|
||||
load(kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ChatsScreen(onOpen: (String) -> Unit, onNew: () -> Unit, onSettings: () -> Unit, model: ChatsViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
var tab by rememberSaveable { mutableIntStateOf(0) }
|
||||
val kind = if (tab == 0) "chat" else "agent"
|
||||
LaunchedEffect(kind) { model.load(kind) }
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.app_name)) },
|
||||
actions = {
|
||||
IconButton(onClick = onSettings) {
|
||||
Icon(Icons.Filled.Settings, contentDescription = stringResource(R.string.settings))
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
floatingActionButton = {
|
||||
if (tab == 0) {
|
||||
ExtendedFloatingActionButton(
|
||||
onClick = onNew,
|
||||
icon = { Icon(Icons.Filled.Add, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.new_chat)) },
|
||||
)
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.padding(padding).fillMaxSize()) {
|
||||
PrimaryTabRow(selectedTabIndex = tab) {
|
||||
Tab(selected = tab == 0, onClick = { tab = 0 }, text = { Text(stringResource(R.string.tab_chats)) })
|
||||
Tab(selected = tab == 1, onClick = { tab = 1 }, text = { Text(stringResource(R.string.tab_agents)) })
|
||||
}
|
||||
state.error?.let {
|
||||
Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
|
||||
}
|
||||
PullToRefreshBox(isRefreshing = state.loading, onRefresh = { model.load(kind) }, modifier = Modifier.fillMaxSize()) {
|
||||
if (state.chats.isEmpty() && !state.loading) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
stringResource(if (tab == 0) R.string.empty_chats else R.string.empty_agents),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(32.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.chats, key = { it.id }) { chat ->
|
||||
ChatRow(chat, onOpen = { onOpen(chat.id) }, onArchive = { model.archive(chat) })
|
||||
HorizontalDivider()
|
||||
}
|
||||
if (state.more) {
|
||||
item {
|
||||
LaunchedEffect(state.chats.size) { model.more() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ChatRow(chat: Chat, onOpen: () -> Unit, onArchive: () -> Unit) {
|
||||
val swipe = rememberSwipeToDismissBoxState()
|
||||
SwipeToDismissBox(state = swipe, onDismiss = { onArchive() }, backgroundContent = {
|
||||
Box(
|
||||
Modifier.fillMaxSize().background(MaterialTheme.colorScheme.surfaceContainerHigh).padding(horizontal = 24.dp),
|
||||
contentAlignment = Alignment.CenterStart,
|
||||
) {
|
||||
Text(stringResource(R.string.archive), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}) {
|
||||
ListItem(
|
||||
modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen),
|
||||
leadingContent = {
|
||||
Icon(
|
||||
if (chat.isAgent) Icons.Filled.Terminal else Icons.AutoMirrored.Filled.Chat,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
headlineContent = { Text(chat.title.ifBlank { stringResource(R.string.new_chat) }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
supportingContent = {
|
||||
val line = listOfNotNull(chat.model.ifBlank { null }, chat.device?.directory?.ifBlank { null }).joinToString(" · ")
|
||||
if (line.isNotEmpty()) Text(line, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
},
|
||||
trailingContent = {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
if (chat.unread || chat.running) {
|
||||
Box(
|
||||
Modifier.size(10.dp).clip(CircleShape).background(
|
||||
if (chat.running) MaterialTheme.colorScheme.secondary else MaterialTheme.colorScheme.primary,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.settings
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.provider.Settings
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.RadioButton
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.BuildConfig
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.push.Push
|
||||
import eu.llembas.android.update.Updater
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val store = context.lembas.instances
|
||||
val scope = rememberCoroutineScope()
|
||||
val instances by store.instances.collectAsState(initial = emptyList())
|
||||
val active by store.active.collectAsState(initial = null)
|
||||
val prefs by store.prefs.collectAsState(initial = Prefs())
|
||||
var pushNote by remember { mutableStateOf<String?>(null) }
|
||||
var updateNote by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.settings)) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) }
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(
|
||||
Modifier.padding(padding).fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Section(stringResource(R.string.settings_instances))
|
||||
instances.forEach { instance ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { scope.launch { store.use(instance.id) } },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
RadioButton(selected = instance.id == active?.id, onClick = { scope.launch { store.use(instance.id) } })
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(instance.name.ifBlank { instance.base })
|
||||
Text(
|
||||
"${instance.email} · ${instance.base}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
active?.let { current ->
|
||||
OutlinedButton(onClick = {
|
||||
scope.launch {
|
||||
Push.disable(context, current)
|
||||
runCatching { store.clientFor(current).signOut() }
|
||||
store.remove(current.id)
|
||||
}
|
||||
}) { Text(stringResource(R.string.sign_out)) }
|
||||
OutlinedButton(onClick = onAddInstance) {
|
||||
Text(stringResource(R.string.add_instance))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
Section(stringResource(R.string.settings_theme))
|
||||
listOf("" to R.string.theme_system, "moria" to R.string.theme_moria, "shire" to R.string.theme_shire).forEach { (value, label) ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { scope.launch { store.savePrefs { it.copy(theme = value) } } },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
RadioButton(selected = prefs.theme == value, onClick = { scope.launch { store.savePrefs { it.copy(theme = value) } } })
|
||||
Text(stringResource(label))
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
Section(stringResource(R.string.settings_notifications))
|
||||
val distributors = remember { Push.distributors(context) }
|
||||
Text(
|
||||
stringResource(if (distributors.isEmpty()) R.string.push_no_distributor else R.string.push_explained),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
active?.let { current ->
|
||||
Button(enabled = distributors.isNotEmpty(), onClick = {
|
||||
(context as? Activity)?.let { activity ->
|
||||
Push.enable(activity, current) { ok ->
|
||||
pushNote = context.getString(if (ok) R.string.push_on else R.string.push_failed)
|
||||
}
|
||||
}
|
||||
}) { Text(stringResource(R.string.push_enable)) }
|
||||
}
|
||||
pushNote?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
||||
|
||||
HorizontalDivider()
|
||||
Section(stringResource(R.string.settings_assistant))
|
||||
Text(stringResource(R.string.assistant_explained), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Button(onClick = {
|
||||
context.startActivity(Intent(Settings.ACTION_VOICE_INPUT_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}) { Text(stringResource(R.string.assistant_open_settings)) }
|
||||
Text(stringResource(R.string.assistant_samsung), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stringResource(R.string.assistant_temporary), modifier = Modifier.weight(1f))
|
||||
Switch(checked = prefs.assistantTemporary, onCheckedChange = { on -> scope.launch { store.savePrefs { it.copy(assistantTemporary = on) } } })
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stringResource(R.string.assistant_read_aloud), modifier = Modifier.weight(1f))
|
||||
Switch(checked = prefs.readAloudSpoken, onCheckedChange = { on -> scope.launch { store.savePrefs { it.copy(readAloudSpoken = on) } } })
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
Section(stringResource(R.string.settings_about))
|
||||
Text(stringResource(R.string.about_version, BuildConfig.VERSION_NAME))
|
||||
if (BuildConfig.SELF_UPDATE) {
|
||||
OutlinedButton(onClick = {
|
||||
scope.launch { updateNote = Updater(context).checkAndOffer() }
|
||||
}) { Text(stringResource(R.string.update_check)) }
|
||||
updateNote?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Section(title: String) {
|
||||
Text(title, style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.signin
|
||||
|
||||
import android.app.Application
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import androidx.browser.customtabs.CustomTabsIntent
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.safeDrawingPadding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Doorstep
|
||||
import eu.llembas.android.api.normaliseBase
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** Where the sign-in is. The token arrives once, by device code, as `lembas login` gets it. */
|
||||
sealed interface SignInState {
|
||||
data object Address : SignInState
|
||||
data object Finding : SignInState
|
||||
data class Code(val userCode: String, val verify: String) : SignInState
|
||||
data class Failed(val message: String) : SignInState
|
||||
data object Done : SignInState
|
||||
}
|
||||
|
||||
/** The newest API this app reads. A server with a newer one is told about, not guessed at. */
|
||||
const val APP_API = 1
|
||||
|
||||
class SignInViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow<SignInState>(SignInState.Address)
|
||||
val state = _state.asStateFlow()
|
||||
private var polling: Job? = null
|
||||
|
||||
fun start(typed: String) {
|
||||
polling?.cancel()
|
||||
polling = viewModelScope.launch {
|
||||
_state.value = SignInState.Finding
|
||||
val doorstep = Doorstep()
|
||||
try {
|
||||
val base = normaliseBase(typed)
|
||||
val found = doorstep.discover(base)
|
||||
if (found.service != "lembas" || found.appApi < 1 || "app" !in found.scopes) {
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_too_old))
|
||||
return@launch
|
||||
}
|
||||
if (found.appApi > APP_API) {
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_too_new))
|
||||
return@launch
|
||||
}
|
||||
val device = getApplication<Application>().getString(R.string.device_name)
|
||||
val code = doorstep.deviceCode(found.login.device.code, device, "${Build.MANUFACTURER} ${Build.MODEL}")
|
||||
_state.value = SignInState.Code(code.userCode, code.verificationUriComplete.ifEmpty { code.verificationUri })
|
||||
var interval = code.interval.coerceAtLeast(2) * 1000L
|
||||
val until = System.currentTimeMillis() + code.expiresIn * 1000L
|
||||
while (System.currentTimeMillis() < until) {
|
||||
delay(interval)
|
||||
val answer = doorstep.deviceToken(found.login.device.token, code.deviceCode)
|
||||
when {
|
||||
answer.accessToken != null -> {
|
||||
val account = answer.account
|
||||
getApplication<Application>().lembas.instances.add(
|
||||
base = found.baseUrl.ifEmpty { base }.trimEnd('/'),
|
||||
name = found.name,
|
||||
email = account?.email.orEmpty(),
|
||||
token = answer.accessToken,
|
||||
)
|
||||
_state.value = SignInState.Done
|
||||
return@launch
|
||||
}
|
||||
|
||||
answer.error == "slow_down" -> interval += 5000L
|
||||
|
||||
answer.error == "authorization_pending" -> Unit
|
||||
|
||||
answer.error == "access_denied" -> {
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_denied))
|
||||
return@launch
|
||||
}
|
||||
|
||||
else -> {
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_expired))
|
||||
return@launch
|
||||
}
|
||||
}
|
||||
}
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_expired))
|
||||
} catch (e: Exception) {
|
||||
_state.value = SignInState.Failed(e.message ?: e.javaClass.simpleName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun reset() {
|
||||
polling?.cancel()
|
||||
_state.value = SignInState.Address
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SignInScreen(onDone: () -> Unit = {}, model: SignInViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
LaunchedEffect(state) { if (state == SignInState.Done) onDone() }
|
||||
var address by rememberSaveable { mutableStateOf("") }
|
||||
val context = LocalContext.current
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize().safeDrawingPadding().imePadding().padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Text(stringResource(R.string.app_name), style = MaterialTheme.typography.headlineMedium)
|
||||
Text(
|
||||
stringResource(R.string.signin_intro),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.widthIn(max = 420.dp),
|
||||
)
|
||||
when (val s = state) {
|
||||
SignInState.Address, is SignInState.Failed -> {
|
||||
OutlinedTextField(
|
||||
value = address,
|
||||
onValueChange = { address = it },
|
||||
label = { Text(stringResource(R.string.signin_address)) },
|
||||
placeholder = { Text("llm.example.org") },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Go),
|
||||
keyboardActions = KeyboardActions(onGo = { if (address.isNotBlank()) model.start(address) }),
|
||||
modifier = Modifier.fillMaxWidth().widthIn(max = 420.dp),
|
||||
)
|
||||
if (s is SignInState.Failed) {
|
||||
Text(s.message, color = MaterialTheme.colorScheme.error, modifier = Modifier.widthIn(max = 420.dp))
|
||||
}
|
||||
Button(onClick = { model.start(address) }, enabled = address.isNotBlank()) {
|
||||
Text(stringResource(R.string.signin_continue))
|
||||
}
|
||||
}
|
||||
|
||||
SignInState.Finding, SignInState.Done -> CircularProgressIndicator()
|
||||
|
||||
is SignInState.Code -> {
|
||||
Text(stringResource(R.string.signin_code_intro), modifier = Modifier.widthIn(max = 420.dp))
|
||||
Text(s.userCode, fontFamily = FontFamily.Monospace, fontSize = 32.sp, style = MaterialTheme.typography.headlineLarge)
|
||||
Button(onClick = { CustomTabsIntent.Builder().build().launchUrl(context, Uri.parse(s.verify)) }) {
|
||||
Text(stringResource(R.string.signin_open_browser))
|
||||
}
|
||||
CircularProgressIndicator()
|
||||
OutlinedButton(onClick = { model.reset() }) { Text(stringResource(R.string.cancel)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package eu.llembas.android.ui.theme
|
||||
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.ColorScheme
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
|
||||
/** The palette in use, for the parts Material's scheme has no slot for (code, bubbles, soft tints). */
|
||||
val LocalPalette = staticCompositionLocalOf { Moria }
|
||||
|
||||
private fun scheme(p: Palette, dark: Boolean): ColorScheme {
|
||||
val base = if (dark) darkColorScheme() else lightColorScheme()
|
||||
return base.copy(
|
||||
primary = p.accent,
|
||||
onPrimary = p.accentInk,
|
||||
primaryContainer = p.accentSoft,
|
||||
onPrimaryContainer = p.ink,
|
||||
secondary = p.leaf,
|
||||
onSecondary = p.inkInverse,
|
||||
background = p.bg,
|
||||
onBackground = p.ink,
|
||||
surface = p.surface,
|
||||
onSurface = p.ink,
|
||||
surfaceVariant = p.surfaceRaised,
|
||||
onSurfaceVariant = p.inkMuted,
|
||||
surfaceContainerLowest = p.bgSunken,
|
||||
surfaceContainerLow = p.surface,
|
||||
surfaceContainer = p.surfaceRaised,
|
||||
surfaceContainerHigh = p.surfaceHover,
|
||||
surfaceContainerHighest = p.surfaceActive,
|
||||
outline = p.borderStrong,
|
||||
outlineVariant = p.border,
|
||||
error = p.danger,
|
||||
onError = p.inkInverse,
|
||||
errorContainer = p.dangerSoft,
|
||||
onErrorContainer = p.ink,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Moria (dark) or Shire (light), from the server's own tokens (`Tokens.kt`, generated). Dynamic
|
||||
* colour is off on purpose: the app looks like the web UI it sits beside, not like the wallpaper.
|
||||
* An empty choice follows the system's light or dark setting.
|
||||
*/
|
||||
@Composable
|
||||
fun LembasTheme(choice: String = "", content: @Composable () -> Unit) {
|
||||
val dark = when (choice) {
|
||||
"moria" -> true
|
||||
"shire" -> false
|
||||
else -> isSystemInDarkTheme()
|
||||
}
|
||||
val palette = if (dark) Moria else Shire
|
||||
CompositionLocalProvider(LocalPalette provides palette) {
|
||||
MaterialTheme(colorScheme = scheme(palette, dark), content = content)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v1.6.0. Do not edit.
|
||||
package eu.llembas.android.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
data class Palette(
|
||||
val bg: Color,
|
||||
val bgSunken: Color,
|
||||
val surface: Color,
|
||||
val surfaceRaised: Color,
|
||||
val surfaceHover: Color,
|
||||
val surfaceActive: Color,
|
||||
val border: Color,
|
||||
val borderStrong: Color,
|
||||
val ink: Color,
|
||||
val inkMuted: Color,
|
||||
val inkFaint: Color,
|
||||
val inkInverse: Color,
|
||||
val accent: Color,
|
||||
val accentHover: Color,
|
||||
val accentInk: Color,
|
||||
val accentSoft: Color,
|
||||
val leaf: Color,
|
||||
val danger: Color,
|
||||
val dangerSoft: Color,
|
||||
val success: Color,
|
||||
val successSoft: Color,
|
||||
val warning: Color,
|
||||
val warningSoft: Color,
|
||||
val bubbleUser: Color,
|
||||
val codeBg: Color,
|
||||
val codeBorder: Color,
|
||||
)
|
||||
|
||||
val Moria = Palette(
|
||||
bg = Color(0xFF0B0D10L),
|
||||
bgSunken = Color(0xFF07090BL),
|
||||
surface = Color(0xFF11151AL),
|
||||
surfaceRaised = Color(0xFF171C22L),
|
||||
surfaceHover = Color(0xFF1D232BL),
|
||||
surfaceActive = Color(0xFF232B34L),
|
||||
border = Color(0xFF26303AL),
|
||||
borderStrong = Color(0xFF5C6976L),
|
||||
ink = Color(0xFFE2E8ECL),
|
||||
inkMuted = Color(0xFFA6B2BCL),
|
||||
inkFaint = Color(0xFF808D98L),
|
||||
inkInverse = Color(0xFF07090BL),
|
||||
accent = Color(0xFF8FD8E8L),
|
||||
accentHover = Color(0xFFB4E6F1L),
|
||||
accentInk = Color(0xFF061418L),
|
||||
accentSoft = Color(0x1F8FD8E8L),
|
||||
leaf = Color(0xFF7EE081L),
|
||||
danger = Color(0xFFF0735FL),
|
||||
dangerSoft = Color(0x21F0735FL),
|
||||
success = Color(0xFF5FD6B0L),
|
||||
successSoft = Color(0x215FD6B0L),
|
||||
warning = Color(0xFFF0A840L),
|
||||
warningSoft = Color(0x21F0A840L),
|
||||
bubbleUser = Color(0xFF161C23L),
|
||||
codeBg = Color(0xFF07090BL),
|
||||
codeBorder = Color(0xFF26303AL),
|
||||
)
|
||||
|
||||
val Shire = Palette(
|
||||
bg = Color(0xFFF1EAD6L),
|
||||
bgSunken = Color(0xFFE7DEC6L),
|
||||
surface = Color(0xFFF8F3E5L),
|
||||
surfaceRaised = Color(0xFFFCF9F0L),
|
||||
surfaceHover = Color(0xFFECE4CFL),
|
||||
surfaceActive = Color(0xFFE2D8BDL),
|
||||
border = Color(0xFFCBBF9DL),
|
||||
borderStrong = Color(0xFF2A2E22L),
|
||||
ink = Color(0xFF1F2418L),
|
||||
inkMuted = Color(0xFF474D3BL),
|
||||
inkFaint = Color(0xFF5E6250L),
|
||||
inkInverse = Color(0xFFF8F3E5L),
|
||||
accent = Color(0xFF285F3CL),
|
||||
accentHover = Color(0xFF1F4D30L),
|
||||
accentInk = Color(0xFFF8F3E5L),
|
||||
accentSoft = Color(0x1A285F3CL),
|
||||
leaf = Color(0xFF3D6B1CL),
|
||||
danger = Color(0xFFA3321FL),
|
||||
dangerSoft = Color(0x1AA3321FL),
|
||||
success = Color(0xFF2B6A55L),
|
||||
successSoft = Color(0x1A2B6A55L),
|
||||
warning = Color(0xFF7E5200L),
|
||||
warningSoft = Color(0x1A7E5200L),
|
||||
bubbleUser = Color(0xFFECE4CFL),
|
||||
codeBg = Color(0xFFF1EAD6L),
|
||||
codeBorder = Color(0xFFCBBF9DL),
|
||||
)
|
||||
@@ -0,0 +1,136 @@
|
||||
package eu.llembas.android.update
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageInstaller
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.provider.Settings
|
||||
import eu.llembas.android.BuildConfig
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.SharedHttp
|
||||
import eu.llembas.android.api.await
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.Serializable
|
||||
import okhttp3.Request
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
|
||||
/** What llembas.eu says the newest release is (`site/android/latest.json`, written at release). */
|
||||
@Serializable
|
||||
data class Latest(val version: String, val url: String, val sha256: String, val notes: String = "")
|
||||
|
||||
/**
|
||||
* The `full` build updates itself, as LLeMbas Desktop does: the manifest on the website names
|
||||
* the newest APK and its SHA-256. The download is checked against that hash and its signer
|
||||
* against this app's own before Android's installer is asked -- which refuses a different
|
||||
* signer on its own as well. The `fdroid` build never runs this: F-Droid updates it.
|
||||
*/
|
||||
class Updater(private val context: Context) {
|
||||
suspend fun checkAndOffer(): String = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val latest = SharedHttp.newCall(Request.Builder().url(MANIFEST).build()).await().use {
|
||||
if (!it.isSuccessful) return@withContext context.getString(R.string.update_unreachable)
|
||||
LembasJson.decodeFromString(Latest.serializer(), it.body!!.string())
|
||||
}
|
||||
if (!newer(latest.version, BuildConfig.VERSION_NAME.removeSuffix("-debug"))) {
|
||||
return@withContext context.getString(R.string.update_none)
|
||||
}
|
||||
if (!context.packageManager.canRequestPackageInstalls()) {
|
||||
context.startActivity(
|
||||
Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:${context.packageName}"))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
return@withContext context.getString(R.string.update_allow_installs)
|
||||
}
|
||||
val apk = File(context.cacheDir, "update.apk")
|
||||
SharedHttp.newCall(Request.Builder().url(latest.url).build()).await().use { response ->
|
||||
if (!response.isSuccessful) return@withContext context.getString(R.string.update_unreachable)
|
||||
apk.outputStream().use { out -> response.body!!.byteStream().copyTo(out) }
|
||||
}
|
||||
if (sha256(apk) != latest.sha256.lowercase()) {
|
||||
apk.delete()
|
||||
return@withContext context.getString(R.string.update_bad_file)
|
||||
}
|
||||
if (!sameSigner(apk)) {
|
||||
apk.delete()
|
||||
return@withContext context.getString(R.string.update_bad_file)
|
||||
}
|
||||
install(apk)
|
||||
context.getString(R.string.update_installing, latest.version)
|
||||
} catch (e: Exception) {
|
||||
e.message ?: context.getString(R.string.update_unreachable)
|
||||
}
|
||||
}
|
||||
|
||||
private fun sha256(file: File): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
file.inputStream().use { input ->
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
digest.update(buffer, 0, read)
|
||||
}
|
||||
}
|
||||
return digest.digest().joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
private fun sameSigner(apk: File): Boolean {
|
||||
val pm = context.packageManager
|
||||
val flags = PackageManager.GET_SIGNING_CERTIFICATES
|
||||
val theirs = pm.getPackageArchiveInfo(apk.path, flags)?.signingInfo?.apkContentsSigners ?: return false
|
||||
val ours = pm.getPackageInfo(context.packageName, flags).signingInfo?.apkContentsSigners ?: return false
|
||||
return theirs.map { it.toCharsString() }.toSet() == ours.map { it.toCharsString() }.toSet()
|
||||
}
|
||||
|
||||
private fun install(apk: File) {
|
||||
val installer = context.packageManager.packageInstaller
|
||||
val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL)
|
||||
val id = installer.createSession(params)
|
||||
installer.openSession(id).use { session ->
|
||||
session.openWrite("update.apk", 0, apk.length()).use { out ->
|
||||
apk.inputStream().use { it.copyTo(out) }
|
||||
session.fsync(out)
|
||||
}
|
||||
val status = PendingIntent.getBroadcast(
|
||||
context,
|
||||
id,
|
||||
Intent(context, InstallStatusReceiver::class.java),
|
||||
PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
session.commit(status.intentSender)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val MANIFEST = "https://llembas.eu/android/latest.json"
|
||||
|
||||
/** Whether `a` is a later x.y.z than `b`. */
|
||||
fun newer(a: String, b: String): Boolean {
|
||||
val left = a.split(".").map { it.toIntOrNull() ?: 0 }
|
||||
val right = b.split(".").map { it.toIntOrNull() ?: 0 }
|
||||
for (i in 0 until maxOf(left.size, right.size)) {
|
||||
val l = left.getOrElse(i) { 0 }
|
||||
val r = right.getOrElse(i) { 0 }
|
||||
if (l != r) return l > r
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The installer's answer. Asking the person to confirm is the usual one, and it is shown. */
|
||||
class InstallStatusReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.getIntExtra(PackageInstaller.EXTRA_STATUS, -1) == PackageInstaller.STATUS_PENDING_USER_ACTION) {
|
||||
@Suppress("DEPRECATION")
|
||||
val confirm = intent.getParcelableExtra<Intent>(Intent.EXTRA_INTENT) ?: return
|
||||
context.startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-icons.py from the LLeMbas server's logo-mark.svg. Do not edit. -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp" android:height="108dp"
|
||||
android:viewportWidth="108" android:viewportHeight="108">
|
||||
<group android:translateX="26" android:translateY="26" android:scaleX="3.5" android:scaleY="3.5">
|
||||
<path android:fillColor="#0B0D10" android:pathData="M10,0h5v1h-5z M8,1h2v1h-2z M15,1h1v1h-1z M6,2h2v1h-2z M15,2h1v1h-1z M5,3h1v1h-1z M15,3h1v1h-1z M5,4h1v1h-1z M14,4h1v1h-1z M4,5h1v1h-1z M14,5h1v1h-1z M4,6h1v1h-1z M14,6h1v1h-1z M3,7h1v1h-1z M13,7h1v1h-1z M3,8h1v1h-1z M12,8h1v1h-1z M3,9h1v1h-1z M11,9h1v1h-1z M3,10h1v1h-1z M10,10h1v1h-1z M3,11h1v1h-1z M7,11h3v1h-3z M2,12h1v1h-1z M4,12h3v1h-3z M1,13h1v1h-1z M3,13h1v1h-1z M0,14h1v1h-1z M2,14h1v1h-1z M1,15h1v1h-1z"/>
|
||||
<path android:fillColor="#4FAE5A" android:pathData="M14,2h1v1h-1z M13,3h2v1h-2z M12,4h2v1h-2z M11,5h3v1h-3z M10,6h4v1h-4z M9,7h4v1h-4z M8,8h4v1h-4z M7,9h4v1h-4z M6,10h4v1h-4z M5,11h2v1h-2z M3,12h1v1h-1z M2,13h1v1h-1z M1,14h1v1h-1z"/>
|
||||
<path android:fillColor="#7EE081" android:pathData="M11,1h4v1h-4z M10,2h2v1h-2z M9,3h2v1h-2z M8,4h2v1h-2z M7,5h2v1h-2z M6,6h2v1h-2z M5,7h2v1h-2z M4,8h2v1h-2z M4,9h1v1h-1z M4,11h1v1h-1z"/>
|
||||
<path android:fillColor="#B6F2A6" android:pathData="M10,1h1v1h-1z M8,2h2v1h-2z M6,3h3v1h-3z M6,4h2v1h-2z M5,5h2v1h-2z M5,6h1v1h-1z M4,7h1v1h-1z"/>
|
||||
<path android:fillColor="#D8FFD0" android:pathData="M12,2h2v1h-2z M11,3h2v1h-2z M10,4h2v1h-2z M9,5h2v1h-2z M8,6h2v1h-2z M7,7h2v1h-2z M6,8h2v1h-2z M5,9h2v1h-2z M4,10h2v1h-2z"/>
|
||||
</group>
|
||||
</vector>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-icons.py from the LLeMbas server's logo-mark.svg. Do not edit. -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp" android:height="108dp"
|
||||
android:viewportWidth="108" android:viewportHeight="108">
|
||||
<group android:translateX="26" android:translateY="26" android:scaleX="3.5" android:scaleY="3.5">
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M10,0h5v1h-5z M8,1h2v1h-2z M10,1h1v1h-1z M11,1h4v1h-4z M15,1h1v1h-1z M6,2h2v1h-2z M8,2h2v1h-2z M10,2h2v1h-2z M12,2h2v1h-2z M14,2h1v1h-1z M15,2h1v1h-1z M5,3h1v1h-1z M6,3h3v1h-3z M9,3h2v1h-2z M11,3h2v1h-2z M13,3h2v1h-2z M15,3h1v1h-1z M5,4h1v1h-1z M6,4h2v1h-2z M8,4h2v1h-2z M10,4h2v1h-2z M12,4h2v1h-2z M14,4h1v1h-1z M4,5h1v1h-1z M5,5h2v1h-2z M7,5h2v1h-2z M9,5h2v1h-2z M11,5h3v1h-3z M14,5h1v1h-1z M4,6h1v1h-1z M5,6h1v1h-1z M6,6h2v1h-2z M8,6h2v1h-2z M10,6h4v1h-4z M14,6h1v1h-1z M3,7h1v1h-1z M4,7h1v1h-1z M5,7h2v1h-2z M7,7h2v1h-2z M9,7h4v1h-4z M13,7h1v1h-1z M3,8h1v1h-1z M4,8h2v1h-2z M6,8h2v1h-2z M8,8h4v1h-4z M12,8h1v1h-1z M3,9h1v1h-1z M4,9h1v1h-1z M5,9h2v1h-2z M7,9h4v1h-4z M11,9h1v1h-1z M3,10h1v1h-1z M4,10h2v1h-2z M6,10h4v1h-4z M10,10h1v1h-1z M3,11h1v1h-1z M4,11h1v1h-1z M5,11h2v1h-2z M7,11h3v1h-3z M2,12h1v1h-1z M3,12h1v1h-1z M4,12h3v1h-3z M1,13h1v1h-1z M2,13h1v1h-1z M3,13h1v1h-1z M0,14h1v1h-1z M1,14h1v1h-1z M2,14h1v1h-1z M1,15h1v1h-1z"/>
|
||||
</group>
|
||||
</vector>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-icons.py from the LLeMbas server's logo-mark.svg. Do not edit. -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp" android:height="24dp"
|
||||
android:viewportWidth="16" android:viewportHeight="16">
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M10,0h5v1h-5z M8,1h2v1h-2z M10,1h1v1h-1z M11,1h4v1h-4z M15,1h1v1h-1z M6,2h2v1h-2z M8,2h2v1h-2z M10,2h2v1h-2z M12,2h2v1h-2z M14,2h1v1h-1z M15,2h1v1h-1z M5,3h1v1h-1z M6,3h3v1h-3z M9,3h2v1h-2z M11,3h2v1h-2z M13,3h2v1h-2z M15,3h1v1h-1z M5,4h1v1h-1z M6,4h2v1h-2z M8,4h2v1h-2z M10,4h2v1h-2z M12,4h2v1h-2z M14,4h1v1h-1z M4,5h1v1h-1z M5,5h2v1h-2z M7,5h2v1h-2z M9,5h2v1h-2z M11,5h3v1h-3z M14,5h1v1h-1z M4,6h1v1h-1z M5,6h1v1h-1z M6,6h2v1h-2z M8,6h2v1h-2z M10,6h4v1h-4z M14,6h1v1h-1z M3,7h1v1h-1z M4,7h1v1h-1z M5,7h2v1h-2z M7,7h2v1h-2z M9,7h4v1h-4z M13,7h1v1h-1z M3,8h1v1h-1z M4,8h2v1h-2z M6,8h2v1h-2z M8,8h4v1h-4z M12,8h1v1h-1z M3,9h1v1h-1z M4,9h1v1h-1z M5,9h2v1h-2z M7,9h4v1h-4z M11,9h1v1h-1z M3,10h1v1h-1z M4,10h2v1h-2z M6,10h4v1h-4z M10,10h1v1h-1z M3,11h1v1h-1z M4,11h1v1h-1z M5,11h2v1h-2z M7,11h3v1h-3z M2,12h1v1h-1z M3,12h1v1h-1z M4,12h3v1h-3z M1,13h1v1h-1z M2,13h1v1h-1z M3,13h1v1h-1z M0,14h1v1h-1z M1,14h1v1h-1z M2,14h1v1h-1z M1,15h1v1h-1z"/>
|
||||
</vector>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
<monochrome android:drawable="@drawable/ic_launcher_monochrome" />
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->
|
||||
<resources>
|
||||
<string name="device_name">LLeMbas pro Android</string>
|
||||
<string name="share_label">Zeptat se LLeMbas</string>
|
||||
<string name="tile_ask">Zeptat se LLeMbas</string>
|
||||
<string name="signin_intro">Přihlaste se k instanci LLeMbas. Tento telefon schválíte v prohlížeči, stejně jako u CLI.</string>
|
||||
<string name="signin_address">Adresa instance</string>
|
||||
<string name="signin_continue">Pokračovat</string>
|
||||
<string name="signin_code_intro">Otevřete instanci v prohlížeči, přihlaste se a schvalte tento kód:</string>
|
||||
<string name="signin_open_browser">Otevřít v prohlížeči</string>
|
||||
<string name="signin_denied">Přihlášení bylo odmítnuto.</string>
|
||||
<string name="signin_expired">Kód vypršel, než byl schválen. Zkuste to znovu.</string>
|
||||
<string name="signin_too_old">Tato instance ještě nemá rozhraní API pro aplikace. Potřebuje LLeMbas 1.7.0 nebo novější.</string>
|
||||
<string name="signin_too_new">Tato instance používá novější rozhraní API pro aplikace než tato aplikace. Aktualizujte aplikaci.</string>
|
||||
<string name="new_chat">Nová konverzace</string>
|
||||
<string name="tab_chats">Konverzace</string>
|
||||
<string name="tab_agents">Agenti</string>
|
||||
<string name="empty_chats">Zatím žádné konverzace. Ne všichni, kdo bloudí, jsou ztraceni — založte jednu.</string>
|
||||
<string name="empty_agents">Žádné konverzace s agentem. Spusťte jednu z webového rozhraní na propojeném zařízení.</string>
|
||||
<string name="empty_chat">O čem si promluvíme?</string>
|
||||
<string name="loading_line">Pečou se lembasy…</string>
|
||||
<string name="archive">Archivovat</string>
|
||||
<string name="delete">Smazat</string>
|
||||
<string name="edit">Upravit</string>
|
||||
<string name="regenerate">Vygenerovat znovu</string>
|
||||
<string name="continue_reply">Pokračovat</string>
|
||||
<string name="older">Starší zprávy</string>
|
||||
<string name="queued">Čeká na odeslání</string>
|
||||
<string name="thinking">Přemýšlí</string>
|
||||
<string name="thought">Přemýšlel</string>
|
||||
<string name="output_cut">Výstup je zde zkrácen. Celý ho najdete na webové stránce.</string>
|
||||
<string name="composer_hint">Zpráva</string>
|
||||
<string name="listening">Naslouchám…</string>
|
||||
<string name="send">Odeslat</string>
|
||||
<string name="stop">Zastavit</string>
|
||||
<string name="attach">Přiložit soubor</string>
|
||||
<string name="dictate">Diktovat</string>
|
||||
<string name="remove">Odebrat</string>
|
||||
<string name="more">Více</string>
|
||||
<string name="back">Zpět</string>
|
||||
<string name="cancel">Zrušit</string>
|
||||
<string name="close">Zavřít</string>
|
||||
<string name="effort_off">Úsilí: vypnuto</string>
|
||||
<string name="mode_plan">Plán</string>
|
||||
<string name="mode_edit">Upravit</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="card_approval">Povolit to?</string>
|
||||
<string name="card_allow_once">Povolit jednou</string>
|
||||
<string name="card_allow_always">Toto vždy povolit</string>
|
||||
<string name="card_deny">Zamítnout</string>
|
||||
<string name="card_reason">Proč ne? (nepovinné)</string>
|
||||
<string name="card_recommended">doporučeno</string>
|
||||
<string name="card_answer">Vaše odpověď</string>
|
||||
<string name="card_something_else">Něco jiného</string>
|
||||
<string name="card_send">Odeslat</string>
|
||||
<string name="plan_approve">Schválit plán</string>
|
||||
<string name="plan_revise">Přepracovat</string>
|
||||
<string name="plan_what_to_change">Co by se mělo změnit?</string>
|
||||
<string name="plan_carry_out">Provést plán</string>
|
||||
<string name="settings">Nastavení</string>
|
||||
<string name="settings_instances">Instance</string>
|
||||
<string name="sign_out">Odhlásit se</string>
|
||||
<string name="add_instance">Přidat instanci</string>
|
||||
<string name="settings_theme">Vzhled</string>
|
||||
<string name="theme_system">Podle systému</string>
|
||||
<string name="theme_moria">Moria (temná)</string>
|
||||
<string name="theme_shire">Shire (světlý)</string>
|
||||
<string name="settings_notifications">Upozornění</string>
|
||||
<string name="push_explained">Upozornění chodí přes UnifiedPush, bez služeb Google: doručuje je distribuční aplikace, kterou jste zvolili; jsou zašifrované jen pro tento telefon.</string>
|
||||
<string name="push_no_distributor">Abyste se dozvěděli, že je odpověď hotová, nainstalujte distributora UnifiedPush, například ntfy, a pak se vraťte sem. Bez něj aplikace nové odpovědi ukáže, jen když je otevřená.</string>
|
||||
<string name="push_enable">Zapnout upozornění</string>
|
||||
<string name="push_on">Upozornění jsou pro tuto instanci zapnutá.</string>
|
||||
<string name="push_failed">Nebyl zvolen žádný distributor, takže upozornění jsou stále vypnutá.</string>
|
||||
<string name="channel_replies">Odpovědi</string>
|
||||
<string name="channel_asks">Otázky a schválení</string>
|
||||
<string name="channel_reports">Zprávy</string>
|
||||
<string name="settings_assistant">Asistent</string>
|
||||
<string name="assistant_explained">Nastavte LLeMbas jako digitálního asistenta telefonu: zvolte ho v Výchozí aplikace › Digitální asistent. Podržení tlačítka napájení, gesto asistenta nebo zkratka na zamykací obrazovce ho pak otevře přes to, co je právě na obrazovce.</string>
|
||||
<string name="assistant_open_settings">Otevřít nastavení asistenta</string>
|
||||
<string name="assistant_samsung">Na telefonech Samsung: Nastavení › Pokročilé funkce › Boční tlačítko › Stisknutí a podržení › Digitální asistent.</string>
|
||||
<string name="assistant_temporary">Konverzace s asistentem jsou dočasné</string>
|
||||
<string name="assistant_read_aloud">Přečíst odpověď nahlas, když se zeptáte hlasem</string>
|
||||
<string name="settings_about">O aplikaci</string>
|
||||
<string name="about_version">LLeMbas pro Android %1$s</string>
|
||||
<string name="update_check">Zkontrolovat aktualizaci</string>
|
||||
<string name="update_none">Toto je nejnovější verze.</string>
|
||||
<string name="update_unreachable">Aktualizaci se nepodařilo stáhnout.</string>
|
||||
<string name="update_allow_installs">Povolte aplikaci LLeMbas instalovat aktualizace a pak to zkontrolujte znovu.</string>
|
||||
<string name="update_bad_file">Stažený soubor neodpovídal verzi a byl zahozen.</string>
|
||||
<string name="update_installing">Instaluje se %1$s…</string>
|
||||
<string name="assist_hint">Zeptejte se na cokoli</string>
|
||||
<string name="assist_include_screen">Zahrnout obrazovku</string>
|
||||
<string name="assist_signed_out">Nejprve se v aplikaci přihlaste k instanci LLeMbas.</string>
|
||||
<string name="assist_open_app">Otevřít aplikaci</string>
|
||||
<string name="assist_open_in_app">Pokračovat v aplikaci</string>
|
||||
<string name="share_sending">Odesílá se do LLeMbas…</string>
|
||||
<string name="share_default_prompt">Podívejte se na tohle.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->
|
||||
<resources>
|
||||
<string name="device_name">LLeMbas für Android</string>
|
||||
<string name="share_label">LLeMbas fragen</string>
|
||||
<string name="tile_ask">LLeMbas fragen</string>
|
||||
<string name="signin_intro">Melden Sie sich bei einer LLeMbas-Instanz an. Sie bestätigen dieses Telefon im Browser, genau wie bei der CLI.</string>
|
||||
<string name="signin_address">Adresse der Instanz</string>
|
||||
<string name="signin_continue">Fortsetzen</string>
|
||||
<string name="signin_code_intro">Öffnen Sie die Instanz im Browser, melden Sie sich an und bestätigen Sie diesen Code:</string>
|
||||
<string name="signin_open_browser">Im Browser öffnen</string>
|
||||
<string name="signin_denied">Die Anmeldung wurde abgelehnt.</string>
|
||||
<string name="signin_expired">Der Code ist abgelaufen, bevor er bestätigt wurde. Versuchen Sie es erneut.</string>
|
||||
<string name="signin_too_old">Diese Instanz hat noch keine App-API. Sie braucht LLeMbas 1.7.0 oder neuer.</string>
|
||||
<string name="signin_too_new">Diese Instanz spricht eine neuere App-API als diese App. Aktualisieren Sie die App.</string>
|
||||
<string name="new_chat">Neuer Chat</string>
|
||||
<string name="tab_chats">Chats</string>
|
||||
<string name="tab_agents">Agenten</string>
|
||||
<string name="empty_chats">Noch keine Chats. Nicht jeder, der wandert, ist verloren — fangen Sie einen an.</string>
|
||||
<string name="empty_agents">Keine Agent-Chats. Starten Sie einen über die Weboberfläche auf einem verknüpften Gerät.</string>
|
||||
<string name="empty_chat">Worüber sprechen wir?</string>
|
||||
<string name="loading_line">Lembas wird gebacken…</string>
|
||||
<string name="archive">Archivieren</string>
|
||||
<string name="delete">Löschen</string>
|
||||
<string name="edit">Bearbeiten</string>
|
||||
<string name="regenerate">Neu generieren</string>
|
||||
<string name="continue_reply">Fortsetzen</string>
|
||||
<string name="older">Frühere Nachrichten</string>
|
||||
<string name="queued">Wartet auf das Senden</string>
|
||||
<string name="thinking">Denkt nach</string>
|
||||
<string name="thought">Nachgedacht</string>
|
||||
<string name="output_cut">Die Ausgabe ist hier verkürzt. Vollständig finden Sie sie auf der Webseite.</string>
|
||||
<string name="composer_hint">Nachricht</string>
|
||||
<string name="listening">Hört zu…</string>
|
||||
<string name="send">Senden</string>
|
||||
<string name="stop">Stoppen</string>
|
||||
<string name="attach">Datei anhängen</string>
|
||||
<string name="dictate">Diktieren</string>
|
||||
<string name="remove">Entfernen</string>
|
||||
<string name="more">Mehr</string>
|
||||
<string name="back">Zurück</string>
|
||||
<string name="cancel">Abbrechen</string>
|
||||
<string name="close">Schließen</string>
|
||||
<string name="effort_off">Aufwand: aus</string>
|
||||
<string name="mode_plan">Tarif</string>
|
||||
<string name="mode_edit">Bearbeiten</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="card_approval">Das erlauben?</string>
|
||||
<string name="card_allow_once">Einmal erlauben</string>
|
||||
<string name="card_allow_always">Dies immer erlauben</string>
|
||||
<string name="card_deny">Ablehnen</string>
|
||||
<string name="card_reason">Warum nicht? (optional)</string>
|
||||
<string name="card_recommended">empfohlen</string>
|
||||
<string name="card_answer">Ihre Antwort</string>
|
||||
<string name="card_something_else">Etwas anderes</string>
|
||||
<string name="card_send">Senden</string>
|
||||
<string name="plan_approve">Plan bestätigen</string>
|
||||
<string name="plan_revise">Überarbeiten</string>
|
||||
<string name="plan_what_to_change">Was soll sich ändern?</string>
|
||||
<string name="plan_carry_out">Plan ausführen</string>
|
||||
<string name="settings">Einstellungen</string>
|
||||
<string name="settings_instances">Instanzen</string>
|
||||
<string name="sign_out">Abmelden</string>
|
||||
<string name="add_instance">Instanz hinzufügen</string>
|
||||
<string name="settings_theme">Design</string>
|
||||
<string name="theme_system">Wie das System</string>
|
||||
<string name="theme_moria">Moria (dunkel)</string>
|
||||
<string name="theme_shire">Shire (hell)</string>
|
||||
<string name="settings_notifications">Benachrichtigungen</string>
|
||||
<string name="push_explained">Benachrichtigungen kommen über UnifiedPush, ohne Google-Dienste: Die von Ihnen gewählte Distributor-App trägt sie, verschlüsselt nur für dieses Telefon.</string>
|
||||
<string name="push_no_distributor">Um erfahren zu lassen, wenn eine Antwort fertig ist, installieren Sie einen UnifiedPush-Distributor wie ntfy und kommen Sie dann hierher zurück. Ohne einen zeigt die App neue Antworten nur, wenn sie geöffnet ist.</string>
|
||||
<string name="push_enable">Benachrichtigungen einschalten</string>
|
||||
<string name="push_on">Benachrichtigungen sind für diese Instanz eingeschaltet.</string>
|
||||
<string name="push_failed">Es wurde kein Distributor gewählt, daher sind die Benachrichtigungen noch ausgeschaltet.</string>
|
||||
<string name="channel_replies">Antworten</string>
|
||||
<string name="channel_asks">Fragen und Bestätigungen</string>
|
||||
<string name="channel_reports">Berichte</string>
|
||||
<string name="settings_assistant">Assistent</string>
|
||||
<string name="assistant_explained">Machen Sie LLeMbas zum digitalen Assistenten des Telefons: Wählen Sie ihn unter Standard-Apps › Digitaler Assistent. Das Halten der Einschalttaste, die Assistenzgeste oder die Verknüpfung auf dem Sperrbildschirm öffnet ihn dann über allem, was gerade angezeigt wird.</string>
|
||||
<string name="assistant_open_settings">Assistenten-Einstellungen öffnen</string>
|
||||
<string name="assistant_samsung">Auf Samsung-Telefonen: Einstellungen › Erweiterte Funktionen › Seitentaste › Gedrückt halten › Digitaler Assistent.</string>
|
||||
<string name="assistant_temporary">Assistenten-Chats sind temporär</string>
|
||||
<string name="assistant_read_aloud">Antwort vorlesen, wenn per Sprache gefragt wurde</string>
|
||||
<string name="settings_about">Über</string>
|
||||
<string name="about_version">LLeMbas für Android %1$s</string>
|
||||
<string name="update_check">Nach einem Update suchen</string>
|
||||
<string name="update_none">Dies ist die neueste Version.</string>
|
||||
<string name="update_unreachable">Das Update konnte nicht abgerufen werden.</string>
|
||||
<string name="update_allow_installs">Erlauben Sie LLeMbas, Updates zu installieren, und prüfen Sie dann erneut.</string>
|
||||
<string name="update_bad_file">Der Download stimmte nicht mit der Version überein und wurde verworfen.</string>
|
||||
<string name="update_installing">%1$s wird installiert…</string>
|
||||
<string name="assist_hint">Fragen Sie irgendetwas</string>
|
||||
<string name="assist_include_screen">Bildschirm einbeziehen</string>
|
||||
<string name="assist_signed_out">Melden Sie sich zuerst in der App bei einer LLeMbas-Instanz an.</string>
|
||||
<string name="assist_open_app">App öffnen</string>
|
||||
<string name="assist_open_in_app">In der App fortsetzen</string>
|
||||
<string name="share_sending">Wird an LLeMbas gesendet…</string>
|
||||
<string name="share_default_prompt">Schauen Sie sich das an.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->
|
||||
<resources>
|
||||
<string name="device_name">LLeMbas para Android</string>
|
||||
<string name="share_label">Preguntar a LLeMbas</string>
|
||||
<string name="tile_ask">Preguntar a LLeMbas</string>
|
||||
<string name="signin_intro">Inicie sesión en una instancia de LLeMbas. Aprobará este teléfono en el navegador, igual que haría con la CLI.</string>
|
||||
<string name="signin_address">Dirección de la instancia</string>
|
||||
<string name="signin_continue">Continuar</string>
|
||||
<string name="signin_code_intro">Abra la instancia en el navegador, inicie sesión y apruebe este código:</string>
|
||||
<string name="signin_open_browser">Abrir en el navegador</string>
|
||||
<string name="signin_denied">El inicio de sesión fue rechazado.</string>
|
||||
<string name="signin_expired">El código caducó antes de ser aprobado. Inténtelo de nuevo.</string>
|
||||
<string name="signin_too_old">Esta instancia aún no tiene API para aplicaciones. Necesita LLeMbas 1.7.0 o una versión posterior.</string>
|
||||
<string name="signin_too_new">Esta instancia habla una API de aplicaciones más reciente que esta aplicación. Actualice la aplicación.</string>
|
||||
<string name="new_chat">Nuevo chat</string>
|
||||
<string name="tab_chats">Chats</string>
|
||||
<string name="tab_agents">Agentes</string>
|
||||
<string name="empty_chats">Aún no hay chats. No todos los que vagan están perdidos — empiece uno.</string>
|
||||
<string name="empty_agents">No hay chats de agente. Inicie uno desde la interfaz web en un dispositivo vinculado.</string>
|
||||
<string name="empty_chat">¿De qué hablamos?</string>
|
||||
<string name="loading_line">Horneando lembas…</string>
|
||||
<string name="archive">Archivar</string>
|
||||
<string name="delete">Eliminar</string>
|
||||
<string name="edit">Editar</string>
|
||||
<string name="regenerate">Regenerar</string>
|
||||
<string name="continue_reply">Continuar</string>
|
||||
<string name="older">Mensajes anteriores</string>
|
||||
<string name="queued">Esperando para enviarse</string>
|
||||
<string name="thinking">Pensando</string>
|
||||
<string name="thought">Pensamiento</string>
|
||||
<string name="output_cut">La salida está acortada aquí. La tiene completa en la página web.</string>
|
||||
<string name="composer_hint">Mensaje</string>
|
||||
<string name="listening">Escuchando…</string>
|
||||
<string name="send">Enviar</string>
|
||||
<string name="stop">Detener</string>
|
||||
<string name="attach">Adjuntar un archivo</string>
|
||||
<string name="dictate">Dictar</string>
|
||||
<string name="remove">Quitar</string>
|
||||
<string name="more">Más</string>
|
||||
<string name="back">Volver</string>
|
||||
<string name="cancel">Cancelar</string>
|
||||
<string name="close">Cerrar</string>
|
||||
<string name="effort_off">Esfuerzo: desactivado</string>
|
||||
<string name="mode_plan">Plan</string>
|
||||
<string name="mode_edit">Editar</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="card_approval">¿Permitir esto?</string>
|
||||
<string name="card_allow_once">Permitir una vez</string>
|
||||
<string name="card_allow_always">Permitir siempre esto</string>
|
||||
<string name="card_deny">Denegar</string>
|
||||
<string name="card_reason">¿Por qué no? (opcional)</string>
|
||||
<string name="card_recommended">recomendado</string>
|
||||
<string name="card_answer">Su respuesta</string>
|
||||
<string name="card_something_else">Otra cosa</string>
|
||||
<string name="card_send">Enviar</string>
|
||||
<string name="plan_approve">Aprobar el plan</string>
|
||||
<string name="plan_revise">Revisar</string>
|
||||
<string name="plan_what_to_change">¿Qué debería cambiar?</string>
|
||||
<string name="plan_carry_out">Llevar a cabo el plan</string>
|
||||
<string name="settings">Ajustes</string>
|
||||
<string name="settings_instances">Instancias</string>
|
||||
<string name="sign_out">Cerrar sesión</string>
|
||||
<string name="add_instance">Añadir una instancia</string>
|
||||
<string name="settings_theme">Tema</string>
|
||||
<string name="theme_system">Como el sistema</string>
|
||||
<string name="theme_moria">Moria (oscuro)</string>
|
||||
<string name="theme_shire">Shire (claro)</string>
|
||||
<string name="settings_notifications">Notificaciones</string>
|
||||
<string name="push_explained">Las notificaciones llegan mediante UnifiedPush, sin servicios de Google: la aplicación distribuidora que eligió las transporta, cifradas solo para este teléfono.</string>
|
||||
<string name="push_no_distributor">Para que le avisen cuando una respuesta esté lista, instale un distribuidor de UnifiedPush como ntfy y luego vuelva aquí. Sin uno, la aplicación muestra las respuestas nuevas solo cuando está abierta.</string>
|
||||
<string name="push_enable">Activar las notificaciones</string>
|
||||
<string name="push_on">Las notificaciones están activadas para esta instancia.</string>
|
||||
<string name="push_failed">No se eligió ningún distribuidor, así que las notificaciones siguen desactivadas.</string>
|
||||
<string name="channel_replies">Respuestas</string>
|
||||
<string name="channel_asks">Preguntas y aprobaciones</string>
|
||||
<string name="channel_reports">Informes</string>
|
||||
<string name="settings_assistant">Asistente</string>
|
||||
<string name="assistant_explained">Convierta LLeMbas en el asistente digital del teléfono: elíjalo en Aplicaciones predeterminadas › App de asistencia digital. Mantener pulsado el botón de encendido, el gesto de asistencia o el acceso directo de la pantalla de bloqueo lo abrirá entonces sobre lo que haya en pantalla.</string>
|
||||
<string name="assistant_open_settings">Abrir los ajustes del asistente</string>
|
||||
<string name="assistant_samsung">En los teléfonos Samsung: Ajustes › Funciones avanzadas › Botón lateral › Mantener pulsado › Asistente digital.</string>
|
||||
<string name="assistant_temporary">Los chats del asistente son temporales</string>
|
||||
<string name="assistant_read_aloud">Leer la respuesta en voz alta cuando se pregunte por voz</string>
|
||||
<string name="settings_about">Acerca de</string>
|
||||
<string name="about_version">LLeMbas para Android %1$s</string>
|
||||
<string name="update_check">Buscar una actualización</string>
|
||||
<string name="update_none">Esta es la versión más reciente.</string>
|
||||
<string name="update_unreachable">No se pudo obtener la actualización.</string>
|
||||
<string name="update_allow_installs">Permita que LLeMbas instale actualizaciones y vuelva a comprobarlo.</string>
|
||||
<string name="update_bad_file">La descarga no coincidía con la versión y se descartó.</string>
|
||||
<string name="update_installing">Instalando %1$s…</string>
|
||||
<string name="assist_hint">Pregunte lo que quiera</string>
|
||||
<string name="assist_include_screen">Incluir pantalla</string>
|
||||
<string name="assist_signed_out">Primero inicie sesión en una instancia de LLeMbas en la aplicación.</string>
|
||||
<string name="assist_open_app">Abrir la aplicación</string>
|
||||
<string name="assist_open_in_app">Continuar en la aplicación</string>
|
||||
<string name="share_sending">Enviando a LLeMbas…</string>
|
||||
<string name="share_default_prompt">Échele un vistazo a esto.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->
|
||||
<resources>
|
||||
<string name="device_name">LLeMbas pour Android</string>
|
||||
<string name="share_label">Demander à LLeMbas</string>
|
||||
<string name="tile_ask">Demander à LLeMbas</string>
|
||||
<string name="signin_intro">Connectez-vous à une instance LLeMbas. Vous approuvez ce téléphone dans le navigateur, comme vous le feriez pour la CLI.</string>
|
||||
<string name="signin_address">Adresse de l\'instance</string>
|
||||
<string name="signin_continue">Continuer</string>
|
||||
<string name="signin_code_intro">Ouvrez l\'instance dans le navigateur, connectez-vous et approuvez ce code :</string>
|
||||
<string name="signin_open_browser">Ouvrir dans le navigateur</string>
|
||||
<string name="signin_denied">La connexion a été refusée.</string>
|
||||
<string name="signin_expired">Le code a expiré avant d\'être approuvé. Réessayez.</string>
|
||||
<string name="signin_too_old">Cette instance n\'a pas encore d\'API pour l\'application. Elle nécessite LLeMbas 1.7.0 ou une version plus récente.</string>
|
||||
<string name="signin_too_new">Cette instance utilise une API d\'application plus récente que cette application. Mettez à jour l\'application.</string>
|
||||
<string name="new_chat">Nouvelle conversation</string>
|
||||
<string name="tab_chats">Conversations</string>
|
||||
<string name="tab_agents">Agents</string>
|
||||
<string name="empty_chats">Pas encore de conversation. Tous ceux qui errent ne sont pas perdus — commencez-en une.</string>
|
||||
<string name="empty_agents">Aucune conversation d\'agent. Démarrez-en une depuis l\'interface web sur un appareil associé.</string>
|
||||
<string name="empty_chat">De quoi allons-nous parler ?</string>
|
||||
<string name="loading_line">Cuisson des lembas…</string>
|
||||
<string name="archive">Archiver</string>
|
||||
<string name="delete">Supprimer</string>
|
||||
<string name="edit">Modifier</string>
|
||||
<string name="regenerate">Régénérer</string>
|
||||
<string name="continue_reply">Continuer</string>
|
||||
<string name="older">Messages précédents</string>
|
||||
<string name="queued">En attente d\'envoi</string>
|
||||
<string name="thinking">Réflexion</string>
|
||||
<string name="thought">Réflexion</string>
|
||||
<string name="output_cut">La sortie est raccourcie ici. Vous la trouverez en entier sur la page web.</string>
|
||||
<string name="composer_hint">Message</string>
|
||||
<string name="listening">Écoute…</string>
|
||||
<string name="send">Envoyer</string>
|
||||
<string name="stop">Arrêter</string>
|
||||
<string name="attach">Joindre un fichier</string>
|
||||
<string name="dictate">Dicter</string>
|
||||
<string name="remove">Retirer</string>
|
||||
<string name="more">Plus</string>
|
||||
<string name="back">Retour</string>
|
||||
<string name="cancel">Annuler</string>
|
||||
<string name="close">Fermer</string>
|
||||
<string name="effort_off">Effort : désactivé</string>
|
||||
<string name="mode_plan">Forfait</string>
|
||||
<string name="mode_edit">Modifier</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="card_approval">Autoriser ceci ?</string>
|
||||
<string name="card_allow_once">Autoriser une fois</string>
|
||||
<string name="card_allow_always">Toujours autoriser ceci</string>
|
||||
<string name="card_deny">Refuser</string>
|
||||
<string name="card_reason">Pourquoi pas ? (facultatif)</string>
|
||||
<string name="card_recommended">recommandé</string>
|
||||
<string name="card_answer">Votre réponse</string>
|
||||
<string name="card_something_else">Autre chose</string>
|
||||
<string name="card_send">Envoyer</string>
|
||||
<string name="plan_approve">Approuver le plan</string>
|
||||
<string name="plan_revise">Réviser</string>
|
||||
<string name="plan_what_to_change">Qu\'est-ce qui doit changer ?</string>
|
||||
<string name="plan_carry_out">Exécuter le plan</string>
|
||||
<string name="settings">Paramètres</string>
|
||||
<string name="settings_instances">Instances</string>
|
||||
<string name="sign_out">Se déconnecter</string>
|
||||
<string name="add_instance">Ajouter une instance</string>
|
||||
<string name="settings_theme">Thème</string>
|
||||
<string name="theme_system">Comme le système</string>
|
||||
<string name="theme_moria">Moria (sombre)</string>
|
||||
<string name="theme_shire">Shire (clair)</string>
|
||||
<string name="settings_notifications">Notifications</string>
|
||||
<string name="push_explained">Les notifications arrivent par UnifiedPush, sans services Google : l\'application distributrice que vous avez choisie les transporte, chiffrées pour ce téléphone uniquement.</string>
|
||||
<string name="push_no_distributor">Pour être averti quand une réponse est prête, installez un distributeur UnifiedPush tel que ntfy, puis revenez ici. Sans cela, l\'application affiche les nouvelles réponses seulement quand elle est ouverte.</string>
|
||||
<string name="push_enable">Activer les notifications</string>
|
||||
<string name="push_on">Les notifications sont activées pour cette instance.</string>
|
||||
<string name="push_failed">Aucun distributeur n\'a été choisi, les notifications sont donc toujours désactivées.</string>
|
||||
<string name="channel_replies">Réponses</string>
|
||||
<string name="channel_asks">Questions et approbations</string>
|
||||
<string name="channel_reports">Rapports</string>
|
||||
<string name="settings_assistant">Assistant</string>
|
||||
<string name="assistant_explained">Faites de LLeMbas l\'assistant numérique du téléphone : choisissez-le dans Applications par défaut › Application d\'assistance numérique. Maintenir le bouton d\'alimentation, le geste d\'assistance ou le raccourci de l\'écran de verrouillage l\'ouvrira alors par-dessus ce qui est affiché.</string>
|
||||
<string name="assistant_open_settings">Ouvrir les paramètres de l\'assistant</string>
|
||||
<string name="assistant_samsung">Sur les téléphones Samsung : Paramètres › Fonctions avancées › Bouton latéral › Maintenir enfoncé › Assistant numérique.</string>
|
||||
<string name="assistant_temporary">Les conversations de l\'assistant sont temporaires</string>
|
||||
<string name="assistant_read_aloud">Lire la réponse à voix haute en cas de question orale</string>
|
||||
<string name="settings_about">À propos</string>
|
||||
<string name="about_version">LLeMbas pour Android %1$s</string>
|
||||
<string name="update_check">Rechercher une mise à jour</string>
|
||||
<string name="update_none">C\'est la version la plus récente.</string>
|
||||
<string name="update_unreachable">La mise à jour n\'a pas pu être récupérée.</string>
|
||||
<string name="update_allow_installs">Autorisez LLeMbas à installer des mises à jour, puis vérifiez à nouveau.</string>
|
||||
<string name="update_bad_file">Le téléchargement ne correspondait pas à la version et a été rejeté.</string>
|
||||
<string name="update_installing">Installation de %1$s…</string>
|
||||
<string name="assist_hint">Demandez n\'importe quoi</string>
|
||||
<string name="assist_include_screen">Inclure l\'écran</string>
|
||||
<string name="assist_signed_out">Connectez-vous d\'abord à une instance LLeMbas dans l\'application.</string>
|
||||
<string name="assist_open_app">Ouvrir l\'application</string>
|
||||
<string name="assist_open_in_app">Continuer dans l\'application</string>
|
||||
<string name="share_sending">Envoi à LLeMbas…</string>
|
||||
<string name="share_default_prompt">Jetez un œil à ceci.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->
|
||||
<resources>
|
||||
<string name="device_name">LLeMbas Androidra</string>
|
||||
<string name="share_label">Kérdés az LLeMbas-tól</string>
|
||||
<string name="tile_ask">Kérdés az LLeMbas-tól</string>
|
||||
<string name="signin_intro">Jelentkezzen be egy LLeMbas példányba. Ezt a telefont a böngészőben hagyja jóvá, ahogyan a CLI-t is tenné.</string>
|
||||
<string name="signin_address">A példány címe</string>
|
||||
<string name="signin_continue">Folytatás</string>
|
||||
<string name="signin_code_intro">Nyissa meg a példányt a böngészőben, jelentkezzen be, és hagyja jóvá ezt a kódot:</string>
|
||||
<string name="signin_open_browser">Megnyitás a böngészőben</string>
|
||||
<string name="signin_denied">A bejelentkezést elutasították.</string>
|
||||
<string name="signin_expired">A kód lejárt, mielőtt jóváhagyták volna. Próbálja újra.</string>
|
||||
<string name="signin_too_old">Ennek a példánynak még nincs alkalmazás-API-ja. LLeMbas 1.7.0 vagy újabb verzió szükséges hozzá.</string>
|
||||
<string name="signin_too_new">Ez a példány újabb alkalmazás-API-t használ, mint ez az alkalmazás. Frissítse az alkalmazást.</string>
|
||||
<string name="new_chat">Új csevegés</string>
|
||||
<string name="tab_chats">Csevegések</string>
|
||||
<string name="tab_agents">Ügynökök</string>
|
||||
<string name="empty_chats">Még nincs csevegés. Nem mindenki van elveszve, aki bolyong — kezdjen el egyet.</string>
|
||||
<string name="empty_agents">Nincs ügynök-csevegés. Indítson el egyet a webes felületen egy összekapcsolt eszközön.</string>
|
||||
<string name="empty_chat">Miről beszéljünk?</string>
|
||||
<string name="loading_line">Lembas sül…</string>
|
||||
<string name="archive">Archiválás</string>
|
||||
<string name="delete">Törlés</string>
|
||||
<string name="edit">Szerkesztés</string>
|
||||
<string name="regenerate">Újragenerálás</string>
|
||||
<string name="continue_reply">Folytatás</string>
|
||||
<string name="older">Korábbi üzenetek</string>
|
||||
<string name="queued">Küldésre vár</string>
|
||||
<string name="thinking">Gondolkodás</string>
|
||||
<string name="thought">Gondolkodott</string>
|
||||
<string name="output_cut">A kimenet itt lerövidítve jelenik meg. A teljes szöveg a weblapon található.</string>
|
||||
<string name="composer_hint">Üzenet</string>
|
||||
<string name="listening">Hallgatja…</string>
|
||||
<string name="send">Küldés</string>
|
||||
<string name="stop">Leállítás</string>
|
||||
<string name="attach">Fájl csatolása</string>
|
||||
<string name="dictate">Diktálás</string>
|
||||
<string name="remove">Eltávolítás</string>
|
||||
<string name="more">Továbbiak</string>
|
||||
<string name="back">Vissza</string>
|
||||
<string name="cancel">Mégse</string>
|
||||
<string name="close">Bezárás</string>
|
||||
<string name="effort_off">Erőfeszítés: kikapcsolva</string>
|
||||
<string name="mode_plan">Csomag</string>
|
||||
<string name="mode_edit">Szerkesztés</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="card_approval">Engedélyezzük ezt?</string>
|
||||
<string name="card_allow_once">Engedélyezés egyszer</string>
|
||||
<string name="card_allow_always">Ennek mindig engedélyezése</string>
|
||||
<string name="card_deny">Elutasítás</string>
|
||||
<string name="card_reason">Miért nem? (opcionális)</string>
|
||||
<string name="card_recommended">ajánlott</string>
|
||||
<string name="card_answer">Az Ön válasza</string>
|
||||
<string name="card_something_else">Valami más</string>
|
||||
<string name="card_send">Küldés</string>
|
||||
<string name="plan_approve">Terv jóváhagyása</string>
|
||||
<string name="plan_revise">Átdolgozás</string>
|
||||
<string name="plan_what_to_change">Mi változzon?</string>
|
||||
<string name="plan_carry_out">Terv végrehajtása</string>
|
||||
<string name="settings">Beállítások</string>
|
||||
<string name="settings_instances">Példányok</string>
|
||||
<string name="sign_out">Kijelentkezés</string>
|
||||
<string name="add_instance">Példány hozzáadása</string>
|
||||
<string name="settings_theme">Téma</string>
|
||||
<string name="theme_system">A rendszer szerint</string>
|
||||
<string name="theme_moria">Moria (sötét)</string>
|
||||
<string name="theme_shire">Shire (világos)</string>
|
||||
<string name="settings_notifications">Értesítések</string>
|
||||
<string name="push_explained">Az értesítések a UnifiedPush-on keresztül érkeznek, Google-szolgáltatások nélkül: az Ön által választott elosztó alkalmazás szállítja őket, titkosítva, csak ehhez a telefonhoz.</string>
|
||||
<string name="push_no_distributor">Hogy értesítést kapjon, amikor egy válasz elkészül, telepítsen egy UnifiedPush-elosztót, például az ntfy-t, majd jöjjön vissza ide. Ha nincs ilyen, az alkalmazás csak akkor mutatja az új válaszokat, amikor meg van nyitva.</string>
|
||||
<string name="push_enable">Értesítések bekapcsolása</string>
|
||||
<string name="push_on">Az értesítések be vannak kapcsolva ehhez a példányhoz.</string>
|
||||
<string name="push_failed">Nem választottak elosztót, így az értesítések továbbra is ki vannak kapcsolva.</string>
|
||||
<string name="channel_replies">Válaszok</string>
|
||||
<string name="channel_asks">Kérdések és jóváhagyások</string>
|
||||
<string name="channel_reports">Jelentések</string>
|
||||
<string name="settings_assistant">Asszisztens</string>
|
||||
<string name="assistant_explained">Tegye az LLeMbas-t a telefon digitális asszisztensévé: válassza ki az Alapértelmezett alkalmazások › Digitális asszisztens alkalmazás alatt. A bekapcsológomb lenyomva tartása, az asszisztens-gesztus vagy a lezárási képernyő parancsikonja ezután a képernyőn lévő tartalom felett nyitja meg.</string>
|
||||
<string name="assistant_open_settings">Asszisztens beállításainak megnyitása</string>
|
||||
<string name="assistant_samsung">Samsung telefonokon: Beállítások › Speciális funkciók › Oldalgomb › Nyomva tartás › Digitális asszisztens.</string>
|
||||
<string name="assistant_temporary">Az asszisztenses csevegések ideiglenesek</string>
|
||||
<string name="assistant_read_aloud">Olvassa fel a választ, ha hangos kérdés érkezett</string>
|
||||
<string name="settings_about">Névjegy</string>
|
||||
<string name="about_version">LLeMbas Androidra %1$s</string>
|
||||
<string name="update_check">Frissítés keresése</string>
|
||||
<string name="update_none">Ez a legújabb verzió.</string>
|
||||
<string name="update_unreachable">A frissítést nem sikerült letölteni.</string>
|
||||
<string name="update_allow_installs">Engedélyezze, hogy az LLeMbas frissítéseket telepítsen, majd ellenőrizze újra.</string>
|
||||
<string name="update_bad_file">A letöltés nem egyezett a verzióval, és el lett dobva.</string>
|
||||
<string name="update_installing">%1$s telepítése…</string>
|
||||
<string name="assist_hint">Kérdezzen bármit</string>
|
||||
<string name="assist_include_screen">Képernyő hozzáadása</string>
|
||||
<string name="assist_signed_out">Először jelentkezzen be egy LLeMbas példányba az alkalmazásban.</string>
|
||||
<string name="assist_open_app">Alkalmazás megnyitása</string>
|
||||
<string name="assist_open_in_app">Folytatás az alkalmazásban</string>
|
||||
<string name="share_sending">Küldés az LLeMbas-nak…</string>
|
||||
<string name="share_default_prompt">Nézze meg ezt.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->
|
||||
<resources>
|
||||
<string name="device_name">LLeMbas per Android</string>
|
||||
<string name="share_label">Chiedi a LLeMbas</string>
|
||||
<string name="tile_ask">Chiedi a LLeMbas</string>
|
||||
<string name="signin_intro">Accedi a un\'istanza LLeMbas. Approvi questo telefono nel browser, come faresti con la CLI.</string>
|
||||
<string name="signin_address">Indirizzo dell\'istanza</string>
|
||||
<string name="signin_continue">Continua</string>
|
||||
<string name="signin_code_intro">Apri l\'istanza nel browser, accedi e approva questo codice:</string>
|
||||
<string name="signin_open_browser">Apri nel browser</string>
|
||||
<string name="signin_denied">L\'accesso è stato rifiutato.</string>
|
||||
<string name="signin_expired">Il codice è scaduto prima di essere approvato. Riprova.</string>
|
||||
<string name="signin_too_old">Questa istanza non ha ancora un\'API per l\'app. Richiede LLeMbas 1.7.0 o una versione più recente.</string>
|
||||
<string name="signin_too_new">Questa istanza usa un\'API per l\'app più recente di questa app. Aggiorna l\'app.</string>
|
||||
<string name="new_chat">Nuova chat</string>
|
||||
<string name="tab_chats">Chat</string>
|
||||
<string name="tab_agents">Agenti</string>
|
||||
<string name="empty_chats">Ancora nessuna chat. Non tutti quelli che vagano sono perduti — iniziane una.</string>
|
||||
<string name="empty_agents">Nessuna chat agente. Avviane una dall\'interfaccia web su un dispositivo collegato.</string>
|
||||
<string name="empty_chat">Di cosa parliamo?</string>
|
||||
<string name="loading_line">I lembas stanno cuocendo…</string>
|
||||
<string name="archive">Archivia</string>
|
||||
<string name="delete">Elimina</string>
|
||||
<string name="edit">Modifica</string>
|
||||
<string name="regenerate">Rigenera</string>
|
||||
<string name="continue_reply">Continua</string>
|
||||
<string name="older">Messaggi precedenti</string>
|
||||
<string name="queued">In attesa di invio</string>
|
||||
<string name="thinking">Ragionamento</string>
|
||||
<string name="thought">Ha ragionato</string>
|
||||
<string name="output_cut">L\'output qui è abbreviato. Lo trovi per intero sulla pagina web.</string>
|
||||
<string name="composer_hint">Messaggio</string>
|
||||
<string name="listening">In ascolto…</string>
|
||||
<string name="send">Invia</string>
|
||||
<string name="stop">Ferma</string>
|
||||
<string name="attach">Allega un file</string>
|
||||
<string name="dictate">Detta</string>
|
||||
<string name="remove">Rimuovi</string>
|
||||
<string name="more">Altro</string>
|
||||
<string name="back">Indietro</string>
|
||||
<string name="cancel">Annulla</string>
|
||||
<string name="close">Chiudi</string>
|
||||
<string name="effort_off">Impegno: disattivato</string>
|
||||
<string name="mode_plan">Piano</string>
|
||||
<string name="mode_edit">Modifica</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="card_approval">Consentire questo?</string>
|
||||
<string name="card_allow_once">Consenti una volta</string>
|
||||
<string name="card_allow_always">Consenti sempre questo</string>
|
||||
<string name="card_deny">Nega</string>
|
||||
<string name="card_reason">Perché no? (facoltativo)</string>
|
||||
<string name="card_recommended">consigliato</string>
|
||||
<string name="card_answer">La tua risposta</string>
|
||||
<string name="card_something_else">Altro</string>
|
||||
<string name="card_send">Invia</string>
|
||||
<string name="plan_approve">Approva il piano</string>
|
||||
<string name="plan_revise">Rivedi</string>
|
||||
<string name="plan_what_to_change">Cosa dovrebbe cambiare?</string>
|
||||
<string name="plan_carry_out">Esegui il piano</string>
|
||||
<string name="settings">Impostazioni</string>
|
||||
<string name="settings_instances">Istanze</string>
|
||||
<string name="sign_out">Esci</string>
|
||||
<string name="add_instance">Aggiungi un\'istanza</string>
|
||||
<string name="settings_theme">Tema</string>
|
||||
<string name="theme_system">Come il sistema</string>
|
||||
<string name="theme_moria">Moria (scuro)</string>
|
||||
<string name="theme_shire">Shire (chiaro)</string>
|
||||
<string name="settings_notifications">Notifiche</string>
|
||||
<string name="push_explained">Le notifiche arrivano tramite UnifiedPush, senza servizi Google: l\'app di distribuzione che hai scelto le trasporta, cifrate solo per questo telefono.</string>
|
||||
<string name="push_no_distributor">Per essere avvisato quando una risposta è pronta, installa un distributore UnifiedPush come ntfy, poi torna qui. Senza uno, l\'app mostra le nuove risposte solo quando è aperta.</string>
|
||||
<string name="push_enable">Attiva le notifiche</string>
|
||||
<string name="push_on">Le notifiche sono attive per questa istanza.</string>
|
||||
<string name="push_failed">Non è stato scelto nessun distributore, quindi le notifiche sono ancora disattivate.</string>
|
||||
<string name="channel_replies">Risposte</string>
|
||||
<string name="channel_asks">Domande e approvazioni</string>
|
||||
<string name="channel_reports">Report</string>
|
||||
<string name="settings_assistant">Assistente</string>
|
||||
<string name="assistant_explained">Rendi LLeMbas l\'assistente digitale del telefono: selezionalo in App predefinite › App di assistenza digitale. Tenendo premuto il tasto di accensione, il gesto di assistenza o la scorciatoia della schermata di blocco lo apre quindi sopra qualsiasi cosa sia a schermo.</string>
|
||||
<string name="assistant_open_settings">Apri le impostazioni dell\'assistente</string>
|
||||
<string name="assistant_samsung">Sui telefoni Samsung: Impostazioni › Funzioni avanzate › Tasto laterale › Pressione prolungata › Assistente digitale.</string>
|
||||
<string name="assistant_temporary">Le chat dell\'assistente sono temporanee</string>
|
||||
<string name="assistant_read_aloud">Leggi la risposta ad alta voce quando la domanda è vocale</string>
|
||||
<string name="settings_about">Informazioni</string>
|
||||
<string name="about_version">LLeMbas per Android %1$s</string>
|
||||
<string name="update_check">Controlla aggiornamenti</string>
|
||||
<string name="update_none">Questa è la versione più recente.</string>
|
||||
<string name="update_unreachable">Non è stato possibile scaricare l\'aggiornamento.</string>
|
||||
<string name="update_allow_installs">Consenti a LLeMbas di installare gli aggiornamenti, poi controlla di nuovo.</string>
|
||||
<string name="update_bad_file">Il download non corrispondeva alla versione ed è stato scartato.</string>
|
||||
<string name="update_installing">Installazione di %1$s…</string>
|
||||
<string name="assist_hint">Chiedi qualsiasi cosa</string>
|
||||
<string name="assist_include_screen">Includi lo schermo</string>
|
||||
<string name="assist_signed_out">Accedi prima a un\'istanza LLeMbas nell\'app.</string>
|
||||
<string name="assist_open_app">Apri l\'app</string>
|
||||
<string name="assist_open_in_app">Continua nell\'app</string>
|
||||
<string name="share_sending">Invio a LLeMbas…</string>
|
||||
<string name="share_default_prompt">Dai un\'occhiata a questo.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->
|
||||
<resources>
|
||||
<string name="device_name">LLeMbas na Androida</string>
|
||||
<string name="share_label">Zapytaj LLeMbas</string>
|
||||
<string name="tile_ask">Zapytaj LLeMbas</string>
|
||||
<string name="signin_intro">Zaloguj się do instancji LLeMbas. Ten telefon zatwierdza się w przeglądarce, tak jak CLI.</string>
|
||||
<string name="signin_address">Adres instancji</string>
|
||||
<string name="signin_continue">Kontynuuj</string>
|
||||
<string name="signin_code_intro">Otwórz instancję w przeglądarce, zaloguj się i zatwierdź ten kod:</string>
|
||||
<string name="signin_open_browser">Otwórz w przeglądarce</string>
|
||||
<string name="signin_denied">Logowanie zostało odrzucone.</string>
|
||||
<string name="signin_expired">Kod wygasł, zanim został zatwierdzony. Spróbuj ponownie.</string>
|
||||
<string name="signin_too_old">Ta instancja nie ma jeszcze API aplikacji. Wymaga LLeMbas 1.7.0 lub nowszego.</string>
|
||||
<string name="signin_too_new">Ta instancja używa nowszego API aplikacji niż ta aplikacja. Zaktualizuj aplikację.</string>
|
||||
<string name="new_chat">Nowy czat</string>
|
||||
<string name="tab_chats">Czaty</string>
|
||||
<string name="tab_agents">Agenci</string>
|
||||
<string name="empty_chats">Nie ma jeszcze czatów. Nie każdy, kto błądzi, jest zgubiony — zacznij jeden.</string>
|
||||
<string name="empty_agents">Brak czatów agenta. Zacznij jeden z interfejsu webowego na połączonym urządzeniu.</string>
|
||||
<string name="empty_chat">O czym porozmawiamy?</string>
|
||||
<string name="loading_line">Lembasy się pieczą…</string>
|
||||
<string name="archive">Archiwizuj</string>
|
||||
<string name="delete">Usuń</string>
|
||||
<string name="edit">Edytuj</string>
|
||||
<string name="regenerate">Wygeneruj ponownie</string>
|
||||
<string name="continue_reply">Kontynuuj</string>
|
||||
<string name="older">Wcześniejsze wiadomości</string>
|
||||
<string name="queued">Czeka na wysłanie</string>
|
||||
<string name="thinking">Rozumowanie</string>
|
||||
<string name="thought">Rozumowanie</string>
|
||||
<string name="output_cut">Wynik jest tu skrócony. Cały znajduje się na stronie internetowej.</string>
|
||||
<string name="composer_hint">Wiadomość</string>
|
||||
<string name="listening">Słucham…</string>
|
||||
<string name="send">Wyślij</string>
|
||||
<string name="stop">Zatrzymać</string>
|
||||
<string name="attach">Załącz plik</string>
|
||||
<string name="dictate">Dyktuj</string>
|
||||
<string name="remove">Usuń</string>
|
||||
<string name="more">Więcej</string>
|
||||
<string name="back">Wstecz</string>
|
||||
<string name="cancel">Anuluj</string>
|
||||
<string name="close">Zamknij</string>
|
||||
<string name="effort_off">Wysiłek: wyłączony</string>
|
||||
<string name="mode_plan">Plan</string>
|
||||
<string name="mode_edit">Edytuj</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="card_approval">Zezwolić na to?</string>
|
||||
<string name="card_allow_once">Zezwól raz</string>
|
||||
<string name="card_allow_always">Zawsze na to zezwalaj</string>
|
||||
<string name="card_deny">Odrzuć</string>
|
||||
<string name="card_reason">Czemu nie? (opcjonalnie)</string>
|
||||
<string name="card_recommended">zalecane</string>
|
||||
<string name="card_answer">Twoja odpowiedź</string>
|
||||
<string name="card_something_else">Coś innego</string>
|
||||
<string name="card_send">Wyślij</string>
|
||||
<string name="plan_approve">Zatwierdź plan</string>
|
||||
<string name="plan_revise">Popraw</string>
|
||||
<string name="plan_what_to_change">Co powinno się zmienić?</string>
|
||||
<string name="plan_carry_out">Wykonaj plan</string>
|
||||
<string name="settings">Ustawienia</string>
|
||||
<string name="settings_instances">Instancje</string>
|
||||
<string name="sign_out">Wyloguj się</string>
|
||||
<string name="add_instance">Dodaj instancję</string>
|
||||
<string name="settings_theme">Motyw</string>
|
||||
<string name="theme_system">Jak system</string>
|
||||
<string name="theme_moria">Moria (ciemny)</string>
|
||||
<string name="theme_shire">Shire (jasny)</string>
|
||||
<string name="settings_notifications">Powiadomienia</string>
|
||||
<string name="push_explained">Powiadomienia przychodzą przez UnifiedPush, bez usług Google: niesie je wybrana aplikacja dystrybucyjna, zaszyfrowane tylko dla tego telefonu.</string>
|
||||
<string name="push_no_distributor">Aby dostawać informacje, kiedy odpowiedź jest gotowa, zainstaluj dystrybutora UnifiedPush, na przykład ntfy, a potem wróć tutaj. Bez niego aplikacja pokazuje nowe odpowiedzi tylko wtedy, gdy jest otwarta.</string>
|
||||
<string name="push_enable">Włącz powiadomienia</string>
|
||||
<string name="push_on">Powiadomienia są włączone dla tej instancji.</string>
|
||||
<string name="push_failed">Nie wybrano dystrybutora, więc powiadomienia są wciąż wyłączone.</string>
|
||||
<string name="channel_replies">Odpowiedzi</string>
|
||||
<string name="channel_asks">Pytania i zatwierdzenia</string>
|
||||
<string name="channel_reports">Raporty</string>
|
||||
<string name="settings_assistant">Asystent</string>
|
||||
<string name="assistant_explained">Ustaw LLeMbas jako cyfrowego asystenta telefonu: wybierz go w Domyślne aplikacje › Aplikacja asystenta cyfrowego. Przytrzymanie przycisku zasilania, gest asystenta lub skrót z ekranu blokady otwiera go wtedy nad tym, co jest na ekranie.</string>
|
||||
<string name="assistant_open_settings">Otwórz ustawienia asystenta</string>
|
||||
<string name="assistant_samsung">W telefonach Samsung: Ustawienia › Funkcje zaawansowane › Przycisk boczny › Naciśnięcie i przytrzymanie › Asystent cyfrowy.</string>
|
||||
<string name="assistant_temporary">Czaty asystenta są tymczasowe</string>
|
||||
<string name="assistant_read_aloud">Odczytaj odpowiedź na głos, gdy pytanie było głosowe</string>
|
||||
<string name="settings_about">Informacje</string>
|
||||
<string name="about_version">LLeMbas na Androida %1$s</string>
|
||||
<string name="update_check">Sprawdź aktualizację</string>
|
||||
<string name="update_none">To jest najnowsza wersja.</string>
|
||||
<string name="update_unreachable">Nie udało się pobrać aktualizacji.</string>
|
||||
<string name="update_allow_installs">Zezwól LLeMbas na instalowanie aktualizacji, a potem sprawdź ponownie.</string>
|
||||
<string name="update_bad_file">Pobrany plik nie zgadzał się z wersją i został odrzucony.</string>
|
||||
<string name="update_installing">Instalowanie %1$s…</string>
|
||||
<string name="assist_hint">Zapytaj o cokolwiek</string>
|
||||
<string name="assist_include_screen">Dołącz ekran</string>
|
||||
<string name="assist_signed_out">Najpierw zaloguj się do instancji LLeMbas w aplikacji.</string>
|
||||
<string name="assist_open_app">Otwórz aplikację</string>
|
||||
<string name="assist_open_in_app">Kontynuuj w aplikacji</string>
|
||||
<string name="share_sending">Wysyłanie do LLeMbas…</string>
|
||||
<string name="share_default_prompt">Zobacz to.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->
|
||||
<resources>
|
||||
<string name="device_name">LLeMbas pre Android</string>
|
||||
<string name="share_label">Spýtať sa LLeMbas</string>
|
||||
<string name="tile_ask">Spýtať sa LLeMbas</string>
|
||||
<string name="signin_intro">Prihláste sa do inštancie LLeMbas. Tento telefón schválite v prehliadači, tak ako by ste schválili CLI.</string>
|
||||
<string name="signin_address">Adresa inštancie</string>
|
||||
<string name="signin_continue">Pokračovať</string>
|
||||
<string name="signin_code_intro">Otvorte inštanciu v prehliadači, prihláste sa a schváľte tento kód:</string>
|
||||
<string name="signin_open_browser">Otvoriť v prehliadači</string>
|
||||
<string name="signin_denied">Prihlásenie bolo odmietnuté.</string>
|
||||
<string name="signin_expired">Kód vypršal skôr, než bol schválený. Skúste to znova.</string>
|
||||
<string name="signin_too_old">Táto inštancia ešte nemá API pre aplikácie. Potrebuje LLeMbas 1.7.0 alebo novší.</string>
|
||||
<string name="signin_too_new">Táto inštancia používa novšie API pre aplikácie než táto aplikácia. Aktualizujte aplikáciu.</string>
|
||||
<string name="new_chat">Nová konverzácia</string>
|
||||
<string name="tab_chats">Konverzácie</string>
|
||||
<string name="tab_agents">Agenti</string>
|
||||
<string name="empty_chats">Zatiaľ žiadne konverzácie. Nie všetci, čo blúdia, sú stratení — začnite jednu.</string>
|
||||
<string name="empty_agents">Žiadne konverzácie s agentom. Spustite jednu z webového rozhrania na prepojenom zariadení.</string>
|
||||
<string name="empty_chat">O čom sa pozhovárame?</string>
|
||||
<string name="loading_line">Pečú sa lembasy…</string>
|
||||
<string name="archive">Archivovať</string>
|
||||
<string name="delete">Zmazať</string>
|
||||
<string name="edit">Upraviť</string>
|
||||
<string name="regenerate">Vygenerovať znova</string>
|
||||
<string name="continue_reply">Pokračovať</string>
|
||||
<string name="older">Staršie správy</string>
|
||||
<string name="queued">Čaká na odoslanie</string>
|
||||
<string name="thinking">Premýšľa</string>
|
||||
<string name="thought">Premýšľal</string>
|
||||
<string name="output_cut">Výstup je tu skrátený. Celý nájdete na webovej stránke.</string>
|
||||
<string name="composer_hint">Správa</string>
|
||||
<string name="listening">Počúvam…</string>
|
||||
<string name="send">Poslať</string>
|
||||
<string name="stop">Zastaviť</string>
|
||||
<string name="attach">Priložiť súbor</string>
|
||||
<string name="dictate">Diktovať</string>
|
||||
<string name="remove">Odstrániť</string>
|
||||
<string name="more">Viac</string>
|
||||
<string name="back">Späť</string>
|
||||
<string name="cancel">Zrušiť</string>
|
||||
<string name="close">Zavrieť</string>
|
||||
<string name="effort_off">Úsilie: vypnuté</string>
|
||||
<string name="mode_plan">Plán</string>
|
||||
<string name="mode_edit">Upraviť</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="card_approval">Povoliť to?</string>
|
||||
<string name="card_allow_once">Povoliť raz</string>
|
||||
<string name="card_allow_always">Toto vždy povoliť</string>
|
||||
<string name="card_deny">Odmietnuť</string>
|
||||
<string name="card_reason">Prečo nie? (nepovinné)</string>
|
||||
<string name="card_recommended">odporúčané</string>
|
||||
<string name="card_answer">Vaša odpoveď</string>
|
||||
<string name="card_something_else">Niečo iné</string>
|
||||
<string name="card_send">Poslať</string>
|
||||
<string name="plan_approve">Schváliť plán</string>
|
||||
<string name="plan_revise">Prepracovať</string>
|
||||
<string name="plan_what_to_change">Čo by sa malo zmeniť?</string>
|
||||
<string name="plan_carry_out">Vykonať plán</string>
|
||||
<string name="settings">Nastavenia</string>
|
||||
<string name="settings_instances">Inštancie</string>
|
||||
<string name="sign_out">Odhlásiť sa</string>
|
||||
<string name="add_instance">Pridať inštanciu</string>
|
||||
<string name="settings_theme">Vzhľad</string>
|
||||
<string name="theme_system">Podľa systému</string>
|
||||
<string name="theme_moria">Moria (tmavá)</string>
|
||||
<string name="theme_shire">Shire (svetlá)</string>
|
||||
<string name="settings_notifications">Upozornenia</string>
|
||||
<string name="push_explained">Upozornenia chodia cez UnifiedPush, bez služieb Google: doručuje ich distribučná aplikácia, ktorú ste zvolili, zašifrované len pre tento telefón.</string>
|
||||
<string name="push_no_distributor">Aby ste sa dozvedeli, že je odpoveď hotová, nainštalujte distributora UnifiedPush, napríklad ntfy, a potom sa vráťte sem. Bez neho aplikácia nové odpovede ukáže, len keď je otvorená.</string>
|
||||
<string name="push_enable">Zapnúť upozornenia</string>
|
||||
<string name="push_on">Upozornenia sú pre túto inštanciu zapnuté.</string>
|
||||
<string name="push_failed">Nebol zvolený žiadny distributor, takže upozornenia sú stále vypnuté.</string>
|
||||
<string name="channel_replies">Odpovede</string>
|
||||
<string name="channel_asks">Otázky a schválenia</string>
|
||||
<string name="channel_reports">Správy</string>
|
||||
<string name="settings_assistant">Asistent</string>
|
||||
<string name="assistant_explained">Nastavte LLeMbas ako digitálneho asistenta telefónu: zvoľte ho v Predvolené aplikácie › Digitálny asistent. Podržanie tlačidla napájania, gesto asistenta alebo skratka na uzamknutej obrazovke ho potom otvorí nad tým, čo je práve na obrazovke.</string>
|
||||
<string name="assistant_open_settings">Otvoriť nastavenia asistenta</string>
|
||||
<string name="assistant_samsung">Na telefónoch Samsung: Nastavenia › Rozšírené funkcie › Tlačidlo na boku › Stlačenie a podržanie › Digitálny asistent.</string>
|
||||
<string name="assistant_temporary">Konverzácie s asistentom sú dočasné</string>
|
||||
<string name="assistant_read_aloud">Prečítať odpoveď nahlas, keď sa spýtate hlasom</string>
|
||||
<string name="settings_about">O aplikácii</string>
|
||||
<string name="about_version">LLeMbas pre Android %1$s</string>
|
||||
<string name="update_check">Skontrolovať aktualizáciu</string>
|
||||
<string name="update_none">Toto je najnovšia verzia.</string>
|
||||
<string name="update_unreachable">Aktualizáciu sa nepodarilo stiahnuť.</string>
|
||||
<string name="update_allow_installs">Povoľte aplikácii LLeMbas instalovať aktualizácie a potom to skontrolujte znova.</string>
|
||||
<string name="update_bad_file">Stiahnutý súbor nezodpovedal verzii a bol zahodený.</string>
|
||||
<string name="update_installing">Inštaluje sa %1$s…</string>
|
||||
<string name="assist_hint">Spýtajte sa na čokoľvek</string>
|
||||
<string name="assist_include_screen">Zahrnúť obrazovku</string>
|
||||
<string name="assist_signed_out">Najprv sa v aplikácii prihláste do inštancie LLeMbas.</string>
|
||||
<string name="assist_open_app">Otvoriť aplikáciu</string>
|
||||
<string name="assist_open_in_app">Pokračovať v aplikácii</string>
|
||||
<string name="share_sending">Odosiela sa do LLeMbas…</string>
|
||||
<string name="share_default_prompt">Pozrite sa na toto.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- Moria's --bg, the colour the launcher tile sits on. -->
|
||||
<color name="launcher_background">#0B0D10</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,100 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->
|
||||
<resources>
|
||||
<string name="app_name" translatable="false">LLeMbas</string>
|
||||
<string name="device_name">LLeMbas for Android</string>
|
||||
<string name="share_label">Ask LLeMbas</string>
|
||||
<string name="tile_ask">Ask LLeMbas</string>
|
||||
<string name="signin_intro">Sign in to a LLeMbas instance. You approve this phone in the browser, as you would the CLI.</string>
|
||||
<string name="signin_address">Instance address</string>
|
||||
<string name="signin_continue">Continue</string>
|
||||
<string name="signin_code_intro">Open the instance in the browser, sign in, and approve this code:</string>
|
||||
<string name="signin_open_browser">Open in the browser</string>
|
||||
<string name="signin_denied">The sign-in was refused.</string>
|
||||
<string name="signin_expired">The code expired before it was approved. Try again.</string>
|
||||
<string name="signin_too_old">This instance has no app API yet. It needs LLeMbas 1.7.0 or newer.</string>
|
||||
<string name="signin_too_new">This instance speaks a newer app API than this app. Update the app.</string>
|
||||
<string name="new_chat">New chat</string>
|
||||
<string name="tab_chats">Chats</string>
|
||||
<string name="tab_agents">Agents</string>
|
||||
<string name="empty_chats">No chats yet. Not all those who wander are lost — start one.</string>
|
||||
<string name="empty_agents">No agent chats. Start one from the web interface on a linked device.</string>
|
||||
<string name="empty_chat">What shall we talk about?</string>
|
||||
<string name="loading_line">Baking lembas…</string>
|
||||
<string name="archive">Archive</string>
|
||||
<string name="delete">Delete</string>
|
||||
<string name="edit">Edit</string>
|
||||
<string name="regenerate">Regenerate</string>
|
||||
<string name="continue_reply">Continue</string>
|
||||
<string name="older">Earlier messages</string>
|
||||
<string name="queued">Waiting to be sent</string>
|
||||
<string name="thinking">Thinking</string>
|
||||
<string name="thought">Thought</string>
|
||||
<string name="output_cut">Output shortened here. The whole of it is on the web page.</string>
|
||||
<string name="composer_hint">Message</string>
|
||||
<string name="listening">Listening…</string>
|
||||
<string name="send">Send</string>
|
||||
<string name="stop">Stop</string>
|
||||
<string name="attach">Attach a file</string>
|
||||
<string name="dictate">Dictate</string>
|
||||
<string name="remove">Remove</string>
|
||||
<string name="more">More</string>
|
||||
<string name="back">Back</string>
|
||||
<string name="cancel">Cancel</string>
|
||||
<string name="close">Close</string>
|
||||
<string name="effort_off">Effort: off</string>
|
||||
<string name="mode_plan">Plan</string>
|
||||
<string name="mode_edit">Edit</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="card_approval">Allow this?</string>
|
||||
<string name="card_allow_once">Allow once</string>
|
||||
<string name="card_allow_always">Always allow this</string>
|
||||
<string name="card_deny">Deny</string>
|
||||
<string name="card_reason">Why not? (optional)</string>
|
||||
<string name="card_recommended">recommended</string>
|
||||
<string name="card_answer">Your answer</string>
|
||||
<string name="card_something_else">Something else</string>
|
||||
<string name="card_send">Send</string>
|
||||
<string name="plan_approve">Approve the plan</string>
|
||||
<string name="plan_revise">Revise</string>
|
||||
<string name="plan_what_to_change">What should change?</string>
|
||||
<string name="plan_carry_out">Carry out the plan</string>
|
||||
<string name="settings">Settings</string>
|
||||
<string name="settings_instances">Instances</string>
|
||||
<string name="sign_out">Sign out</string>
|
||||
<string name="add_instance">Add an instance</string>
|
||||
<string name="settings_theme">Theme</string>
|
||||
<string name="theme_system">As the system</string>
|
||||
<string name="theme_moria">Moria (dark)</string>
|
||||
<string name="theme_shire">Shire (light)</string>
|
||||
<string name="settings_notifications">Notifications</string>
|
||||
<string name="push_explained">Notifications come through UnifiedPush, with no Google services: the distributor app you chose carries them, encrypted for this phone only.</string>
|
||||
<string name="push_no_distributor">To be told when a reply is ready, install a UnifiedPush distributor such as ntfy, then come back here. Without one, the app shows new replies when it is open.</string>
|
||||
<string name="push_enable">Turn notifications on</string>
|
||||
<string name="push_on">Notifications are on for this instance.</string>
|
||||
<string name="push_failed">No distributor was chosen, so notifications are still off.</string>
|
||||
<string name="channel_replies">Replies</string>
|
||||
<string name="channel_asks">Questions and approvals</string>
|
||||
<string name="channel_reports">Reports</string>
|
||||
<string name="settings_assistant">Assistant</string>
|
||||
<string name="assistant_explained">Make LLeMbas the phone\'s digital assistant: choose it under Default apps › Digital assistant app. Then holding the power button, the assist gesture or the lock screen\'s shortcut opens it over whatever is on screen.</string>
|
||||
<string name="assistant_open_settings">Open the assistant settings</string>
|
||||
<string name="assistant_samsung">On Samsung phones: Settings › Advanced features › Side button › Press and hold › Digital assistant.</string>
|
||||
<string name="assistant_temporary">Assistant chats are temporary</string>
|
||||
<string name="assistant_read_aloud">Read the answer aloud when asked by voice</string>
|
||||
<string name="settings_about">About</string>
|
||||
<string name="about_version">LLeMbas for Android %1$s</string>
|
||||
<string name="update_check">Check for an update</string>
|
||||
<string name="update_none">This is the newest version.</string>
|
||||
<string name="update_unreachable">The update could not be fetched.</string>
|
||||
<string name="update_allow_installs">Allow LLeMbas to install updates, then check again.</string>
|
||||
<string name="update_bad_file">The download did not match the release and was discarded.</string>
|
||||
<string name="update_installing">Installing %1$s…</string>
|
||||
<string name="assist_hint">Ask anything</string>
|
||||
<string name="assist_include_screen">Include screen</string>
|
||||
<string name="assist_signed_out">Sign in to a LLeMbas instance in the app first.</string>
|
||||
<string name="assist_open_app">Open the app</string>
|
||||
<string name="assist_open_in_app">Continue in the app</string>
|
||||
<string name="share_sending">Sending to LLeMbas…</string>
|
||||
<string name="share_default_prompt">Have a look at this.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- The window behind Compose. Compose draws everything; this only sets the first frame. -->
|
||||
<style name="Theme.Lembas" parent="android:Theme.Material.NoActionBar">
|
||||
<item name="android:windowBackground">@color/launcher_background</item>
|
||||
</style>
|
||||
|
||||
<!-- The assistant's sheet: see-through, so the app it opened over stays visible. -->
|
||||
<style name="Theme.Lembas.Sheet" parent="android:Theme.Material.NoActionBar">
|
||||
<item name="android:windowIsTranslucent">true</item>
|
||||
<item name="android:windowBackground">@android:color/transparent</item>
|
||||
<item name="android:windowAnimationStyle">@android:style/Animation.InputMethod</item>
|
||||
<item name="android:backgroundDimEnabled">false</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Android rejects a voice-interaction service without both a session and a recognition
|
||||
service. No hotwordDetectionService: that needs a privileged permission third-party apps
|
||||
cannot hold. -->
|
||||
<voice-interaction-service xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:sessionService="eu.llembas.android.assist.LembasAssistSessionService"
|
||||
android:recognitionService="eu.llembas.android.assist.LembasRecognitionService"
|
||||
android:settingsActivity="eu.llembas.android.MainActivity"
|
||||
android:supportsAssist="true"
|
||||
android:supportsLaunchVoiceAssistFromKeyguard="true"
|
||||
android:supportsLocalInteraction="false" />
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Nothing is backed up or moved to another phone: the token is sealed with a key that never
|
||||
leaves this one, so a copy would be ciphertext nobody can open. Sign in again instead. -->
|
||||
<data-extraction-rules>
|
||||
<cloud-backup>
|
||||
<exclude domain="root" />
|
||||
<exclude domain="file" />
|
||||
<exclude domain="database" />
|
||||
<exclude domain="sharedpref" />
|
||||
</cloud-backup>
|
||||
<device-transfer>
|
||||
<exclude domain="root" />
|
||||
<exclude domain="file" />
|
||||
<exclude domain="database" />
|
||||
<exclude domain="sharedpref" />
|
||||
</device-transfer>
|
||||
</data-extraction-rules>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- A self-hosted instance often sits behind its owner's own certificate authority. Trusting
|
||||
the CAs the person installed on this phone (Settings › Security › Install a certificate)
|
||||
is what lets the app reach it -- the same step the browser needs. No plain HTTP: a token
|
||||
goes with every request. -->
|
||||
<network-security-config>
|
||||
<base-config cleartextTrafficPermitted="false">
|
||||
<trust-anchors>
|
||||
<certificates src="system" />
|
||||
<certificates src="user" />
|
||||
</trust-anchors>
|
||||
</base-config>
|
||||
</network-security-config>
|
||||
@@ -0,0 +1,3 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<recognition-service xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:settingsActivity="eu.llembas.android.MainActivity" />
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<shortcut
|
||||
android:shortcutId="ask"
|
||||
android:enabled="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:shortcutShortLabel="@string/tile_ask">
|
||||
<intent
|
||||
android:action="android.intent.action.ASSIST"
|
||||
android:targetPackage="eu.llembas.android"
|
||||
android:targetClass="eu.llembas.android.assist.AssistActivity" />
|
||||
</shortcut>
|
||||
</shortcuts>
|
||||
@@ -0,0 +1,64 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.normaliseBase
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
class ClientTest {
|
||||
private lateinit var server: MockWebServer
|
||||
|
||||
@Before
|
||||
fun up() {
|
||||
server = MockWebServer().apply { start() }
|
||||
}
|
||||
|
||||
@After
|
||||
fun down() = server.shutdown()
|
||||
|
||||
private fun client() = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test")
|
||||
|
||||
@Test
|
||||
fun anAddressBecomesABase() {
|
||||
assertEquals("https://llm.example.org", normaliseBase(" llm.example.org/ "))
|
||||
assertEquals("http://10.1.2.3:8080", normaliseBase("http://10.1.2.3:8080"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun everyCallCarriesTheToken() = runTest {
|
||||
server.enqueue(MockResponse().setBody("""{"api":1,"account":{"name":"Frodo","email":"f@shire.test"}}"""))
|
||||
assertEquals("Frodo", client().me().account.name)
|
||||
val request = server.takeRequest()
|
||||
assertEquals("/api/v2/me", request.path)
|
||||
assertEquals("Bearer lmb_test", request.getHeader("Authorization"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRefusalIsTheServersOwnSentence() = runTest {
|
||||
server.enqueue(MockResponse().setResponseCode(409).setBody("""{"detail":"That question is no longer waiting for an answer."}"""))
|
||||
try {
|
||||
client().answer("c", "card", CardAnswer(verdict = "allow"))
|
||||
fail("a 409 must throw")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals(409, e.status)
|
||||
assertEquals("That question is no longer waiting for an answer.", e.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aCardAnswerIsThePagesFormInJson() = runTest {
|
||||
server.enqueue(MockResponse().setBody("""{"answered":true}"""))
|
||||
client().answer("c1", "card1", CardAnswer(choices = mapOf("q0" to listOf("Tea"))))
|
||||
val body = server.takeRequest().body.readUtf8()
|
||||
assertTrue(body, body.contains(""""choices":{"q0":["Tea"]}"""))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.AskFrame
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.DoneFrame
|
||||
import eu.llembas.android.api.JobsFrame
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Metrics
|
||||
import eu.llembas.android.api.Plan
|
||||
import eu.llembas.android.api.StatusFrame
|
||||
import eu.llembas.android.api.SteeredFrame
|
||||
import eu.llembas.android.api.StepsFrame
|
||||
import eu.llembas.android.api.Tail
|
||||
import kotlinx.serialization.KSerializer
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* The server's contract, as pinned in `contract/` by `scripts/fetch-contract.py`: every shape
|
||||
* the server's serialisers wrote must parse into this app's models, and say what it said.
|
||||
*/
|
||||
class ContractTest {
|
||||
private fun text(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) { "contract/$name.json is missing" }.readText()
|
||||
|
||||
private fun <T> read(name: String, serializer: KSerializer<T>): T = LembasJson.decodeFromString(serializer, text(name))
|
||||
|
||||
@Test
|
||||
fun theVersionIsOneThisAppReads() {
|
||||
val version = LembasJson.parseToJsonElement(text("version")).toString()
|
||||
assertEquals("""{"app_api":1}""", version)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aChatAndAnAgentChat() {
|
||||
val chat = read("chat", Chat.serializer())
|
||||
assertEquals("Waybread", chat.title)
|
||||
assertEquals("low", chat.effort)
|
||||
assertTrue(chat.unread)
|
||||
val agent = read("chat_agent", Chat.serializer())
|
||||
assertTrue(agent.isAgent)
|
||||
assertEquals("edit", agent.mode)
|
||||
assertEquals("/home/dev/project", agent.device?.directory)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theMessages() {
|
||||
val user = read("message_user", Message.serializer())
|
||||
assertTrue(user.isUser)
|
||||
assertEquals("How is lembas made?", user.text)
|
||||
|
||||
val reply = read("message_assistant", Message.serializer())
|
||||
assertEquals(listOf("thinking", "text", "tools", "steer", "text"), reply.steps.map { it.kind })
|
||||
assertTrue(reply.steps[1].markdown!!.startsWith("Here is how it is made"))
|
||||
val call = reply.steps[2].calls.single()
|
||||
assertEquals("shell", call.block.kind)
|
||||
assertEquals("bake --slow", call.block.title)
|
||||
assertEquals(listOf("exit 0"), call.block.chips)
|
||||
assertEquals("and add honey", reply.steps[3].messages.single().text)
|
||||
assertEquals(40, reply.metrics!!.completionTokens)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun everyFrameParses() {
|
||||
assertTrue(read("event_steps", StepsFrame.serializer()).steps.isNotEmpty())
|
||||
assertNotNull(read("event_tail", Tail.serializer()).label)
|
||||
assertEquals(listOf("msg9"), read("event_steered", SteeredFrame.serializer()).ids)
|
||||
assertEquals("Bake lembas", read("event_plan", Plan.serializer()).title)
|
||||
assertTrue(read("event_status", StatusFrame.serializer()).text.isNotEmpty())
|
||||
val cards = read("event_ask", AskFrame.serializer()).cards
|
||||
assertEquals(listOf("question", "approval", "plan"), cards.map { it.kind })
|
||||
assertEquals(listOf("Honey", "Plain"), cards[0].items[0].options.map { it.label })
|
||||
assertTrue(cards[1].items[0].editable)
|
||||
assertNotNull(cards[2].items[0].plan)
|
||||
assertTrue(read("event_ask_empty", AskFrame.serializer()).cards.isEmpty())
|
||||
assertEquals("explore", read("event_jobs", JobsFrame.serializer()).jobs.single().agent)
|
||||
assertEquals(2, read("event_metrics", Metrics.serializer()).percent)
|
||||
assertEquals("Waybread", read("event_done", DoneFrame.serializer()).chat.title)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aWholeStreamBuildsAReply() {
|
||||
var live = LiveReply("msg2")
|
||||
for (event in listOf("steps", "tail", "steered", "plan", "status", "ask", "jobs", "metrics", "done", "close")) {
|
||||
live = live.apply(event, text("event_$event"))
|
||||
}
|
||||
assertTrue(live.closed)
|
||||
assertNotNull(live.finished)
|
||||
assertEquals("Waybread", live.title)
|
||||
assertNull(live.next)
|
||||
// A finished reply asks nothing: `done` clears the cards.
|
||||
assertTrue(live.cards.isEmpty())
|
||||
assertEquals(setOf("msg9"), live.steered)
|
||||
assertEquals("Bake lembas", live.plan?.title)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class LiveReplyTest {
|
||||
@Test
|
||||
fun aFrameReplacesItsBlockNeverAppends() {
|
||||
val once = LiveReply("m").apply("tail", """{"thinking":"","text":"Lem","label":""}""")
|
||||
val twice = once.apply("tail", """{"thinking":"","text":"Lembas","label":""}""")
|
||||
assertEquals("Lembas", twice.tail.text)
|
||||
assertEquals(listOf("text"), twice.shown.map { it.kind })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theOpenTailFollowsTheClosedSteps() {
|
||||
val live = LiveReply("m")
|
||||
.apply("steps", """{"steps":[{"index":0,"kind":"text","markdown":"One."}],"tail":{"thinking":"hm","text":"Two","label":"3s"}}""")
|
||||
assertEquals(listOf("text", "thinking", "text"), live.shown.map { it.kind })
|
||||
assertEquals(listOf(0, 1, 1), live.shown.map { it.index })
|
||||
assertTrue(live.shown.drop(1).all { it.open })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anEmptyAskFrameClearsTheCard() {
|
||||
val asked = LiveReply("m").apply("ask", """{"cards":[{"id":"c","kind":"question","items":[{"key":"q0","kind":"question"}]}]}""")
|
||||
assertEquals(1, asked.cards.size)
|
||||
assertTrue(asked.apply("ask", """{"cards":[]}""").cards.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anUnknownOrBrokenFrameChangesNothing() {
|
||||
val live = LiveReply("m").apply("status", """{"text":"Working"}""")
|
||||
assertEquals(live, live.apply("something-newer", "{}"))
|
||||
assertEquals(live, live.apply("status", "not json"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aDrainedQueueNamesTheNextReply() {
|
||||
val done = LiveReply("m").apply(
|
||||
"done",
|
||||
"""{"message":{"id":"m","role":"assistant"},"chat":{"id":"c","title":"T"},"next":"m2"}""",
|
||||
)
|
||||
assertEquals("m2", done.next)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.assist.AssistController
|
||||
import eu.llembas.android.assist.Recorder
|
||||
import eu.llembas.android.update.Updater
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SmallThingsTest {
|
||||
@Test
|
||||
fun versionsCompareAsNumbers() {
|
||||
assertTrue(Updater.newer("0.10.0", "0.9.9"))
|
||||
assertTrue(Updater.newer("1.0.0", "0.99.0"))
|
||||
assertFalse(Updater.newer("0.1.0", "0.1.0"))
|
||||
assertFalse(Updater.newer("0.1.0", "0.2.0"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aVoiceReadsNoMarkup() {
|
||||
val said = AssistController.plain("**Bake** it.\n\n```sh\nbake\n```\nSee [the recipe](https://example.org).")
|
||||
assertEquals("Bake it. See the recipe.", said)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRecordingIsAValidWavFile() {
|
||||
val wav = Recorder.wav(ByteArray(3200))
|
||||
assertEquals(44 + 3200, wav.size)
|
||||
assertEquals("RIFF", String(wav, 0, 4))
|
||||
assertEquals("WAVE", String(wav, 8, 4))
|
||||
assertEquals("data", String(wav, 36, 4))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.application) apply false
|
||||
alias(libs.plugins.kotlin.android) apply false
|
||||
alias(libs.plugins.kotlin.compose) apply false
|
||||
alias(libs.plugins.kotlin.serialization) apply false
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"id": "chat1",
|
||||
"kind": "chat",
|
||||
"title": "Waybread",
|
||||
"model": "qwen",
|
||||
"folder_id": null,
|
||||
"pinned": false,
|
||||
"archived": false,
|
||||
"temporary": false,
|
||||
"unread": true,
|
||||
"running": false,
|
||||
"mode": "",
|
||||
"effort": "low",
|
||||
"device": null,
|
||||
"parent_chat_id": null,
|
||||
"created_at": "2026-01-02T03:04:05+00:00",
|
||||
"updated_at": "2026-01-02T03:04:05+00:00"
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"id": "chat2",
|
||||
"kind": "agent",
|
||||
"title": "Waybread",
|
||||
"model": "qwen",
|
||||
"folder_id": null,
|
||||
"pinned": false,
|
||||
"archived": false,
|
||||
"temporary": false,
|
||||
"unread": true,
|
||||
"running": true,
|
||||
"mode": "edit",
|
||||
"effort": "low",
|
||||
"device": {
|
||||
"token_id": "token1",
|
||||
"directory": "/home/dev/project"
|
||||
},
|
||||
"parent_chat_id": null,
|
||||
"created_at": "2026-01-02T03:04:05+00:00",
|
||||
"updated_at": "2026-01-02T03:04:05+00:00"
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
{
|
||||
"cards": [
|
||||
{
|
||||
"id": "card1",
|
||||
"kind": "question",
|
||||
"why": "",
|
||||
"dismissable": false,
|
||||
"expires_in": null,
|
||||
"items": [
|
||||
{
|
||||
"index": 0,
|
||||
"key": "q0",
|
||||
"kind": "question",
|
||||
"tool": "ask_user",
|
||||
"title": "Honey or not?",
|
||||
"header": "Taste",
|
||||
"detail": "",
|
||||
"reason": "",
|
||||
"purpose": "",
|
||||
"options": [
|
||||
{
|
||||
"label": "Honey",
|
||||
"description": "",
|
||||
"recommended": true
|
||||
},
|
||||
{
|
||||
"label": "Plain",
|
||||
"description": "As the elves have it",
|
||||
"recommended": false
|
||||
}
|
||||
],
|
||||
"multiple": false,
|
||||
"free_text": true,
|
||||
"editable": false,
|
||||
"plan": null,
|
||||
"mode_choice": true,
|
||||
"job": ""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "card2",
|
||||
"kind": "approval",
|
||||
"why": "explore (job1) asks",
|
||||
"dismissable": false,
|
||||
"expires_in": null,
|
||||
"items": [
|
||||
{
|
||||
"index": 0,
|
||||
"key": "a0",
|
||||
"kind": "approval",
|
||||
"tool": "bash",
|
||||
"title": "rm -rf build",
|
||||
"header": "",
|
||||
"detail": "Removes the build directory.",
|
||||
"reason": "",
|
||||
"purpose": "Start clean",
|
||||
"options": [],
|
||||
"multiple": false,
|
||||
"free_text": true,
|
||||
"editable": true,
|
||||
"plan": null,
|
||||
"mode_choice": true,
|
||||
"job": ""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "card3",
|
||||
"kind": "plan",
|
||||
"why": "",
|
||||
"dismissable": true,
|
||||
"expires_in": null,
|
||||
"items": [
|
||||
{
|
||||
"index": 0,
|
||||
"key": "p0",
|
||||
"kind": "plan",
|
||||
"tool": "plan_submit",
|
||||
"title": "Bake lembas",
|
||||
"header": "",
|
||||
"detail": "",
|
||||
"reason": "",
|
||||
"purpose": "",
|
||||
"options": [],
|
||||
"multiple": false,
|
||||
"free_text": true,
|
||||
"editable": false,
|
||||
"plan": {
|
||||
"version": 2,
|
||||
"title": "Bake lembas",
|
||||
"summary": "",
|
||||
"findings": [],
|
||||
"objectives": [],
|
||||
"phases": [
|
||||
{
|
||||
"id": "p1",
|
||||
"title": "Plan",
|
||||
"status": "pending",
|
||||
"tasks": [
|
||||
{
|
||||
"id": "t1",
|
||||
"text": "Gather mallorn leaves",
|
||||
"status": "todo",
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"id": "t2",
|
||||
"text": "Bake slowly",
|
||||
"status": "todo",
|
||||
"note": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"steps": [
|
||||
"Gather mallorn leaves",
|
||||
"Bake slowly"
|
||||
]
|
||||
},
|
||||
"mode_choice": true,
|
||||
"job": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"cards": []
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"tabs": [
|
||||
{
|
||||
"path": "recipe.md",
|
||||
"title": "recipe.md"
|
||||
}
|
||||
],
|
||||
"active": "recipe.md"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{}
|
||||
@@ -0,0 +1,94 @@
|
||||
{
|
||||
"message": {
|
||||
"id": "msg2",
|
||||
"role": "assistant",
|
||||
"created_at": "2026-01-02T03:04:05+00:00",
|
||||
"complete": true,
|
||||
"stopped": false,
|
||||
"error": null,
|
||||
"queued": false,
|
||||
"machine": false,
|
||||
"origin": "",
|
||||
"model": "qwen",
|
||||
"attachments": [],
|
||||
"steps": [
|
||||
{
|
||||
"index": 0,
|
||||
"kind": "thinking",
|
||||
"open": false,
|
||||
"text": "The reader wants a recipe.",
|
||||
"label": "for 1 second · 6 tokens"
|
||||
},
|
||||
{
|
||||
"index": 0,
|
||||
"kind": "text",
|
||||
"open": false,
|
||||
"markdown": "Here is how it is made:\n\n```sh\nbake --slow\n```\n"
|
||||
},
|
||||
{
|
||||
"index": 0,
|
||||
"kind": "tools",
|
||||
"open": false,
|
||||
"calls": [
|
||||
{
|
||||
"id": "call1",
|
||||
"name": "bash",
|
||||
"kind": "shell",
|
||||
"status": "ok",
|
||||
"args": {
|
||||
"command": "bake --slow"
|
||||
},
|
||||
"purpose": "Bake one loaf",
|
||||
"text": "baked\n",
|
||||
"exit": 0,
|
||||
"block": {
|
||||
"kind": "shell",
|
||||
"title": "bake --slow",
|
||||
"chips": [
|
||||
"exit 0"
|
||||
],
|
||||
"added": 0,
|
||||
"removed": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"index": 0,
|
||||
"kind": "steer",
|
||||
"open": false,
|
||||
"messages": [
|
||||
{
|
||||
"id": "msg9",
|
||||
"text": "and add honey"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"kind": "text",
|
||||
"open": false,
|
||||
"markdown": "Done. *Wrap it in a leaf.*"
|
||||
}
|
||||
],
|
||||
"plan": null,
|
||||
"metrics": {
|
||||
"prompt_tokens": 120,
|
||||
"completion_tokens": 40,
|
||||
"total_tokens": 160,
|
||||
"context_tokens": 160,
|
||||
"context_limit": 8192,
|
||||
"estimated": false,
|
||||
"elapsed_ms": 4000,
|
||||
"rounds": 2,
|
||||
"thinking_ms": 1200,
|
||||
"percent": 2,
|
||||
"tok_s": 10.0
|
||||
}
|
||||
},
|
||||
"chat": {
|
||||
"id": "chat1",
|
||||
"title": "Waybread"
|
||||
},
|
||||
"next": null
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"jobs": [
|
||||
{
|
||||
"id": "job1",
|
||||
"kind": "subagent",
|
||||
"state": "running",
|
||||
"description": "Find the recipe",
|
||||
"agent": "explore",
|
||||
"model": "qwen",
|
||||
"started": "2026-01-02T03:04:05+00:00",
|
||||
"ended": null,
|
||||
"seconds": 12,
|
||||
"unread": 0,
|
||||
"steps": 3,
|
||||
"tools": 2,
|
||||
"background": true,
|
||||
"exit": null,
|
||||
"command": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"prompt_tokens": 120,
|
||||
"completion_tokens": 40,
|
||||
"total_tokens": 160,
|
||||
"context_tokens": 160,
|
||||
"context_limit": 8192,
|
||||
"estimated": false,
|
||||
"elapsed_ms": 4000,
|
||||
"rounds": 2,
|
||||
"thinking_ms": 1200,
|
||||
"percent": 2,
|
||||
"tok_s": 10.0
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"version": 2,
|
||||
"title": "Bake lembas",
|
||||
"summary": "",
|
||||
"findings": [],
|
||||
"objectives": [],
|
||||
"phases": [
|
||||
{
|
||||
"id": "p1",
|
||||
"title": "Plan",
|
||||
"status": "pending",
|
||||
"tasks": [
|
||||
{
|
||||
"id": "t1",
|
||||
"text": "Gather mallorn leaves",
|
||||
"status": "todo",
|
||||
"note": ""
|
||||
},
|
||||
{
|
||||
"id": "t2",
|
||||
"text": "Bake slowly",
|
||||
"status": "todo",
|
||||
"note": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"steps": [
|
||||
"Gather mallorn leaves",
|
||||
"Bake slowly"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"text": "Running bake --slow"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"ids": [
|
||||
"msg9"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"steps": [
|
||||
{
|
||||
"index": 0,
|
||||
"kind": "thinking",
|
||||
"open": false,
|
||||
"text": "The reader wants a recipe.",
|
||||
"label": "for 1 second · 6 tokens"
|
||||
},
|
||||
{
|
||||
"index": 0,
|
||||
"kind": "text",
|
||||
"open": false,
|
||||
"markdown": "Here is how it is made:\n\n```sh\nbake --slow\n```\n"
|
||||
},
|
||||
{
|
||||
"index": 0,
|
||||
"kind": "tools",
|
||||
"open": false,
|
||||
"calls": [
|
||||
{
|
||||
"id": "call1",
|
||||
"name": "bash",
|
||||
"kind": "shell",
|
||||
"status": "ok",
|
||||
"args": {
|
||||
"command": "bake --slow"
|
||||
},
|
||||
"purpose": "Bake one loaf",
|
||||
"text": "baked\n",
|
||||
"exit": 0,
|
||||
"block": {
|
||||
"kind": "shell",
|
||||
"title": "bake --slow",
|
||||
"chips": [
|
||||
"exit 0"
|
||||
],
|
||||
"added": 0,
|
||||
"removed": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"index": 0,
|
||||
"kind": "steer",
|
||||
"open": false,
|
||||
"messages": [
|
||||
{
|
||||
"id": "msg9",
|
||||
"text": "and add honey"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"tail": {
|
||||
"thinking": "",
|
||||
"text": "Done. *Wrap",
|
||||
"label": "4s"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"thinking": "",
|
||||
"text": "Done. *Wrap",
|
||||
"label": "4s"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"ref": "2124ba9",
|
||||
"commit": "2124ba99e40acb902fe7ddbf2985e6de095299bf",
|
||||
"sha256": "7d0814e428195d1236e4ebaf5d5d8cf6d73900e62824cea143f517ed4cceba34"
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
{
|
||||
"id": "msg2",
|
||||
"role": "assistant",
|
||||
"created_at": "2026-01-02T03:04:05+00:00",
|
||||
"complete": true,
|
||||
"stopped": false,
|
||||
"error": null,
|
||||
"queued": false,
|
||||
"machine": false,
|
||||
"origin": "",
|
||||
"model": "qwen",
|
||||
"attachments": [],
|
||||
"steps": [
|
||||
{
|
||||
"index": 0,
|
||||
"kind": "thinking",
|
||||
"open": false,
|
||||
"text": "The reader wants a recipe.",
|
||||
"label": "for 1 second · 6 tokens"
|
||||
},
|
||||
{
|
||||
"index": 0,
|
||||
"kind": "text",
|
||||
"open": false,
|
||||
"markdown": "Here is how it is made:\n\n```sh\nbake --slow\n```\n"
|
||||
},
|
||||
{
|
||||
"index": 0,
|
||||
"kind": "tools",
|
||||
"open": false,
|
||||
"calls": [
|
||||
{
|
||||
"id": "call1",
|
||||
"name": "bash",
|
||||
"kind": "shell",
|
||||
"status": "ok",
|
||||
"args": {
|
||||
"command": "bake --slow"
|
||||
},
|
||||
"purpose": "Bake one loaf",
|
||||
"text": "baked\n",
|
||||
"exit": 0,
|
||||
"block": {
|
||||
"kind": "shell",
|
||||
"title": "bake --slow",
|
||||
"chips": [
|
||||
"exit 0"
|
||||
],
|
||||
"added": 0,
|
||||
"removed": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"index": 0,
|
||||
"kind": "steer",
|
||||
"open": false,
|
||||
"messages": [
|
||||
{
|
||||
"id": "msg9",
|
||||
"text": "and add honey"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"kind": "text",
|
||||
"open": false,
|
||||
"markdown": "Done. *Wrap it in a leaf.*"
|
||||
}
|
||||
],
|
||||
"plan": null,
|
||||
"metrics": {
|
||||
"prompt_tokens": 120,
|
||||
"completion_tokens": 40,
|
||||
"total_tokens": 160,
|
||||
"context_tokens": 160,
|
||||
"context_limit": 8192,
|
||||
"estimated": false,
|
||||
"elapsed_ms": 4000,
|
||||
"rounds": 2,
|
||||
"thinking_ms": 1200,
|
||||
"percent": 2,
|
||||
"tok_s": 10.0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"id": "msg1",
|
||||
"role": "user",
|
||||
"created_at": "2026-01-02T03:04:05+00:00",
|
||||
"complete": true,
|
||||
"stopped": false,
|
||||
"error": null,
|
||||
"queued": false,
|
||||
"machine": false,
|
||||
"origin": "",
|
||||
"model": null,
|
||||
"attachments": [],
|
||||
"text": "How is lembas made?"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"app_api": 1}
|
||||
@@ -0,0 +1,5 @@
|
||||
org.gradle.jvmargs=-Xmx4g -Dfile.encoding=UTF-8
|
||||
org.gradle.caching=true
|
||||
android.useAndroidX=true
|
||||
android.nonTransitiveRClass=true
|
||||
kotlin.code.style=official
|
||||
@@ -0,0 +1,50 @@
|
||||
# Every version in one place. Nothing from Google Play Services, Firebase or any other
|
||||
# proprietary SDK: the app must build for F-Droid as it is.
|
||||
[versions]
|
||||
agp = "8.13.2"
|
||||
kotlin = "2.2.21"
|
||||
coreKtx = "1.17.0"
|
||||
activityCompose = "1.11.0"
|
||||
lifecycle = "2.9.4"
|
||||
navigation = "2.9.6"
|
||||
composeBom = "2025.12.01"
|
||||
datastore = "1.1.7"
|
||||
browser = "1.9.0"
|
||||
okhttp = "4.12.0"
|
||||
serialization = "1.9.0"
|
||||
coroutines = "1.10.2"
|
||||
markwon = "4.6.2"
|
||||
unifiedpush = "3.3.5"
|
||||
junit = "4.13.2"
|
||||
|
||||
[libraries]
|
||||
androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "coreKtx" }
|
||||
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" }
|
||||
androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" }
|
||||
androidx-lifecycle-viewmodel-compose = { module = "androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "lifecycle" }
|
||||
androidx-lifecycle-service = { module = "androidx.lifecycle:lifecycle-service", version.ref = "lifecycle" }
|
||||
androidx-navigation-compose = { module = "androidx.navigation:navigation-compose", version.ref = "navigation" }
|
||||
androidx-datastore-preferences = { module = "androidx.datastore:datastore-preferences", version.ref = "datastore" }
|
||||
androidx-browser = { module = "androidx.browser:browser", version.ref = "browser" }
|
||||
compose-bom = { module = "androidx.compose:compose-bom", version.ref = "composeBom" }
|
||||
compose-ui = { module = "androidx.compose.ui:ui" }
|
||||
compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview" }
|
||||
compose-material3 = { module = "androidx.compose.material3:material3" }
|
||||
compose-material-icons = { module = "androidx.compose.material:material-icons-extended" }
|
||||
okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" }
|
||||
okhttp-sse = { module = "com.squareup.okhttp3:okhttp-sse", version.ref = "okhttp" }
|
||||
okhttp-mockwebserver = { module = "com.squareup.okhttp3:mockwebserver", version.ref = "okhttp" }
|
||||
kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "serialization" }
|
||||
kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "coroutines" }
|
||||
kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" }
|
||||
markwon-core = { module = "io.noties.markwon:core", version.ref = "markwon" }
|
||||
markwon-tables = { module = "io.noties.markwon:ext-tables", version.ref = "markwon" }
|
||||
markwon-strikethrough = { module = "io.noties.markwon:ext-strikethrough", version.ref = "markwon" }
|
||||
unifiedpush-connector = { module = "org.unifiedpush.android:connector", version.ref = "unifiedpush" }
|
||||
junit = { module = "junit:junit", version.ref = "junit" }
|
||||
|
||||
[plugins]
|
||||
android-application = { id = "com.android.application", version.ref = "agp" }
|
||||
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
|
||||
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
|
||||
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
|
||||
Vendored
BIN
Binary file not shown.
+8
@@ -0,0 +1,8 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.6-bin.zip
|
||||
distributionSha256Sum=7988ed071b2a07900e2ec715fca15c6ab72bce6db433af301fa7fa7e9407bd24
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
@@ -0,0 +1,251 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH="\\\"\\\""
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Vendored
+94
@@ -0,0 +1,94 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
Executable
+64
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The server's contract, pinned: `contract/*.json` from `tests/fixtures/api_v2/` at a ref.
|
||||
|
||||
scripts/fetch-contract.py <server-ref> copy the fixtures at that ref, write contract/lock.json
|
||||
scripts/fetch-contract.py verify: contract/ matches contract/lock.json
|
||||
|
||||
The fixtures are written by the server's serialisers themselves (its
|
||||
`tests/test_api_v2_contract.py`); `ContractTest` parses every one with this app's models. So a
|
||||
shape the server changed is a failing test here, at the moment the pin moves -- not a blank
|
||||
screen on a phone.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
SERVER = Path(os.environ.get("LEMBAS_SERVER", ROOT.parent / "LLeMbas"))
|
||||
SOURCE = "tests/fixtures/api_v2"
|
||||
OUT = ROOT / "contract"
|
||||
LOCK = OUT / "lock.json"
|
||||
|
||||
|
||||
def digest() -> str:
|
||||
h = hashlib.sha256()
|
||||
for path in sorted(OUT.glob("*.json")):
|
||||
if path.name == LOCK.name:
|
||||
continue
|
||||
h.update(path.name.encode() + b"\0" + path.read_bytes())
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def git(*args: str) -> str:
|
||||
return subprocess.run(["git", "-C", str(SERVER), *args], capture_output=True, text=True, check=True).stdout
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if len(sys.argv) == 1:
|
||||
lock = json.loads(LOCK.read_text())
|
||||
if digest() != lock["sha256"]:
|
||||
sys.exit(f"fetch-contract: contract/ does not match {LOCK.name} (server {lock['ref']})")
|
||||
print(f"fetch-contract: contract/ matches the server at {lock['ref']}")
|
||||
return
|
||||
ref = sys.argv[1]
|
||||
commit = git("rev-parse", "--verify", f"{ref}^{{commit}}").strip()
|
||||
names = [n for n in git("ls-tree", "--name-only", f"{commit}:{SOURCE}").split() if n.endswith(".json")]
|
||||
if not names:
|
||||
sys.exit(f"fetch-contract: no fixtures at {ref}:{SOURCE}")
|
||||
OUT.mkdir(exist_ok=True)
|
||||
for old in OUT.glob("*.json"):
|
||||
old.unlink()
|
||||
for name in names:
|
||||
(OUT / name).write_text(git("show", f"{commit}:{SOURCE}/{name}"), encoding="utf-8")
|
||||
LOCK.write_text(json.dumps({"ref": ref, "commit": commit, "sha256": digest()}, indent=2) + "\n")
|
||||
print(f"fetch-contract: {len(names)} files from {ref} ({commit[:12]})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+128
@@ -0,0 +1,128 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The server's colours, as the app's Compose theme.
|
||||
|
||||
scripts/fetch-tokens.py <server-ref> read tokens.css at that ref (a tag such as v1.7.0),
|
||||
write Tokens.kt and tokens.lock.json
|
||||
scripts/fetch-tokens.py verify: Tokens.kt matches tokens.lock.json
|
||||
|
||||
The server is a git checkout, LLeMbas beside this repository by default (LEMBAS_SERVER names
|
||||
another). Only the colour tokens of the two themes are read -- `moria` (declared on `:root`) and
|
||||
`shire` -- and each becomes a `Palette` in Kotlin. The lock records the ref, the commit and the
|
||||
SHA-256 of the generated file, as LLeMbas Desktop's `tokens.lock.json` does: the file in the tree
|
||||
says which server version the look comes from, and CI refuses a copy that drifted.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
SERVER = Path(os.environ.get("LEMBAS_SERVER", ROOT.parent / "LLeMbas"))
|
||||
SOURCE = "src/lembas/web/static/css/tokens.css"
|
||||
OUT = ROOT / "app/src/main/java/eu/llembas/android/ui/theme/Tokens.kt"
|
||||
LOCK = ROOT / "tokens.lock.json"
|
||||
|
||||
# The tokens the app uses, in the order they are written. A token missing from a theme is an
|
||||
# error rather than a default: a palette that silently fell back would look right and be wrong.
|
||||
NAMES = (
|
||||
"bg", "bg-sunken", "surface", "surface-raised", "surface-hover", "surface-active",
|
||||
"border", "border-strong", "ink", "ink-muted", "ink-faint", "ink-inverse",
|
||||
"accent", "accent-hover", "accent-ink", "accent-soft", "leaf", "danger", "danger-soft",
|
||||
"success", "success-soft", "warning", "warning-soft", "bubble-user", "code-bg", "code-border",
|
||||
)
|
||||
|
||||
THEMES = {
|
||||
"moria": r':root,\s*:root\[data-theme="moria"\]\s*\{',
|
||||
"shire": r':root\[data-theme="shire"\],\s*:root\[data-base="shire"\]\s*\{',
|
||||
}
|
||||
|
||||
|
||||
def sha(path: Path) -> str:
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def block(css: str, opener: str) -> str:
|
||||
match = re.search(opener, css)
|
||||
if not match:
|
||||
sys.exit(f"fetch-tokens: no block {opener!r} in {SOURCE}")
|
||||
depth, start = 1, match.end()
|
||||
for i in range(start, len(css)):
|
||||
depth += {"{": 1, "}": -1}.get(css[i], 0)
|
||||
if depth == 0:
|
||||
return css[start:i]
|
||||
sys.exit("fetch-tokens: unbalanced braces")
|
||||
|
||||
|
||||
def argb(value: str) -> str:
|
||||
value = value.strip()
|
||||
if m := re.fullmatch(r"#([0-9a-fA-F]{6})", value):
|
||||
return f"0xFF{m.group(1).upper()}"
|
||||
if m := re.fullmatch(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d.]+)\s*\)", value):
|
||||
r, g, b = (int(m.group(i)) for i in (1, 2, 3))
|
||||
a = round(float(m.group(4)) * 255)
|
||||
return f"0x{a:02X}{r:02X}{g:02X}{b:02X}"
|
||||
sys.exit(f"fetch-tokens: not a colour this script reads: {value!r}")
|
||||
|
||||
|
||||
def camel(name: str) -> str:
|
||||
head, *rest = name.split("-")
|
||||
return head + "".join(p.capitalize() for p in rest)
|
||||
|
||||
|
||||
def generate(css: str, ref: str) -> str:
|
||||
lines = [
|
||||
"// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at "
|
||||
f"{ref}. Do not edit.",
|
||||
"package eu.llembas.android.ui.theme",
|
||||
"",
|
||||
"import androidx.compose.ui.graphics.Color",
|
||||
"",
|
||||
"data class Palette(",
|
||||
*[f" val {camel(n)}: Color," for n in NAMES],
|
||||
")",
|
||||
"",
|
||||
]
|
||||
for theme, opener in THEMES.items():
|
||||
body = block(css, opener)
|
||||
values = dict(re.findall(r"--([a-z0-9-]+)\s*:\s*([^;]+);", body))
|
||||
missing = [n for n in NAMES if n not in values]
|
||||
if missing:
|
||||
sys.exit(f"fetch-tokens: {theme} has no {', '.join(missing)}")
|
||||
lines.append(f"val {theme.capitalize()} = Palette(")
|
||||
lines += [f" {camel(n)} = Color({argb(values[n])}L)," for n in NAMES]
|
||||
lines += [")", ""]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if len(sys.argv) == 1:
|
||||
lock = json.loads(LOCK.read_text())
|
||||
if sha(OUT) != lock["sha256"]:
|
||||
sys.exit(f"fetch-tokens: {OUT.name} does not match {LOCK.name} (server {lock['tag']})")
|
||||
print(f"fetch-tokens: {OUT.name} matches {LOCK.name} (server {lock['tag']})")
|
||||
return
|
||||
ref = sys.argv[1]
|
||||
commit = subprocess.run(
|
||||
["git", "-C", str(SERVER), "rev-parse", "--verify", f"{ref}^{{commit}}"],
|
||||
capture_output=True, text=True, check=True,
|
||||
).stdout.strip()
|
||||
css = subprocess.run(
|
||||
["git", "-C", str(SERVER), "show", f"{commit}:{SOURCE}"],
|
||||
capture_output=True, text=True, check=True,
|
||||
).stdout
|
||||
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
OUT.write_text(generate(css, ref), encoding="utf-8")
|
||||
LOCK.write_text(
|
||||
json.dumps({"tag": ref, "commit": commit, "sha256": sha(OUT)}, indent=2) + "\n"
|
||||
)
|
||||
print(f"fetch-tokens: wrote {OUT.relative_to(ROOT)} from {ref} ({commit[:12]})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+81
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The app's icons, from the server's pixel leaf (`web/static/img/logo-mark.svg`).
|
||||
|
||||
scripts/gen-icons.py [<server-ref>] (default HEAD of ../LLeMbas, or LEMBAS_SERVER)
|
||||
|
||||
The mark is a 16x16 grid of rects, so it converts exactly into Android vector drawables -- one
|
||||
path per colour -- and needs no PNG at any density:
|
||||
|
||||
drawable/ic_launcher_foreground.xml the leaf, in the adaptive icon's 66dp safe zone
|
||||
drawable/ic_launcher_monochrome.xml its silhouette, for themed icons
|
||||
drawable/ic_notification.xml the same silhouette: a status-bar icon is alpha only
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
SERVER = Path(os.environ.get("LEMBAS_SERVER", ROOT.parent / "LLeMbas"))
|
||||
SOURCE = "src/lembas/web/static/img/logo-mark.svg"
|
||||
RES = ROOT / "app/src/main/res/drawable"
|
||||
HEADER = "<!-- Generated by scripts/gen-icons.py from the LLeMbas server's logo-mark.svg. Do not edit. -->"
|
||||
|
||||
|
||||
def rects(svg: str) -> list[tuple[int, int, int, int, str]]:
|
||||
found = []
|
||||
for attrs in re.findall(r"<rect\s+([^>]*)/>", svg):
|
||||
a = dict(re.findall(r'(\w+)="([^"]*)"', attrs))
|
||||
found.append((int(a["x"]), int(a["y"]), int(a["width"]), int(a["height"]), a["fill"].upper()))
|
||||
if not found:
|
||||
sys.exit("gen-icons: no rects in the mark")
|
||||
return found
|
||||
|
||||
|
||||
def path(cells) -> str:
|
||||
return " ".join(f"M{x},{y}h{w}v{h}h-{w}z" for x, y, w, h, _ in cells)
|
||||
|
||||
|
||||
def vector(size: int, viewport: int, body: str) -> str:
|
||||
return (
|
||||
f'<?xml version="1.0" encoding="utf-8"?>\n{HEADER}\n'
|
||||
'<vector xmlns:android="http://schemas.android.com/apk/res/android"\n'
|
||||
f' android:width="{size}dp" android:height="{size}dp"\n'
|
||||
f' android:viewportWidth="{viewport}" android:viewportHeight="{viewport}">\n'
|
||||
f"{body}</vector>\n"
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ref = sys.argv[1] if len(sys.argv) > 1 else "HEAD"
|
||||
svg = subprocess.run(
|
||||
["git", "-C", str(SERVER), "show", f"{ref}:{SOURCE}"], capture_output=True, text=True, check=True
|
||||
).stdout
|
||||
cells = rects(svg)
|
||||
by_colour: dict[str, list] = defaultdict(list)
|
||||
for cell in cells:
|
||||
by_colour[cell[4]].append(cell)
|
||||
|
||||
# 108dp adaptive canvas; the leaf scaled x3.5 (56dp) and centred, inside the 66dp safe zone.
|
||||
coloured = "".join(
|
||||
f' <path android:fillColor="{colour}" android:pathData="{path(group)}"/>\n'
|
||||
for colour, group in sorted(by_colour.items())
|
||||
)
|
||||
group = f' <group android:translateX="26" android:translateY="26" android:scaleX="3.5" android:scaleY="3.5">\n{coloured} </group>\n'
|
||||
silhouette = f' <path android:fillColor="#FFFFFFFF" android:pathData="{path(cells)}"/>\n'
|
||||
mono = f' <group android:translateX="26" android:translateY="26" android:scaleX="3.5" android:scaleY="3.5">\n{silhouette} </group>\n'
|
||||
|
||||
RES.mkdir(parents=True, exist_ok=True)
|
||||
(RES / "ic_launcher_foreground.xml").write_text(vector(108, 108, group))
|
||||
(RES / "ic_launcher_monochrome.xml").write_text(vector(108, 108, mono))
|
||||
(RES / "ic_notification.xml").write_text(vector(24, 16, silhouette.replace(" ", " ")))
|
||||
print(f"gen-icons: {len(cells)} cells in {len(by_colour)} colours, from {ref}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+91
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Write the app's string resources: English from `strings.py`, the eight translations from
|
||||
the server's catalogues and `strings_own.json`. See `strings.py` for the rule.
|
||||
|
||||
scripts/gen-strings.py (server at ../LLeMbas, or LEMBAS_SERVER)
|
||||
scripts/gen-strings.py --check fail if a key the code uses has no English, or the other way round
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from xml.sax.saxutils import escape
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
SERVER = Path(os.environ.get("LEMBAS_SERVER", ROOT.parent / "LLeMbas"))
|
||||
RES = ROOT / "app/src/main/res"
|
||||
LANGS = ("cs", "de", "es", "fr", "hu", "it", "pl", "sk")
|
||||
HEADER = "<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->"
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
from strings import STRINGS # noqa: E402
|
||||
|
||||
|
||||
def android(text: str) -> str:
|
||||
"""Escaped for a <string>: XML, then Android's own apostrophe and quote rules."""
|
||||
return escape(text).replace("'", "\\'").replace('"', '\\"')
|
||||
|
||||
|
||||
def server_catalogue(code: str) -> dict[str, str]:
|
||||
path = SERVER / "src/lembas/web/i18n" / f"{code}.py"
|
||||
if not path.exists():
|
||||
return {}
|
||||
spec = importlib.util.spec_from_file_location(f"catalogue_{code}", path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.dont_write_bytecode = True
|
||||
spec.loader.exec_module(module)
|
||||
return dict(getattr(module, "MESSAGES", {}))
|
||||
|
||||
|
||||
def used_keys() -> set[str]:
|
||||
keys: set[str] = set()
|
||||
for path in (ROOT / "app/src").rglob("*"):
|
||||
if path.suffix in (".kt", ".xml") and "/res/values" not in str(path):
|
||||
keys |= set(re.findall(r"(?:R\.string\.|@string/)([a-z_]+)", path.read_text(errors="ignore")))
|
||||
return keys
|
||||
|
||||
|
||||
def write(folder: Path, entries: dict[str, str]) -> None:
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
lines = ['<?xml version="1.0" encoding="utf-8"?>', HEADER, "<resources>"]
|
||||
for key, text in entries.items():
|
||||
extra = ' translatable="false"' if key == "app_name" else ""
|
||||
lines.append(f' <string name="{key}"{extra}>{android(text)}</string>')
|
||||
lines.append("</resources>")
|
||||
(folder / "strings.xml").write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
used = used_keys()
|
||||
missing = sorted(used - set(STRINGS))
|
||||
unused = sorted(set(STRINGS) - used)
|
||||
if missing or unused:
|
||||
print(f"gen-strings: used but not in strings.py: {missing}; in strings.py but unused: {unused}")
|
||||
if "--check" in sys.argv or missing:
|
||||
sys.exit(1)
|
||||
if "--check" in sys.argv:
|
||||
print(f"gen-strings: {len(STRINGS)} strings, all used")
|
||||
return
|
||||
own = json.loads((Path(__file__).parent / "strings_own.json").read_text(encoding="utf-8"))
|
||||
write(RES / "values", STRINGS)
|
||||
for code in LANGS:
|
||||
catalogue = server_catalogue(code)
|
||||
mine = own.get(code, {})
|
||||
out = {}
|
||||
for key, english in STRINGS.items():
|
||||
if key == "app_name":
|
||||
continue
|
||||
text = mine.get(key) or catalogue.get(english)
|
||||
if text and text.count("%1$s") == english.count("%1$s"):
|
||||
out[key] = text
|
||||
write(RES / f"values-{code}", out)
|
||||
print(f"gen-strings: {code}: {len(out)}/{len(STRINGS) - 1}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+29
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env bash
|
||||
# The repository is public: nothing in it may name the private estate it was written on.
|
||||
# The LLeMbas section rule ("everything public is current-state and estate-free"), as a check
|
||||
# that runs in CI on every push rather than a sentence somebody has to remember.
|
||||
#
|
||||
# Patterns are the kinds of thing that leak: a private domain, an internal `.lan` name, a
|
||||
# container number, a private address range, a machine's name. This file is the one place that
|
||||
# may spell them, and is skipped.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
patterns=(
|
||||
'houmeres'
|
||||
'\b[a-z0-9-]+\.lan\b'
|
||||
'\bCT ?2[0-9]{2}\b'
|
||||
'\b10\.0\.0\.[0-9]+'
|
||||
'\b192\.168\.[0-9]+\.[0-9]+'
|
||||
'\bgamebox\b'
|
||||
'\bthor\b'
|
||||
)
|
||||
found=0
|
||||
for pattern in "${patterns[@]}"; do
|
||||
if git ls-files -z | grep -zv '^scripts/hygiene.sh$' | xargs -0 grep -nIEi -- "$pattern" ; then
|
||||
echo "hygiene: the lines above match /$pattern/" >&2
|
||||
found=1
|
||||
fi
|
||||
done
|
||||
[ "$found" -eq 0 ] && echo "hygiene: nothing private in the tracked files"
|
||||
exit "$found"
|
||||
Executable
+116
@@ -0,0 +1,116 @@
|
||||
"""The app's text, in English, keyed by its Android resource name.
|
||||
|
||||
`gen-strings.py` turns this into `res/values/strings.xml` and, per language, takes the
|
||||
translation from the LLeMbas server's own catalogue where the English sentence is one the server
|
||||
already has (so "Archive" or "New chat" is worded the same on the phone as on the page), and
|
||||
from `strings_own.json` for the sentences only the app has. A sentence in neither is left out of
|
||||
that language, and Android shows the English -- a half-translated screen, never a broken one.
|
||||
|
||||
Flavour stays where the server keeps it: in empty states and loading lines. Buttons say what
|
||||
they do. `%1$s` is Android's placeholder; it is never translated away.
|
||||
"""
|
||||
|
||||
STRINGS: dict[str, str] = {
|
||||
"app_name": "LLeMbas",
|
||||
"device_name": "LLeMbas for Android",
|
||||
"share_label": "Ask LLeMbas",
|
||||
"tile_ask": "Ask LLeMbas",
|
||||
# Sign-in
|
||||
"signin_intro": "Sign in to a LLeMbas instance. You approve this phone in the browser, as you would the CLI.",
|
||||
"signin_address": "Instance address",
|
||||
"signin_continue": "Continue",
|
||||
"signin_code_intro": "Open the instance in the browser, sign in, and approve this code:",
|
||||
"signin_open_browser": "Open in the browser",
|
||||
"signin_denied": "The sign-in was refused.",
|
||||
"signin_expired": "The code expired before it was approved. Try again.",
|
||||
"signin_too_old": "This instance has no app API yet. It needs LLeMbas 1.7.0 or newer.",
|
||||
"signin_too_new": "This instance speaks a newer app API than this app. Update the app.",
|
||||
# Chats
|
||||
"new_chat": "New chat",
|
||||
"tab_chats": "Chats",
|
||||
"tab_agents": "Agents",
|
||||
"empty_chats": "No chats yet. Not all those who wander are lost — start one.",
|
||||
"empty_agents": "No agent chats. Start one from the web interface on a linked device.",
|
||||
"empty_chat": "What shall we talk about?",
|
||||
"loading_line": "Baking lembas…",
|
||||
"archive": "Archive",
|
||||
"delete": "Delete",
|
||||
"edit": "Edit",
|
||||
"regenerate": "Regenerate",
|
||||
"continue_reply": "Continue",
|
||||
"older": "Earlier messages",
|
||||
"queued": "Waiting to be sent",
|
||||
"thinking": "Thinking",
|
||||
"thought": "Thought",
|
||||
"output_cut": "Output shortened here. The whole of it is on the web page.",
|
||||
"composer_hint": "Message",
|
||||
"listening": "Listening…",
|
||||
"send": "Send",
|
||||
"stop": "Stop",
|
||||
"attach": "Attach a file",
|
||||
"dictate": "Dictate",
|
||||
"remove": "Remove",
|
||||
"more": "More",
|
||||
"back": "Back",
|
||||
"cancel": "Cancel",
|
||||
"close": "Close",
|
||||
"effort_off": "Effort: off",
|
||||
"mode_plan": "Plan",
|
||||
"mode_edit": "Edit",
|
||||
"mode_manual": "Manual",
|
||||
# Cards
|
||||
"card_approval": "Allow this?",
|
||||
"card_allow_once": "Allow once",
|
||||
"card_allow_always": "Always allow this",
|
||||
"card_deny": "Deny",
|
||||
"card_reason": "Why not? (optional)",
|
||||
"card_recommended": "recommended",
|
||||
"card_answer": "Your answer",
|
||||
"card_something_else": "Something else",
|
||||
"card_send": "Send",
|
||||
"plan_approve": "Approve the plan",
|
||||
"plan_revise": "Revise",
|
||||
"plan_what_to_change": "What should change?",
|
||||
"plan_carry_out": "Carry out the plan",
|
||||
# Settings
|
||||
"settings": "Settings",
|
||||
"settings_instances": "Instances",
|
||||
"sign_out": "Sign out",
|
||||
"add_instance": "Add an instance",
|
||||
"settings_theme": "Theme",
|
||||
"theme_system": "As the system",
|
||||
"theme_moria": "Moria (dark)",
|
||||
"theme_shire": "Shire (light)",
|
||||
"settings_notifications": "Notifications",
|
||||
"push_explained": "Notifications come through UnifiedPush, with no Google services: the distributor app you chose carries them, encrypted for this phone only.",
|
||||
"push_no_distributor": "To be told when a reply is ready, install a UnifiedPush distributor such as ntfy, then come back here. Without one, the app shows new replies when it is open.",
|
||||
"push_enable": "Turn notifications on",
|
||||
"push_on": "Notifications are on for this instance.",
|
||||
"push_failed": "No distributor was chosen, so notifications are still off.",
|
||||
"channel_replies": "Replies",
|
||||
"channel_asks": "Questions and approvals",
|
||||
"channel_reports": "Reports",
|
||||
"settings_assistant": "Assistant",
|
||||
"assistant_explained": "Make LLeMbas the phone's digital assistant: choose it under Default apps › Digital assistant app. Then holding the power button, the assist gesture or the lock screen's shortcut opens it over whatever is on screen.",
|
||||
"assistant_open_settings": "Open the assistant settings",
|
||||
"assistant_samsung": "On Samsung phones: Settings › Advanced features › Side button › Press and hold › Digital assistant.",
|
||||
"assistant_temporary": "Assistant chats are temporary",
|
||||
"assistant_read_aloud": "Read the answer aloud when asked by voice",
|
||||
"settings_about": "About",
|
||||
"about_version": "LLeMbas for Android %1$s",
|
||||
"update_check": "Check for an update",
|
||||
"update_none": "This is the newest version.",
|
||||
"update_unreachable": "The update could not be fetched.",
|
||||
"update_allow_installs": "Allow LLeMbas to install updates, then check again.",
|
||||
"update_bad_file": "The download did not match the release and was discarded.",
|
||||
"update_installing": "Installing %1$s…",
|
||||
# Assistant
|
||||
"assist_hint": "Ask anything",
|
||||
"assist_include_screen": "Include screen",
|
||||
"assist_signed_out": "Sign in to a LLeMbas instance in the app first.",
|
||||
"assist_open_app": "Open the app",
|
||||
"assist_open_in_app": "Continue in the app",
|
||||
# Share
|
||||
"share_sending": "Sending to LLeMbas…",
|
||||
"share_default_prompt": "Have a look at this.",
|
||||
}
|
||||
@@ -0,0 +1,522 @@
|
||||
{
|
||||
"cs": {
|
||||
"about_version": "LLeMbas pro Android %1$s",
|
||||
"add_instance": "Přidat instanci",
|
||||
"archive": "Archivovat",
|
||||
"assist_hint": "Zeptejte se na cokoli",
|
||||
"assist_include_screen": "Zahrnout obrazovku",
|
||||
"assist_open_app": "Otevřít aplikaci",
|
||||
"assist_open_in_app": "Pokračovat v aplikaci",
|
||||
"assist_signed_out": "Nejprve se v aplikaci přihlaste k instanci LLeMbas.",
|
||||
"assistant_explained": "Nastavte LLeMbas jako digitálního asistenta telefonu: zvolte ho v Výchozí aplikace › Digitální asistent. Podržení tlačítka napájení, gesto asistenta nebo zkratka na zamykací obrazovce ho pak otevře přes to, co je právě na obrazovce.",
|
||||
"assistant_open_settings": "Otevřít nastavení asistenta",
|
||||
"assistant_read_aloud": "Přečíst odpověď nahlas, když se zeptáte hlasem",
|
||||
"assistant_samsung": "Na telefonech Samsung: Nastavení › Pokročilé funkce › Boční tlačítko › Stisknutí a podržení › Digitální asistent.",
|
||||
"assistant_temporary": "Konverzace s asistentem jsou dočasné",
|
||||
"attach": "Přiložit soubor",
|
||||
"card_allow_once": "Povolit jednou",
|
||||
"card_answer": "Vaše odpověď",
|
||||
"card_approval": "Povolit to?",
|
||||
"card_reason": "Proč ne? (nepovinné)",
|
||||
"channel_asks": "Otázky a schválení",
|
||||
"device_name": "LLeMbas pro Android",
|
||||
"effort_off": "Úsilí: vypnuto",
|
||||
"empty_agents": "Žádné konverzace s agentem. Spusťte jednu z webového rozhraní na propojeném zařízení.",
|
||||
"empty_chat": "O čem si promluvíme?",
|
||||
"empty_chats": "Zatím žádné konverzace. Ne všichni, kdo bloudí, jsou ztraceni — založte jednu.",
|
||||
"listening": "Naslouchám…",
|
||||
"loading_line": "Pečou se lembasy…",
|
||||
"mode_manual": "Manual",
|
||||
"more": "Více",
|
||||
"older": "Starší zprávy",
|
||||
"output_cut": "Výstup je zde zkrácen. Celý ho najdete na webové stránce.",
|
||||
"plan_approve": "Schválit plán",
|
||||
"plan_carry_out": "Provést plán",
|
||||
"plan_what_to_change": "Co by se mělo změnit?",
|
||||
"push_enable": "Zapnout upozornění",
|
||||
"push_explained": "Upozornění chodí přes UnifiedPush, bez služeb Google: doručuje je distribuční aplikace, kterou jste zvolili; jsou zašifrované jen pro tento telefon.",
|
||||
"push_failed": "Nebyl zvolen žádný distributor, takže upozornění jsou stále vypnutá.",
|
||||
"push_no_distributor": "Abyste se dozvěděli, že je odpověď hotová, nainstalujte distributora UnifiedPush, například ntfy, a pak se vraťte sem. Bez něj aplikace nové odpovědi ukáže, jen když je otevřená.",
|
||||
"push_on": "Upozornění jsou pro tuto instanci zapnutá.",
|
||||
"regenerate": "Vygenerovat znovu",
|
||||
"settings_about": "O aplikaci",
|
||||
"settings_assistant": "Asistent",
|
||||
"settings_instances": "Instance",
|
||||
"share_default_prompt": "Podívejte se na tohle.",
|
||||
"share_label": "Zeptat se LLeMbas",
|
||||
"share_sending": "Odesílá se do LLeMbas…",
|
||||
"signin_address": "Adresa instance",
|
||||
"signin_code_intro": "Otevřete instanci v prohlížeči, přihlaste se a schvalte tento kód:",
|
||||
"signin_denied": "Přihlášení bylo odmítnuto.",
|
||||
"signin_expired": "Kód vypršel, než byl schválen. Zkuste to znovu.",
|
||||
"signin_intro": "Přihlaste se k instanci LLeMbas. Tento telefon schválíte v prohlížeči, stejně jako u CLI.",
|
||||
"signin_open_browser": "Otevřít v prohlížeči",
|
||||
"signin_too_new": "Tato instance používá novější rozhraní API pro aplikace než tato aplikace. Aktualizujte aplikaci.",
|
||||
"signin_too_old": "Tato instance ještě nemá rozhraní API pro aplikace. Potřebuje LLeMbas 1.7.0 nebo novější.",
|
||||
"theme_moria": "Moria (temná)",
|
||||
"theme_shire": "Shire (světlý)",
|
||||
"theme_system": "Podle systému",
|
||||
"tile_ask": "Zeptat se LLeMbas",
|
||||
"update_allow_installs": "Povolte aplikaci LLeMbas instalovat aktualizace a pak to zkontrolujte znovu.",
|
||||
"update_bad_file": "Stažený soubor neodpovídal verzi a byl zahozen.",
|
||||
"update_check": "Zkontrolovat aktualizaci",
|
||||
"update_installing": "Instaluje se %1$s…",
|
||||
"update_none": "Toto je nejnovější verze.",
|
||||
"update_unreachable": "Aktualizaci se nepodařilo stáhnout."
|
||||
},
|
||||
"de": {
|
||||
"about_version": "LLeMbas für Android %1$s",
|
||||
"add_instance": "Instanz hinzufügen",
|
||||
"archive": "Archivieren",
|
||||
"assist_hint": "Fragen Sie irgendetwas",
|
||||
"assist_include_screen": "Bildschirm einbeziehen",
|
||||
"assist_open_app": "App öffnen",
|
||||
"assist_open_in_app": "In der App fortsetzen",
|
||||
"assist_signed_out": "Melden Sie sich zuerst in der App bei einer LLeMbas-Instanz an.",
|
||||
"assistant_explained": "Machen Sie LLeMbas zum digitalen Assistenten des Telefons: Wählen Sie ihn unter Standard-Apps › Digitaler Assistent. Das Halten der Einschalttaste, die Assistenzgeste oder die Verknüpfung auf dem Sperrbildschirm öffnet ihn dann über allem, was gerade angezeigt wird.",
|
||||
"assistant_open_settings": "Assistenten-Einstellungen öffnen",
|
||||
"assistant_read_aloud": "Antwort vorlesen, wenn per Sprache gefragt wurde",
|
||||
"assistant_samsung": "Auf Samsung-Telefonen: Einstellungen › Erweiterte Funktionen › Seitentaste › Gedrückt halten › Digitaler Assistent.",
|
||||
"assistant_temporary": "Assistenten-Chats sind temporär",
|
||||
"attach": "Datei anhängen",
|
||||
"card_allow_once": "Einmal erlauben",
|
||||
"card_answer": "Ihre Antwort",
|
||||
"card_approval": "Das erlauben?",
|
||||
"card_reason": "Warum nicht? (optional)",
|
||||
"channel_asks": "Fragen und Bestätigungen",
|
||||
"device_name": "LLeMbas für Android",
|
||||
"effort_off": "Aufwand: aus",
|
||||
"empty_agents": "Keine Agent-Chats. Starten Sie einen über die Weboberfläche auf einem verknüpften Gerät.",
|
||||
"empty_chat": "Worüber sprechen wir?",
|
||||
"empty_chats": "Noch keine Chats. Nicht jeder, der wandert, ist verloren — fangen Sie einen an.",
|
||||
"listening": "Hört zu…",
|
||||
"loading_line": "Lembas wird gebacken…",
|
||||
"mode_manual": "Manual",
|
||||
"more": "Mehr",
|
||||
"older": "Frühere Nachrichten",
|
||||
"output_cut": "Die Ausgabe ist hier verkürzt. Vollständig finden Sie sie auf der Webseite.",
|
||||
"plan_approve": "Plan bestätigen",
|
||||
"plan_carry_out": "Plan ausführen",
|
||||
"plan_what_to_change": "Was soll sich ändern?",
|
||||
"push_enable": "Benachrichtigungen einschalten",
|
||||
"push_explained": "Benachrichtigungen kommen über UnifiedPush, ohne Google-Dienste: Die von Ihnen gewählte Distributor-App trägt sie, verschlüsselt nur für dieses Telefon.",
|
||||
"push_failed": "Es wurde kein Distributor gewählt, daher sind die Benachrichtigungen noch ausgeschaltet.",
|
||||
"push_no_distributor": "Um erfahren zu lassen, wenn eine Antwort fertig ist, installieren Sie einen UnifiedPush-Distributor wie ntfy und kommen Sie dann hierher zurück. Ohne einen zeigt die App neue Antworten nur, wenn sie geöffnet ist.",
|
||||
"push_on": "Benachrichtigungen sind für diese Instanz eingeschaltet.",
|
||||
"regenerate": "Neu generieren",
|
||||
"settings_about": "Über",
|
||||
"settings_assistant": "Assistent",
|
||||
"settings_instances": "Instanzen",
|
||||
"share_default_prompt": "Schauen Sie sich das an.",
|
||||
"share_label": "LLeMbas fragen",
|
||||
"share_sending": "Wird an LLeMbas gesendet…",
|
||||
"signin_address": "Adresse der Instanz",
|
||||
"signin_code_intro": "Öffnen Sie die Instanz im Browser, melden Sie sich an und bestätigen Sie diesen Code:",
|
||||
"signin_denied": "Die Anmeldung wurde abgelehnt.",
|
||||
"signin_expired": "Der Code ist abgelaufen, bevor er bestätigt wurde. Versuchen Sie es erneut.",
|
||||
"signin_intro": "Melden Sie sich bei einer LLeMbas-Instanz an. Sie bestätigen dieses Telefon im Browser, genau wie bei der CLI.",
|
||||
"signin_open_browser": "Im Browser öffnen",
|
||||
"signin_too_new": "Diese Instanz spricht eine neuere App-API als diese App. Aktualisieren Sie die App.",
|
||||
"signin_too_old": "Diese Instanz hat noch keine App-API. Sie braucht LLeMbas 1.7.0 oder neuer.",
|
||||
"theme_moria": "Moria (dunkel)",
|
||||
"theme_shire": "Shire (hell)",
|
||||
"theme_system": "Wie das System",
|
||||
"tile_ask": "LLeMbas fragen",
|
||||
"update_allow_installs": "Erlauben Sie LLeMbas, Updates zu installieren, und prüfen Sie dann erneut.",
|
||||
"update_bad_file": "Der Download stimmte nicht mit der Version überein und wurde verworfen.",
|
||||
"update_check": "Nach einem Update suchen",
|
||||
"update_installing": "%1$s wird installiert…",
|
||||
"update_none": "Dies ist die neueste Version.",
|
||||
"update_unreachable": "Das Update konnte nicht abgerufen werden."
|
||||
},
|
||||
"es": {
|
||||
"about_version": "LLeMbas para Android %1$s",
|
||||
"add_instance": "Añadir una instancia",
|
||||
"archive": "Archivar",
|
||||
"assist_hint": "Pregunte lo que quiera",
|
||||
"assist_include_screen": "Incluir pantalla",
|
||||
"assist_open_app": "Abrir la aplicación",
|
||||
"assist_open_in_app": "Continuar en la aplicación",
|
||||
"assist_signed_out": "Primero inicie sesión en una instancia de LLeMbas en la aplicación.",
|
||||
"assistant_explained": "Convierta LLeMbas en el asistente digital del teléfono: elíjalo en Aplicaciones predeterminadas › App de asistencia digital. Mantener pulsado el botón de encendido, el gesto de asistencia o el acceso directo de la pantalla de bloqueo lo abrirá entonces sobre lo que haya en pantalla.",
|
||||
"assistant_open_settings": "Abrir los ajustes del asistente",
|
||||
"assistant_read_aloud": "Leer la respuesta en voz alta cuando se pregunte por voz",
|
||||
"assistant_samsung": "En los teléfonos Samsung: Ajustes › Funciones avanzadas › Botón lateral › Mantener pulsado › Asistente digital.",
|
||||
"assistant_temporary": "Los chats del asistente son temporales",
|
||||
"attach": "Adjuntar un archivo",
|
||||
"card_allow_once": "Permitir una vez",
|
||||
"card_answer": "Su respuesta",
|
||||
"card_approval": "¿Permitir esto?",
|
||||
"card_reason": "¿Por qué no? (opcional)",
|
||||
"channel_asks": "Preguntas y aprobaciones",
|
||||
"device_name": "LLeMbas para Android",
|
||||
"effort_off": "Esfuerzo: desactivado",
|
||||
"empty_agents": "No hay chats de agente. Inicie uno desde la interfaz web en un dispositivo vinculado.",
|
||||
"empty_chat": "¿De qué hablamos?",
|
||||
"empty_chats": "Aún no hay chats. No todos los que vagan están perdidos — empiece uno.",
|
||||
"listening": "Escuchando…",
|
||||
"loading_line": "Horneando lembas…",
|
||||
"mode_manual": "Manual",
|
||||
"more": "Más",
|
||||
"older": "Mensajes anteriores",
|
||||
"output_cut": "La salida está acortada aquí. La tiene completa en la página web.",
|
||||
"plan_approve": "Aprobar el plan",
|
||||
"plan_carry_out": "Llevar a cabo el plan",
|
||||
"plan_what_to_change": "¿Qué debería cambiar?",
|
||||
"push_enable": "Activar las notificaciones",
|
||||
"push_explained": "Las notificaciones llegan mediante UnifiedPush, sin servicios de Google: la aplicación distribuidora que eligió las transporta, cifradas solo para este teléfono.",
|
||||
"push_failed": "No se eligió ningún distribuidor, así que las notificaciones siguen desactivadas.",
|
||||
"push_no_distributor": "Para que le avisen cuando una respuesta esté lista, instale un distribuidor de UnifiedPush como ntfy y luego vuelva aquí. Sin uno, la aplicación muestra las respuestas nuevas solo cuando está abierta.",
|
||||
"push_on": "Las notificaciones están activadas para esta instancia.",
|
||||
"regenerate": "Regenerar",
|
||||
"settings_about": "Acerca de",
|
||||
"settings_assistant": "Asistente",
|
||||
"settings_instances": "Instancias",
|
||||
"share_default_prompt": "Échele un vistazo a esto.",
|
||||
"share_label": "Preguntar a LLeMbas",
|
||||
"share_sending": "Enviando a LLeMbas…",
|
||||
"signin_address": "Dirección de la instancia",
|
||||
"signin_code_intro": "Abra la instancia en el navegador, inicie sesión y apruebe este código:",
|
||||
"signin_denied": "El inicio de sesión fue rechazado.",
|
||||
"signin_expired": "El código caducó antes de ser aprobado. Inténtelo de nuevo.",
|
||||
"signin_intro": "Inicie sesión en una instancia de LLeMbas. Aprobará este teléfono en el navegador, igual que haría con la CLI.",
|
||||
"signin_open_browser": "Abrir en el navegador",
|
||||
"signin_too_new": "Esta instancia habla una API de aplicaciones más reciente que esta aplicación. Actualice la aplicación.",
|
||||
"signin_too_old": "Esta instancia aún no tiene API para aplicaciones. Necesita LLeMbas 1.7.0 o una versión posterior.",
|
||||
"theme_moria": "Moria (oscuro)",
|
||||
"theme_shire": "Shire (claro)",
|
||||
"theme_system": "Como el sistema",
|
||||
"tile_ask": "Preguntar a LLeMbas",
|
||||
"update_allow_installs": "Permita que LLeMbas instale actualizaciones y vuelva a comprobarlo.",
|
||||
"update_bad_file": "La descarga no coincidía con la versión y se descartó.",
|
||||
"update_check": "Buscar una actualización",
|
||||
"update_installing": "Instalando %1$s…",
|
||||
"update_none": "Esta es la versión más reciente.",
|
||||
"update_unreachable": "No se pudo obtener la actualización."
|
||||
},
|
||||
"fr": {
|
||||
"about_version": "LLeMbas pour Android %1$s",
|
||||
"add_instance": "Ajouter une instance",
|
||||
"archive": "Archiver",
|
||||
"assist_hint": "Demandez n'importe quoi",
|
||||
"assist_include_screen": "Inclure l'écran",
|
||||
"assist_open_app": "Ouvrir l'application",
|
||||
"assist_open_in_app": "Continuer dans l'application",
|
||||
"assist_signed_out": "Connectez-vous d'abord à une instance LLeMbas dans l'application.",
|
||||
"assistant_explained": "Faites de LLeMbas l'assistant numérique du téléphone : choisissez-le dans Applications par défaut › Application d'assistance numérique. Maintenir le bouton d'alimentation, le geste d'assistance ou le raccourci de l'écran de verrouillage l'ouvrira alors par-dessus ce qui est affiché.",
|
||||
"assistant_open_settings": "Ouvrir les paramètres de l'assistant",
|
||||
"assistant_read_aloud": "Lire la réponse à voix haute en cas de question orale",
|
||||
"assistant_samsung": "Sur les téléphones Samsung : Paramètres › Fonctions avancées › Bouton latéral › Maintenir enfoncé › Assistant numérique.",
|
||||
"assistant_temporary": "Les conversations de l'assistant sont temporaires",
|
||||
"attach": "Joindre un fichier",
|
||||
"card_allow_once": "Autoriser une fois",
|
||||
"card_answer": "Votre réponse",
|
||||
"card_approval": "Autoriser ceci ?",
|
||||
"card_reason": "Pourquoi pas ? (facultatif)",
|
||||
"channel_asks": "Questions et approbations",
|
||||
"device_name": "LLeMbas pour Android",
|
||||
"effort_off": "Effort : désactivé",
|
||||
"empty_agents": "Aucune conversation d'agent. Démarrez-en une depuis l'interface web sur un appareil associé.",
|
||||
"empty_chat": "De quoi allons-nous parler ?",
|
||||
"empty_chats": "Pas encore de conversation. Tous ceux qui errent ne sont pas perdus — commencez-en une.",
|
||||
"listening": "Écoute…",
|
||||
"loading_line": "Cuisson des lembas…",
|
||||
"mode_manual": "Manual",
|
||||
"more": "Plus",
|
||||
"older": "Messages précédents",
|
||||
"output_cut": "La sortie est raccourcie ici. Vous la trouverez en entier sur la page web.",
|
||||
"plan_approve": "Approuver le plan",
|
||||
"plan_carry_out": "Exécuter le plan",
|
||||
"plan_what_to_change": "Qu'est-ce qui doit changer ?",
|
||||
"push_enable": "Activer les notifications",
|
||||
"push_explained": "Les notifications arrivent par UnifiedPush, sans services Google : l'application distributrice que vous avez choisie les transporte, chiffrées pour ce téléphone uniquement.",
|
||||
"push_failed": "Aucun distributeur n'a été choisi, les notifications sont donc toujours désactivées.",
|
||||
"push_no_distributor": "Pour être averti quand une réponse est prête, installez un distributeur UnifiedPush tel que ntfy, puis revenez ici. Sans cela, l'application affiche les nouvelles réponses seulement quand elle est ouverte.",
|
||||
"push_on": "Les notifications sont activées pour cette instance.",
|
||||
"regenerate": "Régénérer",
|
||||
"settings_about": "À propos",
|
||||
"settings_assistant": "Assistant",
|
||||
"settings_instances": "Instances",
|
||||
"share_default_prompt": "Jetez un œil à ceci.",
|
||||
"share_label": "Demander à LLeMbas",
|
||||
"share_sending": "Envoi à LLeMbas…",
|
||||
"signin_address": "Adresse de l'instance",
|
||||
"signin_code_intro": "Ouvrez l'instance dans le navigateur, connectez-vous et approuvez ce code :",
|
||||
"signin_denied": "La connexion a été refusée.",
|
||||
"signin_expired": "Le code a expiré avant d'être approuvé. Réessayez.",
|
||||
"signin_intro": "Connectez-vous à une instance LLeMbas. Vous approuvez ce téléphone dans le navigateur, comme vous le feriez pour la CLI.",
|
||||
"signin_open_browser": "Ouvrir dans le navigateur",
|
||||
"signin_too_new": "Cette instance utilise une API d'application plus récente que cette application. Mettez à jour l'application.",
|
||||
"signin_too_old": "Cette instance n'a pas encore d'API pour l'application. Elle nécessite LLeMbas 1.7.0 ou une version plus récente.",
|
||||
"theme_moria": "Moria (sombre)",
|
||||
"theme_shire": "Shire (clair)",
|
||||
"theme_system": "Comme le système",
|
||||
"tile_ask": "Demander à LLeMbas",
|
||||
"update_allow_installs": "Autorisez LLeMbas à installer des mises à jour, puis vérifiez à nouveau.",
|
||||
"update_bad_file": "Le téléchargement ne correspondait pas à la version et a été rejeté.",
|
||||
"update_check": "Rechercher une mise à jour",
|
||||
"update_installing": "Installation de %1$s…",
|
||||
"update_none": "C'est la version la plus récente.",
|
||||
"update_unreachable": "La mise à jour n'a pas pu être récupérée."
|
||||
},
|
||||
"hu": {
|
||||
"about_version": "LLeMbas Androidra %1$s",
|
||||
"add_instance": "Példány hozzáadása",
|
||||
"archive": "Archiválás",
|
||||
"assist_hint": "Kérdezzen bármit",
|
||||
"assist_include_screen": "Képernyő hozzáadása",
|
||||
"assist_open_app": "Alkalmazás megnyitása",
|
||||
"assist_open_in_app": "Folytatás az alkalmazásban",
|
||||
"assist_signed_out": "Először jelentkezzen be egy LLeMbas példányba az alkalmazásban.",
|
||||
"assistant_explained": "Tegye az LLeMbas-t a telefon digitális asszisztensévé: válassza ki az Alapértelmezett alkalmazások › Digitális asszisztens alkalmazás alatt. A bekapcsológomb lenyomva tartása, az asszisztens-gesztus vagy a lezárási képernyő parancsikonja ezután a képernyőn lévő tartalom felett nyitja meg.",
|
||||
"assistant_open_settings": "Asszisztens beállításainak megnyitása",
|
||||
"assistant_read_aloud": "Olvassa fel a választ, ha hangos kérdés érkezett",
|
||||
"assistant_samsung": "Samsung telefonokon: Beállítások › Speciális funkciók › Oldalgomb › Nyomva tartás › Digitális asszisztens.",
|
||||
"assistant_temporary": "Az asszisztenses csevegések ideiglenesek",
|
||||
"attach": "Fájl csatolása",
|
||||
"card_allow_once": "Engedélyezés egyszer",
|
||||
"card_answer": "Az Ön válasza",
|
||||
"card_approval": "Engedélyezzük ezt?",
|
||||
"card_reason": "Miért nem? (opcionális)",
|
||||
"channel_asks": "Kérdések és jóváhagyások",
|
||||
"device_name": "LLeMbas Androidra",
|
||||
"effort_off": "Erőfeszítés: kikapcsolva",
|
||||
"empty_agents": "Nincs ügynök-csevegés. Indítson el egyet a webes felületen egy összekapcsolt eszközön.",
|
||||
"empty_chat": "Miről beszéljünk?",
|
||||
"empty_chats": "Még nincs csevegés. Nem mindenki van elveszve, aki bolyong — kezdjen el egyet.",
|
||||
"listening": "Hallgatja…",
|
||||
"loading_line": "Lembas sül…",
|
||||
"mode_manual": "Manual",
|
||||
"more": "Továbbiak",
|
||||
"older": "Korábbi üzenetek",
|
||||
"output_cut": "A kimenet itt lerövidítve jelenik meg. A teljes szöveg a weblapon található.",
|
||||
"plan_approve": "Terv jóváhagyása",
|
||||
"plan_carry_out": "Terv végrehajtása",
|
||||
"plan_what_to_change": "Mi változzon?",
|
||||
"push_enable": "Értesítések bekapcsolása",
|
||||
"push_explained": "Az értesítések a UnifiedPush-on keresztül érkeznek, Google-szolgáltatások nélkül: az Ön által választott elosztó alkalmazás szállítja őket, titkosítva, csak ehhez a telefonhoz.",
|
||||
"push_failed": "Nem választottak elosztót, így az értesítések továbbra is ki vannak kapcsolva.",
|
||||
"push_no_distributor": "Hogy értesítést kapjon, amikor egy válasz elkészül, telepítsen egy UnifiedPush-elosztót, például az ntfy-t, majd jöjjön vissza ide. Ha nincs ilyen, az alkalmazás csak akkor mutatja az új válaszokat, amikor meg van nyitva.",
|
||||
"push_on": "Az értesítések be vannak kapcsolva ehhez a példányhoz.",
|
||||
"regenerate": "Újragenerálás",
|
||||
"settings_about": "Névjegy",
|
||||
"settings_assistant": "Asszisztens",
|
||||
"settings_instances": "Példányok",
|
||||
"share_default_prompt": "Nézze meg ezt.",
|
||||
"share_label": "Kérdés az LLeMbas-tól",
|
||||
"share_sending": "Küldés az LLeMbas-nak…",
|
||||
"signin_address": "A példány címe",
|
||||
"signin_code_intro": "Nyissa meg a példányt a böngészőben, jelentkezzen be, és hagyja jóvá ezt a kódot:",
|
||||
"signin_denied": "A bejelentkezést elutasították.",
|
||||
"signin_expired": "A kód lejárt, mielőtt jóváhagyták volna. Próbálja újra.",
|
||||
"signin_intro": "Jelentkezzen be egy LLeMbas példányba. Ezt a telefont a böngészőben hagyja jóvá, ahogyan a CLI-t is tenné.",
|
||||
"signin_open_browser": "Megnyitás a böngészőben",
|
||||
"signin_too_new": "Ez a példány újabb alkalmazás-API-t használ, mint ez az alkalmazás. Frissítse az alkalmazást.",
|
||||
"signin_too_old": "Ennek a példánynak még nincs alkalmazás-API-ja. LLeMbas 1.7.0 vagy újabb verzió szükséges hozzá.",
|
||||
"theme_moria": "Moria (sötét)",
|
||||
"theme_shire": "Shire (világos)",
|
||||
"theme_system": "A rendszer szerint",
|
||||
"tile_ask": "Kérdés az LLeMbas-tól",
|
||||
"update_allow_installs": "Engedélyezze, hogy az LLeMbas frissítéseket telepítsen, majd ellenőrizze újra.",
|
||||
"update_bad_file": "A letöltés nem egyezett a verzióval, és el lett dobva.",
|
||||
"update_check": "Frissítés keresése",
|
||||
"update_installing": "%1$s telepítése…",
|
||||
"update_none": "Ez a legújabb verzió.",
|
||||
"update_unreachable": "A frissítést nem sikerült letölteni."
|
||||
},
|
||||
"it": {
|
||||
"about_version": "LLeMbas per Android %1$s",
|
||||
"add_instance": "Aggiungi un'istanza",
|
||||
"archive": "Archivia",
|
||||
"assist_hint": "Chiedi qualsiasi cosa",
|
||||
"assist_include_screen": "Includi lo schermo",
|
||||
"assist_open_app": "Apri l'app",
|
||||
"assist_open_in_app": "Continua nell'app",
|
||||
"assist_signed_out": "Accedi prima a un'istanza LLeMbas nell'app.",
|
||||
"assistant_explained": "Rendi LLeMbas l'assistente digitale del telefono: selezionalo in App predefinite › App di assistenza digitale. Tenendo premuto il tasto di accensione, il gesto di assistenza o la scorciatoia della schermata di blocco lo apre quindi sopra qualsiasi cosa sia a schermo.",
|
||||
"assistant_open_settings": "Apri le impostazioni dell'assistente",
|
||||
"assistant_read_aloud": "Leggi la risposta ad alta voce quando la domanda è vocale",
|
||||
"assistant_samsung": "Sui telefoni Samsung: Impostazioni › Funzioni avanzate › Tasto laterale › Pressione prolungata › Assistente digitale.",
|
||||
"assistant_temporary": "Le chat dell'assistente sono temporanee",
|
||||
"attach": "Allega un file",
|
||||
"card_allow_once": "Consenti una volta",
|
||||
"card_answer": "La tua risposta",
|
||||
"card_approval": "Consentire questo?",
|
||||
"card_reason": "Perché no? (facoltativo)",
|
||||
"channel_asks": "Domande e approvazioni",
|
||||
"device_name": "LLeMbas per Android",
|
||||
"effort_off": "Impegno: disattivato",
|
||||
"empty_agents": "Nessuna chat agente. Avviane una dall'interfaccia web su un dispositivo collegato.",
|
||||
"empty_chat": "Di cosa parliamo?",
|
||||
"empty_chats": "Ancora nessuna chat. Non tutti quelli che vagano sono perduti — iniziane una.",
|
||||
"listening": "In ascolto…",
|
||||
"loading_line": "I lembas stanno cuocendo…",
|
||||
"mode_manual": "Manual",
|
||||
"more": "Altro",
|
||||
"older": "Messaggi precedenti",
|
||||
"output_cut": "L'output qui è abbreviato. Lo trovi per intero sulla pagina web.",
|
||||
"plan_approve": "Approva il piano",
|
||||
"plan_carry_out": "Esegui il piano",
|
||||
"plan_what_to_change": "Cosa dovrebbe cambiare?",
|
||||
"push_enable": "Attiva le notifiche",
|
||||
"push_explained": "Le notifiche arrivano tramite UnifiedPush, senza servizi Google: l'app di distribuzione che hai scelto le trasporta, cifrate solo per questo telefono.",
|
||||
"push_failed": "Non è stato scelto nessun distributore, quindi le notifiche sono ancora disattivate.",
|
||||
"push_no_distributor": "Per essere avvisato quando una risposta è pronta, installa un distributore UnifiedPush come ntfy, poi torna qui. Senza uno, l'app mostra le nuove risposte solo quando è aperta.",
|
||||
"push_on": "Le notifiche sono attive per questa istanza.",
|
||||
"regenerate": "Rigenera",
|
||||
"settings_about": "Informazioni",
|
||||
"settings_assistant": "Assistente",
|
||||
"settings_instances": "Istanze",
|
||||
"share_default_prompt": "Dai un'occhiata a questo.",
|
||||
"share_label": "Chiedi a LLeMbas",
|
||||
"share_sending": "Invio a LLeMbas…",
|
||||
"signin_address": "Indirizzo dell'istanza",
|
||||
"signin_code_intro": "Apri l'istanza nel browser, accedi e approva questo codice:",
|
||||
"signin_denied": "L'accesso è stato rifiutato.",
|
||||
"signin_expired": "Il codice è scaduto prima di essere approvato. Riprova.",
|
||||
"signin_intro": "Accedi a un'istanza LLeMbas. Approvi questo telefono nel browser, come faresti con la CLI.",
|
||||
"signin_open_browser": "Apri nel browser",
|
||||
"signin_too_new": "Questa istanza usa un'API per l'app più recente di questa app. Aggiorna l'app.",
|
||||
"signin_too_old": "Questa istanza non ha ancora un'API per l'app. Richiede LLeMbas 1.7.0 o una versione più recente.",
|
||||
"theme_moria": "Moria (scuro)",
|
||||
"theme_shire": "Shire (chiaro)",
|
||||
"theme_system": "Come il sistema",
|
||||
"tile_ask": "Chiedi a LLeMbas",
|
||||
"update_allow_installs": "Consenti a LLeMbas di installare gli aggiornamenti, poi controlla di nuovo.",
|
||||
"update_bad_file": "Il download non corrispondeva alla versione ed è stato scartato.",
|
||||
"update_check": "Controlla aggiornamenti",
|
||||
"update_installing": "Installazione di %1$s…",
|
||||
"update_none": "Questa è la versione più recente.",
|
||||
"update_unreachable": "Non è stato possibile scaricare l'aggiornamento."
|
||||
},
|
||||
"pl": {
|
||||
"about_version": "LLeMbas na Androida %1$s",
|
||||
"add_instance": "Dodaj instancję",
|
||||
"archive": "Archiwizuj",
|
||||
"assist_hint": "Zapytaj o cokolwiek",
|
||||
"assist_include_screen": "Dołącz ekran",
|
||||
"assist_open_app": "Otwórz aplikację",
|
||||
"assist_open_in_app": "Kontynuuj w aplikacji",
|
||||
"assist_signed_out": "Najpierw zaloguj się do instancji LLeMbas w aplikacji.",
|
||||
"assistant_explained": "Ustaw LLeMbas jako cyfrowego asystenta telefonu: wybierz go w Domyślne aplikacje › Aplikacja asystenta cyfrowego. Przytrzymanie przycisku zasilania, gest asystenta lub skrót z ekranu blokady otwiera go wtedy nad tym, co jest na ekranie.",
|
||||
"assistant_open_settings": "Otwórz ustawienia asystenta",
|
||||
"assistant_read_aloud": "Odczytaj odpowiedź na głos, gdy pytanie było głosowe",
|
||||
"assistant_samsung": "W telefonach Samsung: Ustawienia › Funkcje zaawansowane › Przycisk boczny › Naciśnięcie i przytrzymanie › Asystent cyfrowy.",
|
||||
"assistant_temporary": "Czaty asystenta są tymczasowe",
|
||||
"attach": "Załącz plik",
|
||||
"card_allow_once": "Zezwól raz",
|
||||
"card_answer": "Twoja odpowiedź",
|
||||
"card_approval": "Zezwolić na to?",
|
||||
"card_reason": "Czemu nie? (opcjonalnie)",
|
||||
"channel_asks": "Pytania i zatwierdzenia",
|
||||
"device_name": "LLeMbas na Androida",
|
||||
"effort_off": "Wysiłek: wyłączony",
|
||||
"empty_agents": "Brak czatów agenta. Zacznij jeden z interfejsu webowego na połączonym urządzeniu.",
|
||||
"empty_chat": "O czym porozmawiamy?",
|
||||
"empty_chats": "Nie ma jeszcze czatów. Nie każdy, kto błądzi, jest zgubiony — zacznij jeden.",
|
||||
"listening": "Słucham…",
|
||||
"loading_line": "Lembasy się pieczą…",
|
||||
"mode_manual": "Manual",
|
||||
"more": "Więcej",
|
||||
"older": "Wcześniejsze wiadomości",
|
||||
"output_cut": "Wynik jest tu skrócony. Cały znajduje się na stronie internetowej.",
|
||||
"plan_approve": "Zatwierdź plan",
|
||||
"plan_carry_out": "Wykonaj plan",
|
||||
"plan_what_to_change": "Co powinno się zmienić?",
|
||||
"push_enable": "Włącz powiadomienia",
|
||||
"push_explained": "Powiadomienia przychodzą przez UnifiedPush, bez usług Google: niesie je wybrana aplikacja dystrybucyjna, zaszyfrowane tylko dla tego telefonu.",
|
||||
"push_failed": "Nie wybrano dystrybutora, więc powiadomienia są wciąż wyłączone.",
|
||||
"push_no_distributor": "Aby dostawać informacje, kiedy odpowiedź jest gotowa, zainstaluj dystrybutora UnifiedPush, na przykład ntfy, a potem wróć tutaj. Bez niego aplikacja pokazuje nowe odpowiedzi tylko wtedy, gdy jest otwarta.",
|
||||
"push_on": "Powiadomienia są włączone dla tej instancji.",
|
||||
"regenerate": "Wygeneruj ponownie",
|
||||
"settings_about": "Informacje",
|
||||
"settings_assistant": "Asystent",
|
||||
"settings_instances": "Instancje",
|
||||
"share_default_prompt": "Zobacz to.",
|
||||
"share_label": "Zapytaj LLeMbas",
|
||||
"share_sending": "Wysyłanie do LLeMbas…",
|
||||
"signin_address": "Adres instancji",
|
||||
"signin_code_intro": "Otwórz instancję w przeglądarce, zaloguj się i zatwierdź ten kod:",
|
||||
"signin_denied": "Logowanie zostało odrzucone.",
|
||||
"signin_expired": "Kod wygasł, zanim został zatwierdzony. Spróbuj ponownie.",
|
||||
"signin_intro": "Zaloguj się do instancji LLeMbas. Ten telefon zatwierdza się w przeglądarce, tak jak CLI.",
|
||||
"signin_open_browser": "Otwórz w przeglądarce",
|
||||
"signin_too_new": "Ta instancja używa nowszego API aplikacji niż ta aplikacja. Zaktualizuj aplikację.",
|
||||
"signin_too_old": "Ta instancja nie ma jeszcze API aplikacji. Wymaga LLeMbas 1.7.0 lub nowszego.",
|
||||
"theme_moria": "Moria (ciemny)",
|
||||
"theme_shire": "Shire (jasny)",
|
||||
"theme_system": "Jak system",
|
||||
"tile_ask": "Zapytaj LLeMbas",
|
||||
"update_allow_installs": "Zezwól LLeMbas na instalowanie aktualizacji, a potem sprawdź ponownie.",
|
||||
"update_bad_file": "Pobrany plik nie zgadzał się z wersją i został odrzucony.",
|
||||
"update_check": "Sprawdź aktualizację",
|
||||
"update_installing": "Instalowanie %1$s…",
|
||||
"update_none": "To jest najnowsza wersja.",
|
||||
"update_unreachable": "Nie udało się pobrać aktualizacji."
|
||||
},
|
||||
"sk": {
|
||||
"about_version": "LLeMbas pre Android %1$s",
|
||||
"add_instance": "Pridať inštanciu",
|
||||
"archive": "Archivovať",
|
||||
"assist_hint": "Spýtajte sa na čokoľvek",
|
||||
"assist_include_screen": "Zahrnúť obrazovku",
|
||||
"assist_open_app": "Otvoriť aplikáciu",
|
||||
"assist_open_in_app": "Pokračovať v aplikácii",
|
||||
"assist_signed_out": "Najprv sa v aplikácii prihláste do inštancie LLeMbas.",
|
||||
"assistant_explained": "Nastavte LLeMbas ako digitálneho asistenta telefónu: zvoľte ho v Predvolené aplikácie › Digitálny asistent. Podržanie tlačidla napájania, gesto asistenta alebo skratka na uzamknutej obrazovke ho potom otvorí nad tým, čo je práve na obrazovke.",
|
||||
"assistant_open_settings": "Otvoriť nastavenia asistenta",
|
||||
"assistant_read_aloud": "Prečítať odpoveď nahlas, keď sa spýtate hlasom",
|
||||
"assistant_samsung": "Na telefónoch Samsung: Nastavenia › Rozšírené funkcie › Tlačidlo na boku › Stlačenie a podržanie › Digitálny asistent.",
|
||||
"assistant_temporary": "Konverzácie s asistentom sú dočasné",
|
||||
"attach": "Priložiť súbor",
|
||||
"card_allow_once": "Povoliť raz",
|
||||
"card_answer": "Vaša odpoveď",
|
||||
"card_approval": "Povoliť to?",
|
||||
"card_reason": "Prečo nie? (nepovinné)",
|
||||
"channel_asks": "Otázky a schválenia",
|
||||
"device_name": "LLeMbas pre Android",
|
||||
"effort_off": "Úsilie: vypnuté",
|
||||
"empty_agents": "Žiadne konverzácie s agentom. Spustite jednu z webového rozhrania na prepojenom zariadení.",
|
||||
"empty_chat": "O čom sa pozhovárame?",
|
||||
"empty_chats": "Zatiaľ žiadne konverzácie. Nie všetci, čo blúdia, sú stratení — začnite jednu.",
|
||||
"listening": "Počúvam…",
|
||||
"loading_line": "Pečú sa lembasy…",
|
||||
"mode_manual": "Manual",
|
||||
"more": "Viac",
|
||||
"older": "Staršie správy",
|
||||
"output_cut": "Výstup je tu skrátený. Celý nájdete na webovej stránke.",
|
||||
"plan_approve": "Schváliť plán",
|
||||
"plan_carry_out": "Vykonať plán",
|
||||
"plan_what_to_change": "Čo by sa malo zmeniť?",
|
||||
"push_enable": "Zapnúť upozornenia",
|
||||
"push_explained": "Upozornenia chodia cez UnifiedPush, bez služieb Google: doručuje ich distribučná aplikácia, ktorú ste zvolili, zašifrované len pre tento telefón.",
|
||||
"push_failed": "Nebol zvolený žiadny distributor, takže upozornenia sú stále vypnuté.",
|
||||
"push_no_distributor": "Aby ste sa dozvedeli, že je odpoveď hotová, nainštalujte distributora UnifiedPush, napríklad ntfy, a potom sa vráťte sem. Bez neho aplikácia nové odpovede ukáže, len keď je otvorená.",
|
||||
"push_on": "Upozornenia sú pre túto inštanciu zapnuté.",
|
||||
"regenerate": "Vygenerovať znova",
|
||||
"settings_about": "O aplikácii",
|
||||
"settings_assistant": "Asistent",
|
||||
"settings_instances": "Inštancie",
|
||||
"share_default_prompt": "Pozrite sa na toto.",
|
||||
"share_label": "Spýtať sa LLeMbas",
|
||||
"share_sending": "Odosiela sa do LLeMbas…",
|
||||
"signin_address": "Adresa inštancie",
|
||||
"signin_code_intro": "Otvorte inštanciu v prehliadači, prihláste sa a schváľte tento kód:",
|
||||
"signin_denied": "Prihlásenie bolo odmietnuté.",
|
||||
"signin_expired": "Kód vypršal skôr, než bol schválený. Skúste to znova.",
|
||||
"signin_intro": "Prihláste sa do inštancie LLeMbas. Tento telefón schválite v prehliadači, tak ako by ste schválili CLI.",
|
||||
"signin_open_browser": "Otvoriť v prehliadači",
|
||||
"signin_too_new": "Táto inštancia používa novšie API pre aplikácie než táto aplikácia. Aktualizujte aplikáciu.",
|
||||
"signin_too_old": "Táto inštancia ešte nemá API pre aplikácie. Potrebuje LLeMbas 1.7.0 alebo novší.",
|
||||
"theme_moria": "Moria (tmavá)",
|
||||
"theme_shire": "Shire (svetlá)",
|
||||
"theme_system": "Podľa systému",
|
||||
"tile_ask": "Spýtať sa LLeMbas",
|
||||
"update_allow_installs": "Povoľte aplikácii LLeMbas instalovať aktualizácie a potom to skontrolujte znova.",
|
||||
"update_bad_file": "Stiahnutý súbor nezodpovedal verzii a bol zahodený.",
|
||||
"update_check": "Skontrolovať aktualizáciu",
|
||||
"update_installing": "Inštaluje sa %1$s…",
|
||||
"update_none": "Toto je najnovšia verzia.",
|
||||
"update_unreachable": "Aktualizáciu sa nepodarilo stiahnuť."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
|
||||
dependencyResolutionManagement {
|
||||
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.name = "LLeMbas-Android"
|
||||
include(":app")
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"tag": "v1.6.0",
|
||||
"commit": "566af1ac16b9fd6f440ebadc6b4a9769678da491",
|
||||
"sha256": "7f9d6d4c24b4ea34d17761a017a39a1eb19c4a9f21b889b7ad7d22c7b8766594"
|
||||
}
|
||||
Reference in new issue
Block a user